내장 함수¶
파이썬 인터프리터에는 항상 사용할 수 있는 여러 함수와 타입이 내장되어 있습니다. 여기에 알파벳 순서로 나열되어 있습니다.
내장 함수 |
|||
|---|---|---|---|
- abs(number, /)¶
숫자의 절대값을 반환합니다. 인자는 정수, 부동 소수점 수 또는
__abs__()를 구현하는 객체일 수 있습니다. 인자가 복소수인 경우 그 크기(magnitude)가 반환됩니다.
- aiter(async_iterable, /)¶
- aiter(callable, /, stop_value, *, stop_exception=StopAsyncIteration)
- aiter(callable, /, *, stop_exception)
비동기 이터레이터 객체를 반환합니다. 첫 번째 인자는 다른 인자의 존재 여부에 따라 매우 다르게 해석됩니다. 다른 인자가 없는 경우, 단일 인자는 반드시 비동기 이터러블 이어야 하며, 결과는
x.__aiter__()를 호출한 것과 동일합니다.stop_value 또는 stop_exception 이 제공되면 첫 번째 인자는 호출 가능한 객체여야 합니다. 이 경우 생성된 비동기 이터레이터는
__anext__()메서드를 호출할 때마다 인자 없이 callable 을 호출하고 그 결과를 대기(await)합니다. 만약 대기한 값이 stop_value 와 같거나, 호출 시 stop_exception 과 일치하는 예외가 발생하면StopAsyncIteration이 발생하며, 그렇지 않으면 해당 값이 반환됩니다. callable은__anext__()의 결과가 대기될 때만 호출됩니다.stop_exception 은 예외 클래스 또는 예외 클래스들의 튜플입니다. stop_value 가 지정되지 않은 경우, callable이 예외를 발생시킬 때에만 반복이 중단됩니다. 만약 callable이 stop_exception 과 일치하지 않는
StopAsyncIteration을 발생시키면, 비동기 제너레이터와 마찬가지로RuntimeError로 대체됩니다(see PEP 525).예를 들어, 파일 끝에 도달할 때까지 비동기 스트림에서 고정된 크기의 청크를 읽어오는 경우:
from functools import partial async for chunk in aiter(partial(reader.read, 1024), b''): process_chunk(chunk)
또는, 셧다운될 때까지
asyncio.Queue를 소비하는 경우:from asyncio import QueueShutDown async for item in aiter(queue.get, stop_exception=QueueShutDown): process_item(item)
Added in version 3.10.
버전 3.16.0a0 (unreleased)에서 변경: stop_value 및 stop_exception 매개 변수가 추가되었습니다.
- all(iterable, /)¶
iterable 의 모든 요소가 참이면(또는 iterable이 비어있으면)
True를 반환합니다. 다음과 동일합니다:def all(iterable): for element in iterable: if not element: return False return True
- awaitable anext(async_iterator, /)¶
- awaitable anext(async_iterator, default, /)
When awaited, return the next item from the given asynchronous iterator, or default if given and the iterator is exhausted.
이것은
next()내장 함수의 비동기 변체이며, 유사하게 동작합니다.이것은 async_iterator 의
__anext__()메서드를 호출하여 어웨이터블 을 반환합니다. 이를 대기하면 이터레이터의 다음 값을 반환합니다. default 가 제공된 경우 이터레이터가 소진되면 해당 값을 반환하고, 그렇지 않으면StopAsyncIteration이 발생합니다.Added in version 3.10.
- any(iterable, /)¶
iterable 의 요소 중 어느 하나라도 참이면
True를 반환합니다. iterable이 비어있으면False를 반환합니다. 다음과 동일합니다:def any(iterable): for element in iterable: if element: return True return False
- ascii(object, /)¶
repr()과 마찬가지로 객체의 출력 가능한 표현을 포함하는 문자열을 반환하되,repr()이 반환한 문자열 내의 비-ASCII 문자를\x,\u또는\U이스케이프를 사용하여 처리합니다. 이는 파이썬 2에서repr()이 반환하는 것과 유사한 문자열을 생성합니다.
- bin(integer, /)¶
정수형 숫자를 “0b” 접두사가 붙은 이진수 문자열로 변환합니다. 결과는 유효한 파이썬 표현식입니다. integer 가 파이썬
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')
음수 값을 2의 보수 형태로 표현하려면
enum.bin()을 참조하십시오.더 자세한 정보는
format()을 참조하십시오.
- class bool(object=False, /)¶
Boolean 값, 즉
True또는False중 하나를 반환합니다. 인자는 표준 진리 테스트 절차 를 사용하여 변환됩니다. 인자가 거짓이거나 생략된 경우False를 반환하고, 그렇지 않으면True를 반환합니다.bool클래스는int의 하위 클래스이며(참조: Numeric Types — int, float, complex), 더 이상 하위 클래스로 확장될 수 없습니다. 유일한 인스턴스는False와True입니다(참조: Boolean Type - bool).버전 3.7에서 변경: 해당 매개 변수는 이제 위치 전용(positional-only)입니다.
- breakpoint(*args, **kws)¶
이 함수는 호출 시점에서 디버거를 실행합니다. 구체적으로,
args와kws를 그대로 전달하며sys.breakpointhook()를 호출합니다. 기본적으로sys.breakpointhook()는 인자가 없는 상태에서pdb.set_trace()를 호출합니다. 이 경우, 디버거에 진입하기 위해pdb를 명시적으로 임포트하거나 코드를 많이 작성할 필요가 없는 편의용 함수입니다. 하지만sys.breakpointhook()을 다른 함수로 설정하면breakpoint()가 이를 자동으로 호출하여 원하는 디버거를 선택할 수 있습니다.sys.breakpointhook()에 접근할 수 없는 경우 이 함수는RuntimeError를 발생시킵니다.기본적으로
breakpoint()의 동작은PYTHONBREAKPOINT환경 변수로 변경할 수 있습니다. 사용에 관한 자세한 내용은sys.breakpointhook()을 참조하십시오.sys.breakpointhook()이 교체된 경우 동작이 보장되지 않을 수 있음에 유의하십시오.breakpointhook인자를 사용하여 감사 이벤트builtins.breakpoint를 발생시킵니다.Added in version 3.7.
- class bytearray(source=b'')
- class bytearray(source, encoding, errors='strict')
새로운 바이트 배열을 반환합니다.
bytearray클래스는 0 <= x < 256 범위의 정수로 구성된 가변 시퀀스입니다. 이 클래스는 Mutable Sequence Types 에 설명된 가변 시퀀스의 일반적인 메서드들과 Bytes and Bytearray Operations 에서 확인되는bytes타입의 대부분의 메서드를 보유합니다.선택적 source 매개 변수는 배열을 다음과 같은 몇 가지 방식으로 초기화하는 데 사용될 수 있습니다:
이 값이 문자열 인 경우, encoding (그리고 선택적으로 errors) 매개 변수도 함께 제공해야 합니다.
bytearray()는 그 후str.encode()를 사용하여 문자열을 바이트로 변환합니다.이 값이 정수 인 경우, 배열은 해당 크기를 가지며 널 바이트로 초기화됩니다.
이 값이 버퍼 프로토콜 을 따르는 객체인 경우, 해당 객체의 읽기 전용 버퍼가 바이트 배열을 초기화하는 데 사용됩니다.
이 값이 이터러블 인 경우, 반드시
0 <= x < 256범위의 정수들로 구성된 이터러블이어야 하며, 이들은 배열의 초기 내용으로 사용됩니다.
인자가 없으면 크기가 0인 배열이 생성됩니다.
Binary Sequence Types — bytes, bytearray, memoryview 및 Bytearray Objects 도 참조하십시오.
- class bytes(source=b'')
- class bytes(source, encoding, errors='strict')
0 <= x < 256범위의 정수로 구성된 불변 시퀀스인 새로운 “bytes” 객체를 반환합니다.bytes는bytearray의 불변 버전이며, 동일한 비변이 메서드와 동일한 인덱싱 및 슬라이싱 동작을 가집니다.이에 따라 생성자 인수는
bytearray()용으로 해석됩니다.바이트 객체는 리터럴로도 생성할 수 있으며, 문자열과 바이트열 리터럴 를 참조하십시오.
Binary Sequence Types — bytes, bytearray, memoryview, Bytes Objects, 그리고 Bytes and Bytearray Operations 도 참조하십시오.
- callable(object, /)¶
Return
Trueif the object argument appears callable,Falseif not. If this returnsTrue, it is still possible that a call fails, but if it isFalse, 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.Added in version 3.2: 이 함수는 파이썬 3.0에서 처음 삭제되었다가 파이썬 3.2에서 다시 도입되었습니다.
- chr(codepoint, /)¶
지정된 유니코드 코드 포인트를 가진 문자를 나타내는 문자열을 반환합니다. 예를 들어,
chr(97)은'a'를 반환하고,chr(8364)는'€'를 반환합니다. 이는ord()의 역연산입니다.인자의 유효 범위는 0부터 1,114,111(16진수 0x10FFFF)까지입니다. 이 범위를 벗어나는 경우
ValueError가 발생합니다.
- @classmethod¶
메서드를 클래스 메서드로 변환합니다.
클래스 메서드는 인스턴스 메서드가 인스턴스를 받는 것과 마찬가지로 클래스를 암시적인 첫 번째 인자로 받습니다. 클래스 메서드를 선언하려면 다음 관용구를 사용하십시오:
class C: @classmethod def f(cls, arg1, arg2): ...
@classmethod형태는 함수 데코레이터 입니다. 자세한 내용은 함수 정의 을 참조하십시오.클래스 메서드는 클래스(예:
C.f()) 또는 인스턴스(예:C().f())에서 호출할 수 있습니다. 인스턴스는 그 클래스 정보만 제외하고는 무시됩니다. 파생 클래스에서 클래스 메서드가 호출되면 파생 클래스 객체가 암시적인 첫 번째 인자로 전달됩니다.클래스 메서드는 C++이나 Java의 static 메서드와는 다릅니다. 그것들을 원하신다면 이 섹션의
staticmethod()를 참조하십시오. 클래스 메서드에 대한 더 자세한 정보는 표준형 계층 를 참조하십시오.버전 3.9에서 변경: 클래스 메서드는 이제
property()와 같은 다른 디스크립터 를 래핑할 수 있습니다.버전 3.10에서 변경: 클래스 메서드는 이제 메서드 어트리뷰트(
__module__,__name__,__qualname__,__doc__및__annotations__)를 상속받으며 새로운__wrapped__어트리뷰트를 가집니다.버전 3.11부터 사용 지원 중단(deprecated), 버전 3.13에서 제거됨: 클래스 메서드는 이제
property()와 같은 다른 디스크립터 를 래핑할 수 없습니다.
- compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1, *, module=None)¶
source 를 코드 또는 AST 객체로 컴파일합니다. 코드 객체는
exec()또는eval()에 의해 실행될 수 있습니다. source 는 일반 문자열, 바이트 문자열 또는 AST 객체일 수 있습니다. AST 객체를 다루는 방법에 대한 정보는ast모듈 문서를 참조하십시오.filename 인자는 코드가 읽힌 파일을 지정해야 합니다. 파일에서 읽히지 않은 경우 인식 가능한 값(일반적으로
'<string>')을 전달하십시오.mode 인자는 어떤 종류의 코드가 컴파일되어야 하는지 지정합니다. source 가 문장 시퀀스로 구성된 경우
'exec', 단일 표현식으로 구성된 경우'eval', 단일 대화형 문장으로 구성된 경우'single'(이 경우,None이외의 값으로 평가되는 표현식 문장이 출력됨)이 될 수 있습니다.선택적 인자인 flags 와 dont_inherit 는 어떤 컴파일러 옵션 이 활성화되고 어떤 미래 기능 이 허용될지 제어합니다. 둘 중 어느 것도 없거나(또는 둘 다 0인 경우) 코드는
compile()을 호출하는 코드를 영향을 미치는 것과 동일한 플래그로 컴파일됩니다. flags 인자가 제공되고 dont_inherit 이 없거나 0인 경우, 기본적으로 사용될 것들에 더해 flags 인자가 지정한 컴파일러 옵션과 미래 문들이 사용됩니다. dont_inherit 이 0이 아닌 정수이면, flags 인자의 값은 그것이며, 주변 코드의 플래그(미래 기능 및 컴파일러 옵션)는 무시됩니다.컴파일러 옵션과 미래 문은 비트 단위 OR 연산으로 결합하여 여러 옵션을 지정할 수 있는 비트로 명시됩니다. 특정 미래 기능을 지정하는 데 필요한 비트 필드는
__future__모듈의_Feature인스턴스에 있는compiler_flag어트리뷰트에서 찾을 수 있습니다. 컴파일러 플래그 는ast모듈에서PyCF_접두사로 찾을 수 있습니다.optimize 인자는 컴파일러의 최적화 수준을 지정합니다. 기본값인
-1은-O옵션에 의해 제공되는 인터프리터의 최적화 수준을 선택합니다. 명시적인 수준은0(최적화 없음;__debug__가 True),1(assert 제거,__debug__가 False), 또는2(docstring도 제거)입니다.선택적 인자인 module 은 모듈 이름을 지정합니다. 이는 모듈 이름에 의한 필터 구문 경고를 명확하게 구분하기 위해 필요합니다.
이 함수는 컴파일된 소스가 유효하지 않을 경우
SyntaxError또는ValueError를 발생시킵니다.Python 코드를 AST 표현으로 파싱하려면
ast.parse()를 참조하십시오.인자
source및filename을 사용하여 감사 이벤트compile을 발생시킵니다. 이 이벤트는 암시적 컴파일에 의해서도 발생할 수 있습니다.참고
'single'또는'eval'모드에서 여러 줄의 코드가 포함된 문자열을 컴파일할 때, 입력은 최소 하나의 줄 바꿈 문자로 끝나야 합니다. 이는code모듈에서 불완전한 문장과 완료된 문장을 감지하기 용이하도록 하기 위함입니다.경고
Python의 AST 컴파일러에 있는 스택 깊이 제한으로 인해, 충분히 크고 복잡한 문자열을 AST 객체로 컴파일할 때 Python 인터프리터가 충돌할 수 있습니다.
버전 3.2에서 변경: Windows 및 Mac의 줄 바꿈을 허용합니다. 또한,
'exec'모드에서 입력이 더 이상 줄 바꿈으로 끝나지 않아도 됩니다. optimize 매개변수가 추가되었습니다.버전 3.5에서 변경: 이전에는 source 에서 널 바이트를 발견할 때
TypeError가 발생했습니다.Added in version 3.8: 이제 플래그에
ast.PyCF_ALLOW_TOP_LEVEL_AWAIT``를 전달하여 최상위 수준의 ``await,async for,async with지원을 활성화할 수 있습니다.Added in version 3.15: module 매개변수가 추가되었습니다.
- class complex(number=0, /)¶
- class complex(string, /)
- class complex(real=0, imag=0)
단일 문자열이나 숫자를 복소수로 변환하거나, 실수부와 허수부로부터 복소수를 생성합니다.
예시:
>>> complex('+1.23') (1.23+0j) >>> complex('-4.5j') -4.5j >>> complex('-1.23+4.5j') (-1.23+4.5j) >>> complex('\t( -1.23+4.5J )\n') (-1.23+4.5j) >>> complex('-Infinity+NaNj') (-inf+nanj) >>> complex(1.23) (1.23+0j) >>> complex(imag=-4.5) -4.5j >>> complex(-1.23, 4.5) (-1.23+4.5j)
인자가 문자열인 경우, 이 문자열은 실수부(
float()와 동일한 형식), 허부(동일한 형식이되'j''또는'J''접미사가 붙음), 또는 둘 다를 포함해야 합니다(이 경우 허부의 부호는 필수입니다). 문자열은 선택적으로 공백과 둥근 괄호'('및')'로 둘러싸일 수 있으며, 이들은 무시됩니다. 문자열은'+','-','j''또는'J''접미사, 그리고 십진수 사이의 공백을 포함해서는 안 됩니다. 예를 들어,complex('1+2j')는 허용되지만complex('1 + 2j')는ValueError를 발생시킵니다. 더 정확하게는, 입력은 괄호와 앞뒤 공백이 제거된 후 다음 문법의complexvalue생성 규칙을 따라야 합니다:complexvalue:
floatvalue|floatvalue("j" | "J") |floatvaluesignabsfloatvalue("j" | "J")인자가 숫자라면, 이 생성자는
int및float와 같은 숫자 변환으로 작동합니다. 일반적인 Python 객체x에 대해complex(x)는x.__complex__()를 호출합니다. 만약__complex__()가 정의되어 있지 않으면__float__()를 호출합니다. 만약__float__()도 정의되어 있지 않으면__index__()를 호출합니다.두 개의 인자가 제공되거나 키워드 인자가 사용되는 경우, 각 인자는 임의의 숫자 타입(복소수 포함)이 될 수 있습니다. 두 인자가 모두 실수인 경우, 실수 성분이 real 이고 허수 성분이 imag 인 복소수를 반환합니다. 두 인자가 모두 복소수이면, 실수 성분이
real.real-imag.imag이고 허수 성분이real.imag+imag.real인 복소수를 반환합니다. 인자 중 하나가 실수인 경우, 위의 표현식에서 해당 인자의 실수 성분만 사용됩니다.단일 숫자 인자만 수락하는
complex.from_number()도 참조하십시오.모든 인자가 생략되면
0j를 반환합니다.복소형은 Numeric Types — int, float, complex 에 설명되어 있습니다.
버전 3.6에서 변경: 코드 리터럴과 같이 밑줄로 숫자를 그룹화하는 것이 허용됩니다.
버전 3.8에서 변경:
__complex__()및__float__()가 정의되어 있지 않으면__index__()를 사용합니다.버전 3.14부터 폐지됨: 복소수를 real 또는 imag 인자로 전달하는 방식은 이제 더 이상 권장되지 않습니다. 복소수는 단일 위치 인자로만 전달해야 합니다.
- delattr(object, name, /)¶
This is a relative of
setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example,delattr(x, 'foobar')is equivalent todel x.foobar. name need not be a Python identifier (seesetattr()).
- class dict(**kwargs)
- class dict(mapping, /, **kwargs)
- class dict(iterable, /, **kwargs)
새 딕셔너리를 생성합니다.
dict객체는 딕셔너리 클래스입니다. 이 클래스에 대한 설명은 Mapping types — dict, frozendict 을 참조하십시오.다른 컨테이너의 경우 내장된
frozendict,list,set,tuple클래스 및collections모듈을 참조하십시오.
- dir()¶
- 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__', '__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)¶
enumerate 객체를 반환합니다. iterable 은 시퀀스, iterator, 또는 다른 반복을 지원하는 객체여야 합니다.
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(iterable, start=0): n = start for elem in iterable: yield n, elem n += 1
- eval(source, /, globals=None, locals=None)¶
- 매개변수:
source (
str| code object) – 파이썬 표현식.globals (
dict|frozendict|None) – 전역 네임스페이스 (기본값:None).locals (mapping |
None) – 지역 네임스페이스 (기본값:None).
- 반환:
평가된 표현식의 결과.
- raised:
구문 오류는 예외로 보고됩니다.
경고
이 함수는 임의의 코드를 실행합니다. 신뢰할 수 없는 사용자 입력으로 이 함수를 호출하면 보안 취약점이 발생할 수 있습니다.
The source argument is parsed and evaluated as a Python expression (technically speaking, an expression list) using the globals and locals mappings as global and local namespace. If the globals dictionary is present and does not contain a value for the key
__builtins__, a reference to the dictionary of the built-in modulebuiltinsis inserted under that key before source is parsed. Overriding__builtins__can be used to restrict or change the available names, but this is not a security mechanism: the executed code can still access all builtins. If the locals mapping is omitted it defaults to the globals dictionary. If both mappings are omitted, the source is executed with the globals and locals in the environment whereeval()is called. Note, eval() will only have access to the nested scopes (non-locals) in the enclosing environment if they are already referenced in the scope that is callingeval()(e.g. via anonlocalstatement).예제:
>>> x = 1 >>> eval('x+1') 2
>>> eval("1, 2") (1, 2)
이 함수는 임의의 코드 객체(예를 들어
compile()에 의해 생성된 객체)를 실행하는 데에도 사용될 수 있습니다. 이 경우, 문자열 대신 코드 객체를 전달하십시오. 코드 객체가 mode 인자로'exec'를 사용하여 컴파일된 경우,eval()의 반환값은None이 됩니다.힌트: 문장의 동적 실행은
exec()함수에 의해 지원됩니다.globals()및locals()함수는 각각 현재의 전역 및 지역 딕셔너리를 반환하며, 이는eval()또는exec()에서 사용하기 위해 전달하는 데 유용할 수 있습니다.제공된 source가 문자열인 경우, 앞뒤 공백과 탭이 제거됩니다.
리터럴만 포함된 표현이 포함된 문자열을 평가하는 함수를 보려면
ast.literal_eval()을 참조하십시오.코드 객체를 인자로 하여 auditing event
exec을 발생시킵니다. 코드 컴파일 이벤트도 발생할 수 있습니다.버전 3.13에서 변경: globals*와 *locals 인자를 이제 키워드로 전달할 수 있습니다.
버전 3.13에서 변경: 기본 locals 네임스페이스의 의미가
locals()내장 함수에 기술된 대로 조정되었습니다.버전 3.15에서 변경: globals 는 이제
frozendict가 될 수 있습니다.
- exec(source, /, globals=None, locals=None, *, closure=None)¶
경고
이 함수는 임의의 코드를 실행합니다. 신뢰할 수 없는 사용자 입력으로 이 함수를 호출하면 보안 취약점이 발생할 수 있습니다.
이 함수는 파이썬 코드의 동적 실행을 지원합니다. source 는 문자열 또는 코드 객체여야 합니다. 문자열인 경우, 해당 문자열은 파이썬 문장 세트로 파싱되어 실행됩니다(구문 오류가 발생하지 않는 한). [1] 코드 객체인 경우, 단순히 실행됩니다. 모든 경우에 실행되는 코드는 파일 입력으로서 유효해야 합니다(참조 매뉴얼의 파일 입력 섹션 참조).
nonlocal,yield, 그리고return문은exec()함수에 전달된 코드의 문맥이라 하더라도 함수 정의 밖에서는 사용될 수 없음을 유의하십시오. 반환값은None입니다.모든 경우에 선택적 부분이 생략되면 코드는 현재 범위에서 실행됩니다. globals 만 제공되는 경우, 이는 딕셔너리여야 하며(딕셔너리의 서브클래스가 아니어야 함), 전역 및 지역 변수 모두에 사용됩니다. globals 와 locals 가 모두 제공되는 경우, 각각 전역 및 지역 변수에 사용됩니다. 제공될 경우, locals 는 어떤 매핑 객체든 될 수 있습니다. 모듈 수준에서는 globals와 locals가 동일한 딕셔너리임을 기억하십시오.
참고
exec가 globals 와 locals 로 두 개의 개별 객체를 받는 경우, 코드는 클래스 정의 내에 포함된 것처럼 실행됩니다. 이는 실행되는 코드에서 정의된 함수와 클래스가 최상위 수준에서 할당된 변수에 액세스할 수 없음을 의미합니다(클래스 정의에서 ‘최상위’ 변수는 클래스 변수로 취급되기 때문입니다).globals 딕셔너리가
__builtins__키에 대한 값을 포함하지 않는 경우, 내장 모듈builtins의 딕셔너리 참조가 해당 키에 삽입됩니다.__builtins__를 재정의하여 사용 가능한 이름을 제한하거나 변경할 수 있지만, 이는 성능이나 보안 을 위한 기능이 아닙니다. 실행되는 코드는 여전히 모든 내장 기능을 접근할 수 있습니다.closure 인자는 클로저(cellvars의 튜플)를 지정합니다. 이는 object 가 free (closure) variables 를 포함하는 코드 객체인 경우에만 유효합니다. 튜플의 길이는 코드 객체의
co_freevars속성 길이와 정확히 일치해야 합니다.코드 객체를 인자로 하여 auditing event
exec을 발생시킵니다. 코드 컴파일 이벤트도 발생할 수 있습니다.참고
내장 함수
globals()및locals()는 각각 현재의 전역 및 지역 네임스페이스를 반환하며, 이는exec()의 두 번째 및 세 번째 인자로 사용하기 위해 전달하는 데 유용할 수 있습니다.참고
The default locals act as described for function
locals()below. Pass an explicit locals dictionary if you need to see effects of the code on locals after functionexec()returns.버전 3.11에서 변경: closure 매개변수가 추가되었습니다.
버전 3.13에서 변경: globals*와 *locals 인자를 이제 키워드로 전달할 수 있습니다.
버전 3.13에서 변경: 기본 locals 네임스페이스의 의미가
locals()내장 함수에 기술된 대로 조정되었습니다.버전 3.15에서 변경: globals 는 이제
frozendict가 될 수 있습니다.
- filter(function, iterable, /)¶
function 이 참(True)인 iterable 의 요소들로 이터레이터를 구성합니다. iterable 은 시퀀스, 반복을 지원하는 컨테이너 또는 이터레이터일 수 있습니다. function 이
None인 경우, 항등 함수를 사용하는 것으로 간주하며, 즉 iterable 에서 거짓(False)인 모든 요소가 제거됩니다.참고: function 이
None이 아니면filter(function, iterable)은 제너레이터 표현식(item for item in iterable if function(item))과 동등하며, function 이None이면(item for item in_iterable if item)과 동등합니다.function 이 거짓(False)인 iterable 의 요소들을 반환하는 상보적 함수에 대해서는
itertools.filterfalse()를 참조하십시오.
- class float(number=0.0, /)¶
- class float(string, /)
숫자 또는 문자열로부터 생성된 부동 소수점 숫자를 반환합니다.
예시:
>>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf
인자가 문자열인 경우, 소수점 숫자를 포함해야 하며, 선택적으로 부호가 앞에 붙거나 공백에 둘러싸일 수 있습니다. 선택적인 부호는
'+'또는'-'``일 수 있으며, ``'+'부호는 생성되는 값에 영향을 주지 않습니다. 또한 인자는 NaN(not-a-number), 양의 무한대 또는 음의 무한대를 나타내는 문자열일 수 있습니다. 더 정확하게는, 입력은 앞뒤 공백을 제거한 후 다음 문법의floatvalue생성 규칙을 따라야 합니다.sign: "+" | "-" infinity: "Infinity" | "inf" nan: "nan" digit: <a Unicode decimal digit, i.e. characters in Unicode general category Nd> digitpart:
digit(["_"]digit)* number: [digitpart] "."digitpart|digitpart["."] exponent: ("e" | "E") [sign]digitpartfloatnumber:number[exponent] absfloatvalue:floatnumber|infinity|nanfloatvalue: [sign]absfloatvalue대소문자를 구분하지 않으므로, 예를 들어 “inf”, “Inf”, “INFINITY”, “iNfINity”는 모두 양의 무한대에 대한 허용되는 철자입니다.
그렇지 않은 경우, 인자가 정수 또는 부동 소수점 수인 경우 동일한 값(파이썬의 부동 소수점 정밀도 내)을 가진 부동 소수점 수가 반환됩니다. 인자가 파이썬 float 범위를 벗어나는 경우
OverflowError가 발생합니다.일반 파이썬 객체
x에 대해,float(x)는x.__float__()를 호출합니다.__float__()가 정의되어 있지 않으면__index__()를 호출합니다.숫자 인자만 허용하는
float.from_number()를 참고하십시오.인자가 제공되지 않으면
0.0이 반환됩니다.float 타입은 Numeric Types — int, float, complex 에 설명되어 있습니다.
버전 3.6에서 변경: 코드 리터럴과 같이 밑줄로 숫자를 그룹화하는 것이 허용됩니다.
버전 3.7에서 변경: 해당 매개 변수는 이제 위치 전용(positional-only)입니다.
버전 3.8에서 변경: 메서드
__float__()가 정의되어 있지 않으면__index__()를 사용합니다.
- format(value, format_spec='', /)¶
value*를 *format_spec*에 의해 제어되는 “포맷된” 표현으로 변환합니다. *format_spec*의 해석은 *value 인자의 타입에 따라 달라지지만, 대부분의 내장 타입에서 사용되는 표준 포맷팅 구문이 있습니다: 포맷 명세 미니 언어.
기본 format_spec 은 빈 문자열이며, 이는 보통
str(value)를 호출하는 것과 동일한 효과를 줍니다.format(value, format_spec)호출은type(value).__format__(value, format_spec)으로 변환되며, 이는 값의__format__()메서드를 찾을 때 인스턴스 딕셔너리를 거치지 않습니다. 메서드 검색이object까지 도달했고 format_spec 이 비어 있지 않거나, format_spec 또는 반환 값이 문자열이 아닌 경우TypeError예외가 발생합니다.버전 3.4에서 변경:
object().__format__(format_spec)은 format_spec 이 빈 문자열이 아닌 경우TypeError를 발생시킵니다.
- class frozendict(**kwargs)
- class frozendict(mapping, /, **kwargs)
- class frozendict(iterable, /, **kwargs)
새로운 frozen 딕셔너리를 생성합니다.
frozendict객체는 내장 클래스입니다. 이 클래스에 대한 자세한 내용은 Mapping types — dict, frozendict 을 참조하십시오.다른 컨테이너의 경우 내장
dict,list,set,tuple클래스 및collections모듈을 참조하십시오.Added in version 3.15.
- class frozenset(iterable=(), /)
새로운
frozenset객체를 반환하며, 선택적으로 iterable 에서 가져온 요소들을 포함합니다.frozenset은 내장 클래스입니다. 이 클래스에 대한 자세한 내용은 Set Types — set, frozenset 을 참조하십시오.다른 컨테이너의 경우 내장
set,list,tuple,dict클래스 및collections모듈을 참조하십시오.
- getattr(object, name, /)¶
- getattr(object, name, default, /)
object 의 이름이 지정된 속성(attribute)의 값을 반환합니다. name 은 문자열이어야 합니다. 문자열이 객체의 속성 이름 중 하나라면, 해당 속성의 값을 결과로 반환합니다. 예를 들어,
getattr(x, 'foobar')는x.foobar와 동일합니다. 이름이 지정된 속성이 존재하지 않으면, 제공된 경우 default 를 반환하고 그렇지 않으면AttributeError가 발생합니다. name 은 반드시 Python 식별자일 필요는 없습니다(참조:setattr()).참고
Since private name mangling happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with
getattr().
- globals()¶
현재 모듈의 네임스페이스를 구현하는 딕셔너리를 반환합니다. 함수 내부의 코드의 경우, 이는 함수가 정의될 때 설정되며 함수가 호출되는 위치와 상관없이 동일하게 유지됩니다.
- hasattr(object, name, /)¶
인자는 객체와 문자열입니다. 문자열이 객체의 속성 이름 중 하나이면
True를, 아니면False를 반환합니다. (이는getattr(object, name)을 호출하여AttributeError가 발생하는지 여부를 확인하는 방식으로 구현됩니다.)
- hash(object, /)¶
객체의 해시 값을 반환합니다(해시 값이 있는 경우). 해시 값은 정수입니다. 이 값은 딕셔너리 검색 중 딕셔너리 키를 빠르게 비교하는 데 사용됩니다. 비교 결과가 동일한 수치 값은 동일한 해시 값을 가집니다(1과 1.0의 경우처럼 타입이 다르더라도 마찬가지입니다).
참고
사용자 정의
__hash__()메서드가 있는 객체의 경우,hash()가 호스트 머신의 비트 너비에 따라 반환 값을 절단(truncate)한다는 점에 유의하십시오.
- help()¶
- help(request)
내장 도움말 시스템을 호출합니다. (이 함수는 대화형 사용을 목적으로 합니다.) 인자가 제공되지 않으면 인터프리터 콘솔에서 대화형 도움말 시스템이 시작됩니다. 인자가 문자열인 경우, 해당 문자열을 모듈, 함수, 클래스, 메서드, 키워드 또는 문서 주제의 이름으로 검색하여 콘솔에 도움말 페이지를 출력합니다. 인자가 다른 종류의 객체인 경우, 해당 객체에 대한 도움말 페이지를 생성합니다.
help()를 호출할 때 함수의 매개변수 목록에 슬래시(/)가 나타나면, 이는 슬래시 앞의 매개변수가 위치 전용(positional-only)임을 의미합니다. 자세한 내용은 the FAQ entry on positional-only parameters 를 참조하십시오.이 함수는
site모듈에 의해 내장 네임스페이스에 추가됩니다.
- hex(integer, /)¶
정수 숫자를 “0x”로 시작하는 소문자 16진수 문자열로 변환합니다. integer 가 Python
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, /)¶
객체의 “식별자(identity)”를 반환합니다. 이는 객체의 수명 동안 고유하고 일정한 정수입니다. 수명이 겹치지 않는 두 객체는 동일한
id()값을 가질 수 있습니다.이것은 메모리 내 객체의 주소입니다.
인수
id를 사용하여 auditing eventbuiltins.id를 발생시킵니다.
- input()¶
- input(prompt, /)
prompt 인수가 있는 경우, 후행 줄 바꿈 없이 표준 출력에 작성됩니다. 그런 다음 함수는 입력에서 한 줄을 읽고, 이를 문자열로 변환(후행 줄 바꿈 제거)하여 반환합니다. EOF가 읽히면
EOFError가 발생합니다. 예제:>>> s = input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus"
readline모듈이 로드된 경우,input()은 이를 사용하여 정교한 줄 편집 및 히스토리 기능을 제공합니다.입력을 읽기 전에
prompt인자로 auditing eventbuiltins.input을 발생시킵니다.입력을 성공적으로 읽은 후의 결과로 auditing event
builtins.input/result를 발생시킵니다.
- class int(number=0, /)¶
- class int(string, /, base=10)
숫자나 문자열로부터 생성된 정수 객체를 반환하며, 인자가 제공되지 않으면
0을 반환합니다.예시:
>>> int(123.45) 123 >>> int('123') 123 >>> int(' -12_345\n') -12345 >>> int('FACE', 16) 64206 >>> int('0xface', 0) 64206 >>> int('01110011', base=2) 115
인자가
__int__()를 정의하는 경우,int(x)는x.__int__()를 반환합니다. 인자가__index__()를 정의하는 경우,x.__index__()를 반환합니다. 부동 소수점 숫자의 경우, 0을 향해 절사됩니다.인자가 숫자가 아니거나 base 가 제공된 경우, 인자는 base 진법에서 정수를 나타내는 문자열,
bytes, 또는bytearray인스턴스여야 합니다. 선택적으로 문자열 앞에+또는-를 붙일 수 있으며(사이에 공백 없음), 앞부분에 0이 올 수 있고, 공백으로 둘러싸일 수 있으며, 숫자 사이에 밑줄이 포함될 수 있습니다.진수-n 정수 문자열은 0에서 n-1까지의 값을 나타내는 숫자로 구성됩니다. 0-9는 임의의 유니코드 10진수 숫자로 표현될 수 있습니다. 10-35는
a부터z(또는A부터Z)로 표현될 수 있습니다. 기본 base 는 10입니다. 허용되는 진수는 0 및 2-36입니다. 2진법, 8진법, 16진법 문자열은 코드의 정수 리터럴과 마찬가지로 선택적으로0b/0B,0o/0O, 또는0x/0X접두사를 붙일 수 있습니다. 진수 0의 경우, 문자열은 integer literal in code 와 유사하게 해석되며, 접두사에 따라 실제 진수가 2, 8, 10 또는 16로 결정됩니다. 진수 0은 또한 앞선 0을 허용하지 않습니다. 즉,int('010', 0)은 허용되지 않지만,int('010')와int('010', 8)은 허용됩니다.정수 형은 Numeric Types — int, float, complex 에서 설명합니다.
버전 3.4에서 변경: base 가
int인스턴스가 아니고 base 객체가base.__index__메서드를 가지는 경우, 해당 메서드가 호출되어 진수를 위한 정수를 얻습니다. 이전 버전에서는base.__index__대신base.__int__를 사용했습니다.버전 3.6에서 변경: 코드 리터럴과 같이 밑줄로 숫자를 그룹화하는 것이 허용됩니다.
버전 3.7에서 변경: 첫 번째 매개변수는 이제 위치 전용(positional-only)입니다.
버전 3.8에서 변경: 메서드
__int__()가 정의되어 있지 않으면__index__()를 사용합니다.버전 3.11에서 변경:
int문자열 입력 및 문자열 표현은 서비스 거부(DoS) 공격을 방지하기 위해 제한될 수 있습니다. 문자열을int로 변환할 때 제한을 초과하거나,int를 문자열로 변환할 때 제한을 초과하면ValueError가 발생합니다. 자세한 내용은 integer string conversion length limitation 를 참조하십시오.버전 3.14에서 변경:
int()는 더 이상__trunc__()메서드에 위임하지 않습니다.
- isinstance(object, classinfo, /)¶
object 인자가 classinfo 인스턴스이거나, 해당 인스턴스의 (직접, 간접 또는 virtual) 하위 클래스 인스턴스인 경우
True를 반환합니다. object 가 해당 타입의 객체가 아니면 항상False를 반환합니다. classinfo 가 타입 객체의 튜플(또는 재귀적으로 다른 그러한 튜플)이나 여러 타입의 Union Type 인 경우, object 가 그 중 어느 하나라도 해당 타입의 인스턴스이면True를 반환합니다. classinfo 가 타입이나 타입의 튜플이 아닌 경우TypeError예외가 발생합니다. 이전 확인이 성공한 경우 유효하지 않은 타입에 대해TypeError가 발생하지 않을 수도 있습니다.버전 3.10에서 변경: classinfo can be a Union Type.
- issubclass(cls, classinfo, /)¶
Return
Trueif cls 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 (or recursively, other such tuples) or a Union Type, in which case returnTrueif cls is a subclass of any entry in classinfo. In any other case, aTypeErrorexception is raised.버전 3.10에서 변경: classinfo can be a Union Type.
- iter(iterable, /)¶
- iter(callable, /, stop_value, *, stop_exception=StopIteration)
- iter(callable, /, *, stop_exception)
Return an iterator object. The first argument is interpreted very differently depending on the presence of the other arguments. Without other arguments, the single argument must be a collection object which supports the iterable protocol (the
__iter__()method), or it must support the sequence protocol (the__getitem__()method with integer arguments starting at0). If it does not support either of those protocols,TypeErroris raised.If stop_value or stop_exception is given, then the first argument must be a callable object. The iterator created in this case will call callable with no arguments for each call to its
__next__()method; if the value returned is equal to stop_value, or if the call raises an exception matching stop_exception,StopIterationwill be raised, otherwise the value will be returned.stop_exception is an exception class or a tuple of exception classes. If stop_value is not specified, the iteration stops only when the callable raises an exception. If the callable raises
StopIterationwhich does not match stop_exception, it is replaced with aRuntimeError, as for generators (see PEP 479).See also Iteration-related types.
One useful application of the second form of
iter()is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:from functools import partial with open('mydata.db', 'rb') as f: for block in iter(partial(f.read, 64), b''): process_block(block)
stop_exception is useful for callables which report exhaustion by raising an exception instead of returning a special value. For example, draining a queue:
import queue for item in iter(input_queue.get_nowait, stop_exception=queue.Empty): process_item(item)
버전 3.16.0a0 (unreleased)에서 변경: Added the stop_exception parameter and allowed passing stop_value by keyword.
- len(object, /)¶
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
CPython 구현 상세:
lenraisesOverflowErroron lengths larger thansys.maxsize, such asrange(2 ** 100).
- class list(iterable=(), /)
Rather than being a function,
listis actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range.
- locals()¶
Return a mapping object representing the current local symbol table, with variable names as the keys, and their currently bound references as the values.
At module scope, as well as when using
exec()oreval()with a single namespace, this function returns the same namespace asglobals().At class scope, it returns the namespace that will be passed to the metaclass constructor.
When using
exec()oreval()with separate local and global arguments, it returns the local namespace passed in to the function call.In all of the above cases, each call to
locals()in a given frame of execution will return the same mapping object. Changes made through the mapping object returned fromlocals()will be visible as assigned, reassigned, or deleted local variables, and assigning, reassigning, or deleting local variables will immediately affect the contents of the returned mapping object.In an optimized scope (including functions, generators, and coroutines), each call to
locals()instead returns a fresh dictionary containing the current bindings of the function’s local variables and any nonlocal cell references. In this case, name binding changes made via the returned dict are not written back to the corresponding local variables or nonlocal cell references, and assigning, reassigning, or deleting local variables and nonlocal cell references does not affect the contents of previously returned dictionaries.Calling
locals()as part of a comprehension in a function, generator, or coroutine is equivalent to calling it in the containing scope, except that the comprehension’s initialised iteration variables will be included. In other scopes, it behaves as if the comprehension were running as a nested function.Calling
locals()as part of a generator expression is equivalent to calling it in a nested generator function.버전 3.12에서 변경: The behaviour of
locals()in a comprehension has been updated as described in PEP 709.버전 3.13에서 변경: As part of PEP 667, the semantics of mutating the mapping objects returned from this function are now defined. The behavior in optimized scopes is now as described above. Aside from being defined, the behaviour in other scopes remains unchanged from previous versions.
- map(function, iterable, /, *iterables, strict=False)¶
Return an iterator that applies function to every item of iterable, yielding the results. If additional iterables arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. If strict is
Trueand one of the iterables is exhausted before the others, aValueErroris raised. For cases where the function inputs are already arranged into argument tuples, seeitertools.starmap().버전 3.14에서 변경: Added the strict parameter.
- max(iterable, /, *, key=None)¶
- max(iterable, /, *, default, key=None)
- max(arg1, arg2, /, *args, key=None)
Return the largest item in an iterable or the largest of two or more arguments.
If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.
There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for
list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, aValueErroris raised.If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as
sorted(iterable, key=keyfunc, reverse=True)[0]andheapq.nlargest(1, iterable, key=keyfunc).버전 3.4에서 변경: Added the default keyword-only parameter.
버전 3.8에서 변경: The key can be
None.
- class memoryview(object)
Return a “memory view” object created from the given argument. See Memory Views for more information.
- min(iterable, /, *, key=None)¶
- min(iterable, /, *, default, key=None)
- min(arg1, arg2, /, *args, key=None)
Return the smallest item in an iterable or the smallest of two or more arguments.
If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.
There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for
list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, aValueErroris raised.If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as
sorted(iterable, key=keyfunc)[0]andheapq.nsmallest(1, iterable, key=keyfunc).버전 3.4에서 변경: Added the default keyword-only parameter.
버전 3.8에서 변경: The key can be
None.
- next(iterator, /)¶
- next(iterator, default, /)
Retrieve the next item from the iterator by calling its
__next__()method. If default is given, it is returned if the iterator is exhausted, otherwiseStopIterationis raised.
- class object¶
This is the ultimate base class of all other classes. It has methods that are common to all instances of Python classes. When the constructor is called, it returns a new featureless object. The constructor does not accept any arguments.
- oct(integer, /)¶
Convert an integer number to an octal string prefixed with “0o”. The result is a valid Python expression. If integer is not a Python
intobject, it has to define an__index__()method that returns an integer. For example:>>> oct(8) '0o10' >>> oct(-56) '-0o70'
If you want to convert an integer number to an octal string either with the prefix “0o” or not, you can use either of the following ways.
>>> '%#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)¶
Open file and return a corresponding file object. If the file cannot be opened, an
OSErroris raised. See 파일을 읽고 쓰기 for more examples of how to use this function.file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless closefd is set to
False.)mode is an optional string that specifies the mode in which the file is opened. It defaults to
'r'which means open for reading in text mode. Other common values are'w'for writing (truncating the file if it already exists),'x'for exclusive creation, and'a'for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform-dependent:locale.getencoding()is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:Character
Meaning
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of file if it exists
'b'binary mode
't'text mode (default)
'+'open for updating (reading and writing)
The default mode is
'r'(open for reading text, a synonym of'rt'). Modes'w+'and'w+b'open and truncate the file. Modes'r+'and'r+b'open the file with no truncation.As mentioned in the 개요, Python distinguishes between binary and text I/O. Files opened in binary mode (including
'b'in the mode argument) return contents asbytesobjects without any decoding. In text mode (the default, or when't'is included in the mode argument), the contents of the file are returned asstr, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.참고
Python doesn’t depend on the underlying operating system’s notion of text files; all the processing is done by Python itself, and is therefore platform-independent.
buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable when writing in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. Note that specifying a buffer size this way applies for binary buffered I/O, but
TextIOWrapper(i.e., files opened withmode='r+') would have another buffering. To disable buffering inTextIOWrapper, consider using thewrite_throughflag forio.TextIOWrapper.reconfigure(). When no buffering argument is given, the default buffering policy works as follows:Binary files are buffered in fixed-size chunks; the size of the buffer is
max(min(blocksize, 8 MiB), DEFAULT_BUFFER_SIZE)when the device block size is available. On most systems, the buffer will typically be 128 kilobytes long.“Interactive” text files (files for which
isatty()returnsTrue) use line buffering. Other text files use the policy described above for binary files.
encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever
locale.getencoding()returns), but any text encoding supported by Python can be used. See thecodecsmodule for the list of supported encodings.errors is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available, though any error handling name that has been registered with
codecs.register_error()is also valid. The standard names can be found in 에러 처리기.newline determines how to parse newline characters from the stream. 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 closefd is
Falseand a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must beTrue(the default); otherwise, an error will be raised.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 (file, flags). opener must return an open file descriptor (passing
os.openas opener results in functionality similar to passingNone).The newly created file is non-inheritable.
The following example uses the dir_fd parameter of the
os.open()function to open a file relative to a given directory:>>> 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
The type of file object returned by the
open()function depends on the mode. Whenopen()is used to open a file in a text mode ('w','r','wt','rt', etc.), it returns a subclass ofio.TextIOBase(specificallyio.TextIOWrapper). When used to open a file in a binary mode with buffering, the returned class is a subclass ofio.BufferedIOBase. The exact class varies: in read binary mode, it returns anio.BufferedReader; in write binary and append binary modes, it returns anio.BufferedWriter, and in read/write mode, it returns anio.BufferedRandom. When buffering is disabled, the raw stream, a subclass ofio.RawIOBase,io.FileIO, is returned.See also the file handling modules, such as
fileinput,io(whereopen()is declared),os,os.path,tempfile, andshutil.Raises an auditing event
openwith argumentspath,mode,flags.The
modeandflagsarguments may have been modified or inferred from the original call.버전 3.3에서 변경:
The opener parameter was added.
The
'x'mode was added.FileExistsErroris now raised if the file opened in exclusive creation mode ('x') already exists.
버전 3.4에서 변경:
The file is now non-inheritable.
버전 3.5에서 변경:
If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an
InterruptedErrorexception (see PEP 475 for the rationale).The
'namereplace'error handler was added.
버전 3.6에서 변경:
Support added to accept objects implementing
os.PathLike.On Windows, opening a console buffer may return a subclass of
io.RawIOBaseother thanio.FileIO.
버전 3.11에서 변경: The
'U'mode has been removed.
- ord(character, /)¶
Return the ordinal value of a character.
If the argument is a one-character string, return the Unicode code point of that character. For example,
ord('a')returns the integer97andord('€')(Euro sign) returns8364. This is the inverse ofchr().If the argument is a
bytesorbytearrayobject of length 1, return its single byte value. For example,ord(b'a')returns the integer97.
- pow(base, exp, mod=None)¶
Return base to the power exp; if mod is present, return base to the power exp, modulo mod (computed more efficiently than
pow(base, exp) % mod). The two-argument formpow(base, exp)is equivalent to using the power operator:base**exp.When arguments are builtin numeric types with mixed operand types, the coercion rules for binary arithmetic operators apply. For
intoperands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example,pow(10, 2)returns100, butpow(10, -2)returns0.01. For a negative base of typeintorfloatand a non-integral exponent, a complex result is delivered. For example,pow(-9, 0.5)returns a value close to3j. Whereas, for a negative base of typeintorfloatwith an integral exponent, a float result is delivered. For example,pow(-9, 2.0)returns81.0.For
intoperands base and exp, if mod is present, mod must also be of integer type and mod must be nonzero. If mod is present and exp is negative, base must be relatively prime to mod. In that case,pow(inv_base, -exp, mod)is returned, where inv_base is an inverse to base modulo mod.Here’s an example of computing an inverse for
38modulo97:>>> pow(38, -1, mod=97) 23 >>> 23 * 38 % 97 == 1 True
버전 3.8에서 변경: For
intoperands, the three-argument form ofpownow allows the second argument to be negative, permitting computation of modular inverses.버전 3.8에서 변경: Allow keyword arguments. Formerly, only positional arguments were supported.
- print(*objects, sep=' ', end='\n', file=None, flush=False)¶
Print objects to the text stream file, separated by sep and followed by end. sep, end, file, and flush, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like
str()does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also beNone, which means to use the default values. If no objects are given,print()will just write end.The file argument must be an object with a
write(string)method; if it is not present orNone,sys.stdoutwill be used. Since printed arguments are converted to text strings,print()cannot be used with binary mode file objects. For these, usefile.write(...)instead.Output buffering is usually determined by file. However, if flush is true, the stream is forcibly flushed.
버전 3.3에서 변경: Added the flush keyword argument.
- class property(fget=None, fset=None, fdel=None, doc=None)¶
Return a property attribute.
fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute.
A typical use is to define a managed attribute
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.")
If c is an instance of C,
c.xwill invoke the getter,c.x = valuewill invoke the setter, anddel c.xthe deleter.If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget’s docstring (if it exists). This makes it possible to create read-only properties easily using
@propertyas a decorator:class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage
The
@propertydecorator turns thevoltage()method into a “getter” for a read-only attribute with the same name, and it sets the docstring for voltage to “Get the current voltage.”- @getter¶
- @setter¶
- @deleter¶
A property object has
getter,setter, anddeletermethods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example: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
This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (
xin this case.)The returned property object also has the attributes
fget,fset, andfdelcorresponding to the constructor arguments.
버전 3.5에서 변경: The docstrings of property objects are now writeable.
- __name__¶
Attribute holding the name of the property. The name of the property can be changed at runtime.
Added in version 3.13.
- class range(stop, /)
- class range(start, stop, step=1, /)
Rather than being a function,
rangeis actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.
- repr(object, /)¶
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to
eval(); otherwise, the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a__repr__()method. Ifsys.displayhook()is not accessible, this function will raiseRuntimeError.This class has a custom representation that can be evaluated:
class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"Person({self.name!r}, {self.age!r})"
- reversed(object, /)¶
Return a reverse iterator. The argument must be an object which has a
__reversed__()method or supports the sequence protocol (the__len__()method and the__getitem__()method with integer arguments starting at0).
- round(number, ndigits=None)¶
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is
None, it returns the nearest integer to its input.For the built-in types supporting
round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, bothround(0.5)andround(-0.5)are0, andround(1.5)is2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted orNone. Otherwise, the return value has the same type as number.For a general Python object
number,rounddelegates tonumber.__round__.참고
The behavior of
round()for floats can be surprising: for example,round(2.675, 2)gives2.67instead of the expected2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See 부동 소수점 산술: 문제점 및 한계 for more information.
- class set(iterable=(), /)
Return a new
setobject, optionally with elements taken from iterable.setis a built-in class. See also Set Types — set, frozenset for documentation about this class.For other containers see the built-in
frozenset,list,tuple, anddictclasses, as well as thecollectionsmodule.
- setattr(object, name, value, /)¶
This is the counterpart of
getattr(). The arguments are an object, a string, and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example,setattr(x, 'foobar', 123)is equivalent tox.foobar = 123.name need not be a Python identifier as defined in 이름(식별자 및 키워드) unless the object chooses to enforce that, for example in a custom
__getattribute__()or via__slots__. An attribute whose name is not an identifier will not be accessible using the dot notation, but is accessible throughgetattr()etc..참고
Since private name mangling happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to set it with
setattr().
- class sentinel(name, /, *, repr=None)¶
Return a new unique sentinel object. name must be a
str, and is used by default as the returned object’s representation:>>> MISSING = sentinel("MISSING") >>> MISSING MISSING
The optional repr argument can be used to specify a different representation:
>>> MISSING = sentinel("MISSING", repr="<MISSING>") >>> MISSING <MISSING>
Sentinel objects are truthy and compare equal only to themselves. They are intended to be compared with the
isoperator.sentineldoes not support subclassing.Shallow and deep copies of a sentinel object return the object itself.
Sentinels are conventionally assigned to a variable with a matching name. Sentinels defined in this way can be used in type hints:
MISSING = sentinel("MISSING") def next_value(default: int | MISSING = MISSING): ...
Sentinel objects support the | operator for use in type expressions.
Picklingis supported for sentinel objects that are placed in the global scope of a module under a name matching the sentinel’s name, and for sentinels placed in class scopes with a name matching the qualified name of the sentinel. Other sentinels, such as those defined in a function scope, are not picklable. The identity of the sentinel is preserved after pickling:import pickle PICKLABLE = sentinel("PICKLABLE") assert pickle.loads(pickle.dumps(PICKLABLE)) is PICKLABLE class Cls: PICKLABLE = sentinel("Cls.PICKLABLE") assert pickle.loads(pickle.dumps(Cls.PICKLABLE)) is Cls.PICKLABLE
Sentinel objects have the following attributes:
- __name__¶
The sentinel’s name.
- __module__¶
The name of the module where the sentinel was created. This attribute is writable.
Added in version 3.15.
- class slice(stop, /)¶
- class slice(start, stop, step=None, /)
Return a slice object representing the set of indices specified by
range(start, stop, step). The start and step arguments default toNone.Slice objects are also generated when slicing syntax is used. For example:
a[start:stop:step]ora[start:stop, i].See
itertools.islice()for an alternate version that returns an iterator.
- sorted(iterable, /, *, key=None, reverse=False)¶
Return a new sorted list from the items in iterable.
Has two optional arguments which must be specified as keyword arguments.
key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example,
key=str.lower). The default value isNone(compare the elements directly).reverse is a boolean value. If set to
True, then the list elements are sorted as if each comparison were reversed.Use
functools.cmp_to_key()to convert an old-style cmp function to a key function.The built-in
sorted()function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).The sort algorithm uses only
<comparisons between items. While defining an__lt__()method will suffice for sorting, PEP 8 recommends that all six rich comparisons be implemented. This will help avoid bugs when using the same data with other ordering tools such asmax()that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call the reflected__gt__()method.For sorting examples and a brief sorting tutorial, see 정렬 기법.
- @staticmethod¶
Transform a method into a static method.
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C: @staticmethod def f(arg1, arg2, argN): ...
The
@staticmethodform is a function decorator – see 함수 정의 for details.A static method can be called either on the class (such as
C.f()) or on an instance (such asC().f()). Moreover, the static method descriptor is also callable, so it can be used in the class definition (such asf()).Static methods in Python are similar to those found in Java or C++. Also, see
@classmethodfor a variant that is useful for creating alternate class constructors.Like all decorators, it is also possible to call
staticmethodas a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:def regular_function(): ... class C: method = staticmethod(regular_function)
For more information on static methods, see 표준형 계층.
버전 3.10에서 변경: Static methods now inherit the method attributes (
__module__,__name__,__qualname__,__doc__and__annotations__), have a new__wrapped__attribute, and are now callable as regular functions.
- class str(*, encoding='utf-8', errors='strict')
- class str(object)
- class str(object, encoding, errors='strict')
- class str(object, *, errors)
Return a
strversion of object. Seestr()for details.stris the built-in string class. For general information about strings, see Text Sequence Type — str.
- sum(iterable, /, start=0)¶
Sums start and the items of an iterable from left to right and returns the total. The iterable’s items are normally numbers, and the start value is not allowed to be a string.
For some use cases, there are good alternatives to
sum(). The preferred, fast way to concatenate a sequence of strings is by calling''.join(sequence). To add floating-point values with extended precision, seemath.fsum(). To concatenate a series of iterables, consider usingitertools.chain().버전 3.8에서 변경: The start parameter can be specified as a keyword argument.
버전 3.12에서 변경: Summation of floats switched to an algorithm that gives higher accuracy and better commutativity on most builds.
버전 3.14에서 변경: Added specialization for summation of complexes, using same algorithm as for summation of floats.
- class super¶
- class super(type, object_or_type=None, /)
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.
The object_or_type determines the method resolution order to be searched. The search starts from the class right after the type.
For example, if
__mro__of object_or_type isD -> B -> C -> A -> objectand the value of type isB, thensuper()searchesC -> A -> object.The
__mro__attribute of the class corresponding to object_or_type lists the method resolution search order used by bothgetattr()andsuper(). The attribute is dynamic and can change whenever the inheritance hierarchy is updated.If the second argument is omitted, the super object returned is unbound. If the second argument is an object,
isinstance(obj, type)must be true. If the second argument is a type,issubclass(type2, type)must be true (this is useful for classmethods).When called directly within an ordinary method of a class, both arguments may be omitted (“zero-argument
super()”). In this case, type will be the enclosing class, and obj will be the first argument of the immediately enclosing function (typicallyself). (This means that zero-argumentsuper()will not work as expected within nested functions, including generator expressions, which implicitly create nested functions.)There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.
The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that such implementations have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).
For both use cases, a typical superclass call looks like this:
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.Note that
super()is implemented as part of the binding process for explicit dotted attribute lookups such assuper().__getitem__(name). It does so by implementing its own__getattribute__()method for searching classes in a predictable order that supports cooperative multiple inheritance. Accordingly,super()is undefined for implicit lookups using statements or operators such assuper()[name].Also note that, aside from the zero argument form,
super()is not limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references. The zero argument form only works inside a class definition, as the compiler fills in the necessary details to correctly retrieve the class being defined, as well as accessing the current instance for ordinary methods.For practical suggestions on how to design cooperative classes using
super(), see guide to using super().버전 3.14에서 변경:
superobjects are nowpickleableandcopyable.
- class tuple(iterable=(), /)
Rather than being a function,
tupleis actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range.
- class type(object, /)¶
- class type(name, bases, dict, /, **kwargs)
With one argument, return the type of an object. The return value is a type object and generally the same object as returned by
object.__class__.The
isinstance()built-in function is recommended for testing the type of an object, because it takes subclasses into account.With three arguments, return a new type object. This is essentially a dynamic form of the
classstatement. The name string is the class name and becomes the__name__attribute. The bases tuple contains the base classes and becomes the__bases__attribute; if empty,object, the ultimate base of all classes, is added. The dict dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming the__dict__attribute. The following two statements create identicaltypeobjects:>>> class X: ... a = 1 ... >>> X = type('X', (), dict(a=1))
See also:
Keyword arguments provided to the three argument form are passed to the appropriate metaclass machinery (usually
__init_subclass__()) in the same way that keywords in a class definition (besides metaclass) would.Unlike a
classstatement, the three argument form does not call the metaclass__prepare__method (see 클래스 이름 공간 준비하기). Usetypes.new_class()to dynamically create a class using the appropriate metaclass.See also 클래스 생성 커스터마이제이션.
버전 3.6에서 변경: Subclasses of
typewhich don’t overridetype.__new__may no longer use the one-argument form to get the type of an object.버전 3.15에서 변경: dict can now be a
frozendict.
- vars()¶
- vars(object, /)
Return the
__dict__attribute for a module, class, instance, or any other object with a__dict__attribute.Objects such as modules and instances have an updateable
__dict__attribute; however, other objects may have write restrictions on their__dict__attributes (for example, classes use atypes.MappingProxyTypeto prevent direct dictionary updates).Without an argument,
vars()acts likelocals().A
TypeErrorexception is raised if an object is specified but it doesn’t have a__dict__attribute (for example, if its class defines the__slots__attribute).버전 3.13에서 변경: The result of calling this function without an argument has been updated as described for the
locals()builtin.
- zip(*iterables, strict=False)¶
Iterate over several iterables in parallel, producing tuples with an item from each one.
Example:
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']): ... print(item) ... (1, 'sugar') (2, 'spice') (3, 'everything nice')
More formally:
zip()returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables.Another way to think of
zip()is that it turns rows into columns, and columns into rows. This is similar to transposing a matrix.zip()is lazy: The elements won’t be processed until the iterable is iterated on, e.g. by aforloop or by wrapping in alist.One thing to consider is that the iterables passed to
zip()could have different lengths; sometimes by design, and sometimes because of a bug in the code that prepared these iterables. Python offers three different approaches to dealing with this issue:By default,
zip()stops when the shortest iterable is exhausted. It will ignore the remaining items in the longer iterables, cutting off the result to the length of the shortest iterable:>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum'])) [(0, 'fee'), (1, 'fi'), (2, 'fo')]
zip()is often used in cases where the iterables are assumed to be of equal length. In such cases, it’s recommended to use thestrict=Trueoption. Its output is the same as regularzip():>>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True)) [('a', 1), ('b', 2), ('c', 3)]
Unlike the default behavior, it raises a
ValueErrorif one iterable is exhausted before the others:>>> for item in zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True): ... print(item) ... (0, 'fee') (1, 'fi') (2, 'fo') Traceback (most recent call last): ... ValueError: zip() argument 2 is longer than argument 1
Without the
strict=Trueargument, any bug that results in iterables of different lengths will be silenced, possibly manifesting as a hard-to-find bug in another part of the program.Shorter iterables can be padded with a constant value to make all the iterables have the same length. This is done by
itertools.zip_longest().
Edge cases: With a single iterable argument,
zip()returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.Tips and tricks:
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using
zip(*[iter(s)]*n, strict=True). This repeats the same iteratorntimes so that each output tuple has the result ofncalls to the iterator. This has the effect of dividing the input into n-length chunks.zip()in conjunction with the*operator can be used to unzip a list:>>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> list(zip(x, y)) [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zip(x, y)) >>> x == list(x2) and y == list(y2) True
버전 3.10에서 변경: Added the
strictargument.
- __import__(name, globals=None, locals=None, fromlist=(), level=0)¶
참고
This is an advanced function that is not needed in everyday Python programming, unlike
importlib.import_module().This function is invoked by the
importstatement. It can be replaced (by importing thebuiltinsmodule and assigning tobuiltins.__import__) in order to change semantics of theimportstatement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of__import__()is also discouraged in favor ofimportlib.import_module().The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all and uses its globals only to determine the package context of the
importstatement.level specifies whether to use absolute or relative imports.
0(the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling__import__()(see PEP 328 for the details).When the name variable is of the form
package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.For example, the statement
import spamresults in bytecode resembling the following code:spam = __import__('spam', globals(), locals(), [], 0)
The statement
import spam.hamresults in this call:spam = __import__('spam.ham', globals(), locals(), [], 0)
Note how
__import__()returns the toplevel module here because this is the object that is bound to a name by theimportstatement.On the other hand, the statement
from spam.ham import eggs, sausage as sausresults in_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage
Here, the
spam.hammodule is returned from__import__(). From this object, the names to import are retrieved and assigned to their respective names.If you simply want to import a module (potentially within a package) by name, use
importlib.import_module().버전 3.3에서 변경: Negative values for level are no longer supported (which also changes the default value to 0).
버전 3.9에서 변경: When the command line options
-Eor-Iare being used, the environment variablePYTHONCASEOKis now ignored.
Footnotes