내장 함수

파이썬 인터프리터에는 항상 사용할 수 있는 많은 함수와 형이 내장되어 있습니다. 여기에서 알파벳 순으로 나열합니다.

내장 함수

abs(x)

Return the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing __abs__(). If the argument is a complex number, its magnitude is returned.

aiter(async_iterable)

Return an asynchronous iterator for an asynchronous iterable. Equivalent to calling x.__aiter__().

Note: Unlike iter(), aiter() has no 2-argument variant.

버전 3.10에 추가.

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.

This is the async variant of the next() builtin, and behaves similarly.

This calls the __anext__() method of async_iterator, returning an awaitable. Awaiting this returns the next value of the iterator. If default is given, it is returned if the iterator is exhausted, otherwise StopAsyncIteration is raised.

버전 3.10에 추가.

any(iterable)

iterable 의 요소 중 어느 하나라도 참이면 True 를 돌려줍니다. iterable이 비어 있으면 False 를 돌려줍니다. 다음과 동등합니다:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
ascii(object)

As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u, or \U escapes. This generates a string similar to that returned by repr() in Python 2.

bin(x)

Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

If the prefix “0b” is desired or not, you can use either of the following ways.

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

자세한 내용은 format()을 보세요.

class bool(x=False)

Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise, it returns True. The bool class is a subclass of int (see 숫자 형 — int, float, complex). It cannot be subclassed further. Its only instances are False and True (see Boolean Type - bool).

버전 3.7에서 변경: x는 이제 위치 전용 매개 변수입니다.

breakpoint(*args, **kws)

This function drops you into the debugger at the call site. Specifically, it calls sys.breakpointhook(), passing args and kws straight through. By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import pdb or type as much code to enter the debugger. However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice. If sys.breakpointhook() is not accessible, this function will raise RuntimeError.

By default, the behavior of breakpoint() can be changed with the PYTHONBREAKPOINT environment variable. See sys.breakpointhook() for usage details.

Note that this is not guaranteed if sys.breakpointhook() has been replaced.

breakpointhook을 인자로 감사 이벤트(auditing event) builtins.breakpoint를 발생시킵니다.

버전 3.7에 추가.

class bytearray(source=b'')
class bytearray(source, encoding)
class bytearray(source, encoding, errors)

새로운 바이트 배열을 돌려줍니다. bytearray 클래스는 0 <= x < 256 범위에 있는 정수의 가변 시퀀스입니다. bytes 형이 가진 대부분의 메서드뿐만 아니라 (바이트열 과 바이트 배열 연산 를 보세요), 가변 시퀀스 형 에 기술된 가변 시퀀스의 일반적인 메서드 대부분을 갖고 있습니다.

선택적 source 매개변수는 몇 가지 다른 방법으로 배열을 초기화하는 데 사용할 수 있습니다:

  • 문자열 이면, 반드시 encoding 매개변수도 제공해야 합니다 (그리고 선택적으로 errors 도); 그러면 bytearray()str.encode() 를 사용하여 문자열을 바이트로 변환합니다.

  • 정수 면, 배열은 그 크기를 갖고, 널 바이트로 초기화됩니다.

  • 버퍼 인터페이스를 제공하는 객체면, 객체의 읽기 전용 버퍼가 바이트 배열을 초기화하는 데 사용됩니다.

  • 이터러블 이면, 범위 0 <= x < 256 의 정수를 제공하는 이터러블이어야 하고, 그 값들이 배열의 초기 내용물로 사용됩니다.

인자가 없으면 크기 0의 배열이 만들어집니다.

바이너리 시퀀스 형 — bytes, bytearray, memoryview바이트 배열 객체 도 보세요.

class bytes(source=b'')
class bytes(source, encoding)
class bytes(source, encoding, errors)

Return a new “bytes” object which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.

따라서 생성자 인자는 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

메서드를 클래스 메서드로 변환합니다.

A class method receives the class as an implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
    @classmethod
    def f(cls, arg1, arg2): ...

@classmethod 형식은 함수 데코레이터 입니다 – 자세한 내용은 함수 정의를 보세요.

클래스 메서드는 클래스 (C.f() 처럼) 또는 인스턴스 (C().f() 처럼) 를 통해 호출할 수 있습니다. 인스턴스는 클래스만 참조하고 무시됩니다. 파생 클래스에 대해 클래스 메서드가 호출되면, 파생 클래스 객체가 묵시적인 첫 번째 인자로 전달됩니다.

클래스 메서드는 C++ 또는 자바의 정적 메서드와 다릅니다. 그것들을 원하면, 이 섹션의 staticmethod()를 보세요. 클래스 메서드에 대한 더 자세한 정보는, 표준형 계층을 참고하세요.

버전 3.9에서 변경: 클래스 메서드는 이제 property()와 같은 다른 디스크립터를 래핑 할 수 있습니다.

버전 3.10에서 변경: Class methods now inherit the method attributes (__module__, __name__, __qualname__, __doc__ and __annotations__) and have a new __wrapped__ attribute.

버전 3.11에서 변경: Class methods can no longer wrap other descriptors such as property().

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 이외의 값으로 구해지는 표현식 문은 인쇄됩니다).

선택적 인자 flagsdont_inherit 는 어떤 컴파일러 옵션이 활성화되어야 하고 어떤 퓨처 기능이 허락되어야 하는지 제어합니다. 둘 다 제공되지 않는 경우 (또는 둘 다 0의 경우), 코드는 compile() 을 호출하는 코드에 적용되고 있는 것과 같은 플래그로 컴파일됩니다. flags 인자가 주어지고, dont_inherit 가 없으면 (또는 0) 원래 사용될 것에 더해 flags 인자로 지정된 컴파일러 옵션과 퓨처 문이 사용됩니다. dont_inherit 가 0이 아닌 정수면 flags 인자가 사용됩니다 – 둘러싼 코드의 플래그(퓨처 기능과 컴파일러 옵션)는 무시됩니다.

컴파일러 옵션과 퓨처 문은 여러 개의 옵션을 지정하기 위해 비트 OR 될 수 있는 비트에 의해 지정됩니다. 주어진 퓨처 기능을 지정하는 데 필요한 비트 필드는 __future__ 모듈의 _Feature 인스턴스에서 compiler_flag 어트리뷰트로 찾을 수 있습니다. 컴파일러 플래그PyCF_ 접두사로 ast 모듈에서 찾을 수 있습니다.

인자 optimize 는 컴파일러의 최적화 수준을 지정합니다; 기본값 -1-O 옵션에 의해 주어진 인터프리터의 최적화 수준을 선택합니다. 명시적 수준은 0 (최적화 없음, __debug__ 이 참입니다), 1 (assert가 제거됩니다, __debug__ 이 거짓입니다) 또는 2 다 (독스트링도 제거됩니다).

이 함수는 컴파일된 소스가 올바르지 않으면 SyntaxError 를 일으키고, 소스에 널 바이트가 들어있는 경우 ValueError 를 일으킵니다.

파이썬 코드를 AST 표현으로 파싱하려면, ast.parse() 를 보세요.

source, filename 인자로 감사 이벤트(auditing event) compile을 발생시킵니다.

참고

'single' 또는 'eval' mode로 여러 줄 코드를 가진 문자열을 컴파일할 때, 적어도 하나의 개행 문자로 입력을 끝내야 합니다. 이것은 code 모듈에서 문장이 불완전한지 완전한지를 쉽게 탐지하게 하기 위함입니다.

경고

파이썬의 AST 컴파일러에서 스택 깊이 제한으로 인해, AST 객체로 컴파일할 때 충분히 크고 복잡한 문자열로 파이썬 인터프리터가 크래시를 일으키도록 만들 수 있습니다.

버전 3.2에서 변경: Allowed use of Windows and Mac newlines. Also, input in 'exec' mode does not have to end in a newline anymore. Added the optimize parameter.

버전 3.5에서 변경: 이전에는, source 에서 널 바이트가 발견될 때 TypeError 가 발생했습니다.

버전 3.8에 추가: 이제 ast.PyCF_ALLOW_TOP_LEVEL_AWAIT를 flags로 전달하여 최상위 수준 await, async forasync with를 지원할 수 있습니다.

class complex(real=0, imag=0)
class complex(string)

real + imag*1j 값을 가진 복소수를 돌려주거나 문자열 또는 숫자를 복소수로 변환합니다. 첫 번째 매개변수가 문자열이면 복소수로 해석되며, 두 번째 매개변수 없이 함수를 호출해야 합니다. 두 번째 매개변수는 결코 문자열 일 수 없습니다. 각 인자는 모든 (복소수를 포함한) 숫자 형이 될 수 있습니다. imag 가 생략되면 기본값은 0이고, 생성자는 intfloat와 같은 숫자 변환으로 사용됩니다. 두 인자가 모두 생략되면 0j 를 돌려줍니다.

For a general Python object x, complex(x) delegates to x.__complex__(). If __complex__() is not defined then it falls back to __float__(). If __float__() is not defined then it falls back to __index__().

참고

문자열을 변환할 때, 문자열은 중앙의 + 또는 - 연산자 주위에 공백을 포함해서는 안 됩니다. 예를 들어, complex('1+2j') 는 괜찮지만 complex('1 + 2j')ValueError 를 일으킵니다.

복소수 형은 숫자 형 — int, float, complex 에서 설명합니다.

버전 3.6에서 변경: 코드 리터럴 처럼 숫자를 밑줄로 그룹화할 수 있습니다.

버전 3.8에서 변경: Falls back to __index__() if __complex__() and __float__() are not defined.

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 to del x.foobar. name need not be a Python identifier (see setattr()).

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

새 딕셔너리를 만듭니다. dict 객체는 딕셔너리 클래스입니다. 이 클래스에 대한 설명서는 dict매핑 형 — dict 을 보세요.

다른 컨테이너의 경우 list, settuple 클래스와 collections 모듈을 보세요.

dir()
dir(object)

인자가 없으면, 현재 지역 스코프에 있는 이름들의 리스트를 돌려줍니다. 인자가 있으면, 해당 객체에 유효한 어트리뷰트들의 리스트를 돌려주려고 시도합니다.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete and may be inaccurate when the object has a custom __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)

Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 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(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
eval(expression, globals=None, locals=None)

인자는 문자열 및 선택적 globals 및 locals다. 제공된 경우, globals 는 딕셔너리여야 합니다. 제공되는 경우, locals 는 모든 매핑 객체가 될 수 있습니다.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries 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 module builtins is inserted under that key before expression is parsed. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to eval(). If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where eval() is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.

반환 값은 계산된 표현식의 결과입니다. 문법 에러는 예외로 보고됩니다. 예:

>>> x = 1
>>> eval('x+1')
2

This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case, pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()'s return value will be None.

Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions return the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().

If the given source is a string, then leading and trailing spaces and tabs are stripped.

리터럴 만 포함 된 표현식의 값을 안전하게 구할 수 있는 함수 ast.literal_eval() 를 보세요.

code_object 인자로 감사 이벤트(auditing event) exec를 발생시킵니다.

exec(object, globals=None, locals=None, /, *, closure=None)

This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1] If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section 파일 입력 in the Reference Manual). Be aware that the nonlocal, yield, and return statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at the module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

globals 딕셔너리가 __builtins__ 를 키로 하는 값을 갖고 있지 않으면, 그 키로 내장 모듈 builtins 에 대한 참조가 삽입됩니다. 이런 식으로 exec() 에 전달하기 전에 globals 에 여러분 자신의 __builtins__ 딕셔너리를 삽입함으로써, 실행되는 코드에 어떤 내장 객체들이 제공될지를 제어할 수 있습니다.

The closure argument specifies a closure–a tuple of cellvars. It’s only valid when the object is a code object containing free variables. The length of the tuple must exactly match the number of free variables referenced by the code object.

code_object 인자로 감사 이벤트(auditing event) exec를 발생시킵니다.

참고

내장 함수 globals()locals() 는 각각 현재 전역 및 지역 딕셔너리를 돌려주는데, exec() 로 전달되는 두 번째 및 세 번째 인자로 사용하는 데 유용합니다.

참고

기본 locals 는 아래 함수 locals() 에 설명된 대로 작동합니다: 기본 locals 사전에 대해 수정이 시도되어서는 안 됩니다. 함수 exec() 가 돌아온 후에 locals 에 코드가 만든 효과를 보려면 명시적으로 locals 딕셔너리를 전달해야 합니다.

버전 3.11에서 변경: Added the closure parameter.

filter(function, iterable)

Construct an iterator from those elements of iterable for which function is true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

filter(function, iterable) 는 function이 None 이 아닐 때 제너레이터 표현식 (item for item in iterable if function(item)) 과, None 일 때 (item for item in iterable if item) 와 동등함에 유의하세요.

See itertools.filterfalse() for the complementary function that returns elements of iterable for which function is false.

class float(x=0.0)

숫자 또는 문자열 x 로 부터 실수를 만들어 돌려줍니다.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or positive or negative infinity. More precisely, the input must conform to the floatvalue production rule in the following grammar, after leading and trailing whitespace characters are removed:

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") ["+" | "-"] digitpart
floatnumber ::=  number [exponent]
floatvalue  ::=  [sign] (floatnumber | infinity | nan)

Case is not significant, so, for example, “inf”, “Inf”, “INFINITY”, and “iNfINity” are all acceptable spellings for positive infinity.

그렇지 않으면, 인자가 정수 또는 실수면 (파이썬의 부동 소수점 정밀도 내에서) 같은 값을 가진 실수가 반환됩니다. 인자가 파이썬 float 범위를 벗어나면, OverflowError 가 발생합니다.

For a general Python object x, float(x) delegates to x.__float__(). If __float__() is not defined then it falls back to __index__().

인자가 주어지지 않으면, 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는 이제 위치 전용 매개 변수입니다.

버전 3.8에서 변경: Falls back to __index__() if __float__() is not defined.

format(value, format_spec='')

Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument; however, there is a standard formatting syntax that is used by most built-in types: 포맷 명세 미니 언어.

기본 format_spec 은 빈 문자열이며 일반적으로 str(value) 를 호출하는 것과 같은 효과를 줍니다.

A call to format(value, format_spec) is translated to type(value).__format__(value, format_spec) which bypasses the instance dictionary when searching for the value’s __format__() method. A TypeError exception is raised if the method search reaches object and the format_spec is non-empty, or if either the format_spec or the return value are not strings.

버전 3.4에서 변경: object().__format__(format_spec)format_spec 이 빈 문자열이 아닌 경우 TypeError 를 일으킵니다.

class frozenset(iterable=set())

frozenset 객체를 돌려주는데, 선택적으로 iterable 에서 가져온 요소를 포함합니다. frozenset 은 내장 클래스입니다. 이 클래스에 대한 설명서는 frozenset집합 형 — set, frozenset을 보세요.

다른 컨테이너의 경우 set, list, tupledict 클래스와 collections 모듈을 보세요.

getattr(object, name)
getattr(object, name, default)

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised. name need not be a Python identifier (see 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()

Return the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called.

hasattr(object, name)

인자는 객체와 문자열입니다. 문자열이 객체의 속성 중 하나의 이름이면 결과는 True 이고, 그렇지 않으면 False 가 됩니다. (이것은 getattr(object, name) 을 호출하고 AttributeError 를 발생시키는지를 보는 식으로 구현됩니다.)

hash(object)

객체의 해시값을 돌려줍니다 (해시가 있는 경우). 해시값은 정수다. 딕셔너리 조회 중에 딕셔너리 키를 빨리 비교하는 데 사용됩니다. 같다고 비교되는 숫자 값은 같은 해시값을 갖습니다 (1과 1.0의 경우와 같이 형이 다른 경우조차도 그렇습니다).

참고

For objects with custom __hash__() methods, note that hash() truncates the return value based on the bit width of the host machine.

help()
help(request)

내장 도움말 시스템을 호출합니다. (이 함수는 대화형 사용을 위한 것입니다.) 인자가 제공되지 않으면, 인터프리터 콘솔에서 대화형 도움말 시스템이 시작됩니다. 인자가 문자열이면 문자열은 모듈, 함수, 클래스, 메서드, 키워드 또는 설명서 주제의 이름으로 조회되고, 도움말 페이지가 콘솔에 인쇄됩니다. 인자가 다른 종류의 객체면, 객체에 대한 도움말 페이지가 만들어집니다.

Note that if a slash(/) appears in the parameter list of a function when invoking help(), it means that the parameters prior to the slash are positional-only. For more info, see the FAQ entry on positional-only parameters.

이 함수는 site 모듈에 의해 내장 이름 공간에 추가됩니다.

버전 3.4에서 변경: pydocinspect 의 변경 사항은 콜러블의 시그니처가 이제 더 포괄적이고 일관성이 있음을 의미합니다.

hex(x)

Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples:

>>> 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 구현 상세: This is the address of the object in memory.

id 인자로 감사 이벤트(auditing event) builtins.id를 발생시킵니다.

input()
input(prompt)

prompt 인자가 있으면, 끝에 개행 문자를 붙이지 않고 표준 출력에 씁니다. 그런 다음 함수는 입력에서 한 줄을 읽고, 문자열로 변환해서 (줄 끝의 줄 바꿈 문자를 제거한다) 돌려줍니다. EOF를 읽으면 EOFError 를 일으킵니다. 예:

>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s  
"Monty Python's Flying Circus"

readline 모듈이 로드되었다면, input() 은 그것을 사용하여 정교한 줄 편집과 히스토리 기능을 제공합니다.

prompt 인자로 감사 이벤트(auditing event) builtins.input을 발생시킵니다.

result 인자로 감사 이벤트(auditing event) builtins.input/result를 발생시킵니다.

class int(x=0)
class int(x, base=10)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__(), int(x) returns x.__int__(). If x defines __index__(), it returns x.__index__(). If x defines __trunc__(), it returns x.__trunc__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer in radix base. Optionally, the string can be preceded by + or - (with no space in between), have leading zeros, be surrounded by whitespace, and have single underscores interspersed between digits.

A base-n integer string contains digits, each representing a value from 0 to n-1. The values 0–9 can be represented by any Unicode decimal digit. The values 10–35 can be represented by a to z (or A to Z). The default base is 10. The allowed bases are 0 and 2–36. Base-2, -8, and -16 strings can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. For base 0, the string is interpreted in a similar way to an integer literal in code, in that the actual base is 2, 8, 10, or 16 as determined by the prefix. Base 0 also disallows leading zeros: int('010', 0) is not legal, while int('010') and int('010', 8) are.

정수 형은 숫자 형 — int, float, complex 에 설명되어 있습니다.

버전 3.4에서 변경: baseint 의 인스턴스가 아니고 base 객체가 base.__index__ 메서드를 가지면, 그 진수로 쓸 정수를 얻기 위해 그 메서드를 호출합니다. 예전 버전에서는 base.__index__ 대신에 base.__int__ 가 사용되었습니다.

버전 3.6에서 변경: 코드 리터럴 처럼 숫자를 밑줄로 그룹화할 수 있습니다.

버전 3.7에서 변경: x는 이제 위치 전용 매개 변수입니다.

버전 3.8에서 변경: Falls back to __index__() if __int__() is not defined.

버전 3.11에서 변경: The delegation to __trunc__() is deprecated.

버전 3.11에서 변경: 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) or a Union Type of multiple types, 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. TypeError may not be raised for an invalid type if an earlier check succeeds.

버전 3.10에서 변경: classinfo can be a Union Type.

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 (or recursively, other such tuples) or a Union Type, in which case return True if class is a subclass of any entry in classinfo. In any other case, a TypeError exception is raised.

버전 3.10에서 변경: classinfo can be a Union Type.

iter(object)
iter(object, sentinel)

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object 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 at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

이터레이터 형 도 보세요.

두 번째 형태의 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 같은) 또는 컬렉션 (딕셔너리, 집합 또는 불변 집합 같은) 일 수 있습니다.

CPython 구현 상세: lenrange(2 ** 100)와 같이 sys.maxsize보다 긴 길이에서 OverflowError를 발생시킵니다.

class list
class list(iterable)

함수이기보다, 리스트시퀀스 형 — list, tuple, range 에 문서화 된 것처럼, list 는 실제로는 가변 시퀀스 형입니다.

locals()

현재 지역 심볼 테이블을 나타내는 딕셔너리를 갱신하고 돌려줍니다. locals() 이 함수 블록에서 호출될 때 자유 변수를 돌려주지만, 클래스 블록에서 호출할 때는 그렇지 않습니다. 모듈 수준에서 locals()globals()는 같은 딕셔너리임에 유의하십시오.

참고

이 딕셔너리의 내용은 수정해서는 안 됩니다. 변경 사항은 인터프리터가 사용하는 지역 및 자유 변수의 값에 영향을 미치지 않을 수 있습니다.

map(function, iterable, *iterables)

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. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().

max(iterable, *, key=None)
max(iterable, *, default, key=None)
max(arg1, arg2, *args, key=None)

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에서 변경: Added the default keyword-only parameter.

버전 3.8에서 변경: keyNone 일 수 있습니다.

class memoryview(object)

지정된 인자로부터 만들어진 “메모리 뷰” 객체를 돌려줍니다. 자세한 정보는 메모리 뷰 를 보세요.

min(iterable, *, key=None)
min(iterable, *, default, key=None)
min(arg1, arg2, *args, key=None)

iterable 에서 가장 작은 항목이나 두 개 이상의 인자 중 가장 작은 것을 돌려줍니다.

하나의 위치 인자가 제공되면, 그것은 이터러블 이어야 합니다. iterable에서 가장 작은 항목을 돌려줍니다. 두 개 이상의 위치 인자가 제공되면, 위치 인자 중 가장 작은 것을 돌려줍니다.

선택적 키워드-전용 인자가 두 개 있습니다. key 인자는 list.sort() 에 사용되는 것처럼 단일 인자 순서 함수를 지정합니다. default 인자는 제공된 iterable이 비어있는 경우 돌려줄 객체를 지정합니다. iterable이 비어 있고 default 가 제공되지 않으면 ValueError 가 발생합니다.

여러 항목이 최솟값이면, 함수는 처음 만난 항목을 돌려줍니다. 이것은 sorted(iterable, key=keyfunc)[0]heapq.nsmallest(1, iterable, key=keyfunc) 같은 다른 정렬 안정성 보존 도구와 일관성을 유지합니다.

버전 3.4에서 변경: Added the default keyword-only parameter.

버전 3.8에서 변경: keyNone 일 수 있습니다.

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, otherwise StopIteration is raised.

class object

Return a new featureless object. object is a base for all classes. It has methods that are common to all instances of Python classes. This function does not accept any arguments.

참고

object__dict__ 을 가지지 않습니다. 그래서, object 클래스의 인스턴스에 임의의 어트리뷰트를 대입할 수 없습니다.

oct(x)

Convert an integer number to an octal string prefixed with “0o”. The result is a valid Python expression. If x is not a Python int object, 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)

file 을 열고 해당 파일 객체 를 돌려줍니다. 파일을 열 수 없으면, OSError 가 발생합니다. 이 함수를 사용하는 방법에 대한 더 많은 예제는 파일을 읽고 쓰기를 참조하십시오.

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:

문자

의미

'r'

읽기용으로 엽니다 (기본값)

'w'

쓰기용으로 엽니다, 파일을 먼저 자릅니다.

'x'

독점적인 파일 만들기용으로 엽니다, 이미 존재하는 경우에는 실패합니다.

'a'

open for writing, appending to the end of file if it exists

'b'

바이너리 모드

't'

텍스트 모드 (기본값)

'+'

갱신(읽기 및 쓰기)용으로 엽니다

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.

개요 에서 언급했듯이, 파이썬은 바이너리와 텍스트 I/O를 구별합니다. 바이너리 모드 (mode 인자에 'b' 를 포함합니다)로 열린 파일은 내용을 디코딩 없이 bytes 객체로 돌려줍니다. 텍스트 모드 (기본값, 또는 mode 인자에 't' 가 포함될 때)에서는, 파일의 내용이 str로 반환되는데, 바이트열이 플랫폼 의존적인 인코딩이나 주어진 encoding 을 사용해서 먼저 디코드 됩니다.

참고

파이썬은 하위 운영 체제의 텍스트 파일 개념에 의존하지 않습니다. 모든 처리는 파이썬 자체에 의해 수행되므로 플랫폼에 독립적입니다.

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 with mode='r+') would have another buffering. To disable buffering in TextIOWrapper, consider using the write_through flag for io.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 chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.

  • “대화형” 텍스트 파일 (isatty()True 를 돌려주는 파일)은 줄 버퍼링을 사용합니다. 다른 텍스트 파일은 바이너리 파일에 대해 위에서 설명한 정책을 사용합니다.

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 the codecs module for the list of supported encodings.

errors 는 인코딩 및 디코딩 에러를 처리하는 방법을 지정하는 선택적 문자열입니다. 바이너리 모드에서는 사용할 수 없습니다. 다양한 표준 에러 처리기가 제공됩니다 (에러 처리기 에 나열됩니다). 하지만, codecs.register_error()로 등록된 에러 처리기 이름 역시 사용할 수 있습니다. 표준 이름은 다음과 같습니다:

  • 'strict' 는 인코딩 에러가 있는 경우 ValueError 예외를 발생시킵니다. 기본값 None 은 같은 효과를 냅니다.

  • 'ignore' 는 에러를 무시합니다. 인코딩 에러를 무시하면 데이터가 손실될 수 있음에 주의하세요.

  • 'replace' 는 잘못된 데이터가 있는 자리에 대체 마커('?' 와 같은)를 삽입합니다.

  • 'surrogateescape' will represent any incorrect bytes as low surrogate code units ranging from U+DC80 to U+DCFF. These surrogate code units will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.

  • 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn;.

  • 'backslashreplace' 는 잘못된 데이터를 파이썬의 역 슬래시 이스케이프 시퀀스로 대체합니다.

  • 'namereplace' (역시 파일에 쓸 때만 지원됩니다)는 지원되지 않는 문자를 \N{...} 이스케이프 시퀀스로 대체합니다.

newline determines how to parse newline characters from the stream. It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

  • 스트림에서 입력을 읽을 때, newlineNone 이면, 유니버설 줄 넘김 모드가 활성화됩니다. 입력에 있는 줄은 '\n', '\r' 또는 '\r\n' 로 끝날 수 있으며, 호출자에게 돌려주기 전에 모두 '\n' 로 변환됩니다. 그것이 '' 이면, 유니버설 줄 넘김 모드가 활성화되지만, 줄 끝은 변환되지 않은 채로 호출자에게 반환됩니다. 다른 유효한 값이면, 입력 줄은 주어진 문자열로만 끝나며, 줄 끝은 변환되지 않은 채로 호출자에게 돌려줍니다.

  • 스트림에 출력을 쓸 때, newlineNone 이면, 모든 '\n' 문자는 시스템 기본 줄 구분자인 os.linesep 로 변환됩니다. newline'' 또는 '\n' 이면, 변환이 이루어지지 않습니다. newline 이 다른 유효한 값이면, 쓰이는 모든 '\n' 문자는 주어진 문자열로 변환됩니다.

If closefd is False and 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 be True (the default); otherwise, an error will be raised.

콜러블을 opener 로 전달하여 커스텀 오프너를 사용할 수 있습니다. 파일 객체를 위한 하위 파일 디스크립터는 opener 를 (file, flags) 로 호출해서 얻습니다. opener 는 열린 파일 디스크립터를 반환해야 합니다 (openeros.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, 을 돌려줍니다.

See also the file handling modules, such as fileinput, io (where open() is declared), os, os.path, tempfile, and shutil.

file, mode, flags 인자로 감사 이벤트(auditing event) open을 발생시킵니다.

modeflags 인자는 원래 호출에서 수정되거나 추론되었을 수 있습니다.

버전 3.3에서 변경:

  • opener 매개변수가 추가되었습니다.

  • 'x' 모드가 추가되었습니다.

  • IOError 를 일으켜왔습니다. 이제는 OSError 의 별칭입니다.

  • 독점적 파일 만들기 모드('x')로 여는 파일이 이미 존재하면, 이제 FileExistsError 를 일으킵니다.

버전 3.4에서 변경:

  • 파일은 이제 상속 불가능합니다.

버전 3.5에서 변경:

  • 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 이 함수는 이제 InterruptedError 예외를 일으키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 를 보세요).

  • 'namereplace' 오류 처리기가 추가되었습니다.

버전 3.6에서 변경:

  • os.PathLike 를 구현하는 객체를 받아들이도록 지원이 추가되었습니다.

  • 윈도우에서, 콘솔 버퍼를 열면 io.FileIO 가 아닌 io.RawIOBase 의 서브 클래스가 반환될 수 있습니다.

버전 3.11에서 변경: The 'U' mode has been removed.

ord(c)

하나의 유니코드 문자를 나타내는 문자열이 주어지면 해당 문자의 유니코드 코드 포인트를 나타내는 정수를 돌려줍니다. 예를 들어, ord('a') 는 정수 97 을 반환하고 ord('€') (유로 기호)는 8364 를 반환합니다. 이것은 chr() 의 반대입니다.

pow(base, exp, mod=None)

baseexp 거듭제곱을 돌려줍니다; mod 가 있는 경우, baseexp 거듭제곱의 모듈로 mod 를 돌려줍니다 (pow(base, exp) % mod 보다 더 빠르게 계산됩니다). 두 개의 인자 형식인 pow(base, exp) 는 거듭제곱 연산자를 사용하는 것과 동등합니다: base**exp.

The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, 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) returns 100, but pow(10, -2) returns 0.01. For a negative base of type int or float and a non-integral exponent, a complex result is delivered. For example, pow(-9, 0.5) returns a value close to 3j.

int 피연산자 baseexp의 경우, mod가 있으면, mod도 정수 형이어야 하고 mod는 0이 아니어야 합니다. mod가 있고 exp가 음수면, basemod와 서로 소(relatively prime)여야 합니다. 이 경우, pow(inv_base, -exp, mod)가 반환되며, 여기서 inv_basebase 모듈로 mod의 역입니다.

다음은 38 모듈로 97의 역을 계산하는 예입니다:

>>> pow(38, -1, mod=97)
23
>>> 23 * 38 % 97 == 1
True

버전 3.8에서 변경: int 피연산자의 경우, pow의 3 인자 형식은 이제 두 번째 인자가 음수가 되는 것을 허용하여, 모듈러 역수를 계산할 수 있게 합니다.

버전 3.8에서 변경: 키워드 인자를 허용합니다. 이전에는, 위치 인자만 지원되었습니다.

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.

모든 비 키워드 인자는 str() 이 하듯이 문자열로 변환된 후 스트림에 쓰이는데, sep 로 구분되고 end 를 뒤에 붙입니다. sepend 는 모두 문자열이어야 합니다; None 일 수도 있는데, 기본값을 사용한다는 뜻입니다. objects 가 주어지지 않으면 print()end 만 씁니다.

file 인자는 write(string) 메서드를 가진 객체여야 합니다; 존재하지 않거나 None 이면, sys.stdout 이 사용됩니다. 인쇄된 인자는 텍스트 문자열로 변환되기 때문에, print() 는 바이너리 모드 파일 객체와 함께 사용할 수 없습니다. 이를 위해서는. 대신 file.write(...) 를 사용합니다.

Output buffering is usually determined by file. However, if flush is true, the stream is forcibly flushed.

버전 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.")

If c is an instance of C, c.x will invoke the getter, c.x = value will invoke the setter, and del c.x the deleter.

주어진 경우, doc 은 프로퍼티 어트리뷰트의 독스트링이 됩니다. 그렇지 않으면, fget 의 독스트링(있는 경우)이 복사됩니다. 이렇게 하면 property()데코레이터 로 사용하여 읽기 전용 프로퍼티를 쉽게 만들 수 있습니다:

class Parrot:
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

The @property decorator turns the voltage() 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, and deleter methods 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

이 코드는 첫 번째 예제와 정확히 동등합니다. 추가적인 함수들에 원래 프로퍼티(이 경우 x)와 같은 이름을 사용해야 합니다.

반환된 프로퍼티 객체는 생성자 인자에 해당하는 fget, fsetfdel 어트리뷰트를 가집니다.

버전 3.5에서 변경: 이제 프로퍼티 개체의 독스트링이 쓰기 가능합니다.

class range(stop)
class range(start, stop, step=1)

함수라기보다, range 는 실제로는 범위시퀀스 형 — 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. If sys.displayhook() is not accessible, this function will raise RuntimeError.

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}', {self.age})"
reversed(seq)

Return a reverse iterator. seq 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 at 0).

round(number, ndigits=None)

number 를 소수점 다음에 ndigits 정밀도로 반올림한 값을 돌려줍니다. ndigits 가 생략되거나 None 이면, 입력에 가장 가까운 정수를 돌려줍니다.

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, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise, the return value has the same type as number.

일반적인 파이썬 객체 number 의 경우, roundnumber.__round__ 에 위임합니다.

참고

float에 대한 round() 의 동작은 예상과 다를 수 있습니다: 예를 들어, round(2.675, 2)2.68 대신에 2.67 을 제공합니다. 이것은 버그가 아닙니다: 대부분의 십진 소수가 float로 정확히 표현될 수 없다는 사실로부터 오는 결과입니다. 자세한 정보는 부동 소수점 산술: 문제점 및 한계 를 보세요.

class set
class set(iterable)

set 객체를 돌려줍니다. 선택적으로 iterable 에서 가져온 요소를 갖습니다. set 은 내장 클래스입니다. 이 클래스에 대한 설명서는 set집합 형 — set, frozenset 을 보세요.

다른 컨테이너의 경우 내장 frozenset, list, tupledict 클래스와 collections 모듈을 보세요.

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 to x.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 through getattr() 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 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 to None.

start
stop
step

Slice objects have read-only data attributes start, stop, and step which merely return the argument values (or their default). They have no other explicit functionality; however, they are used by NumPy and other third-party packages.

Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

버전 3.12에서 변경: Slice objects are now hashable (provided start, stop, and step are hashable).

sorted(iterable, /, *, key=None, reverse=False)

iterable 의 항목들로 새 정렬된 리스트를 돌려줍니다.

키워드 인자로만 지정해야 하는 두 개의 선택적 인자가 있습니다.

key 는 하나의 인자를 받는 함수를 지정하는데, iterable의 각 요소들로부터 비교 키를 추출하는 데 사용됩니다 (예를 들어, key = str.lower). 기본값은 None 입니다 (요소를 직접 비교합니다).

reverse 는 논리값입니다. True 로 설정되면, 각 비교가 뒤집힌 것처럼 리스트 요소들이 정렬됩니다.

예전 스타일의 cmp 함수를 key 함수로 변환하려면 functools.cmp_to_key() 를 사용하세요.

내장 sorted() 함수는 안정적(stable)임이 보장됩니다. 정렬은 같다고 비교되는 요소의 상대적 순서를 변경하지 않으면 안정적입니다 — 이는 여러 번 정렬할 때 유용합니다 (예를 들어, 부서별로 정렬한 후에 급여 등급별로 정렬하기).

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 as max() that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call reflected the __gt__() method.

정렬 예제와 간단한 정렬 자습서는 Sorting Techniques 를 보세요.

@staticmethod

메서드를 정적 메서드로 변환합니다.

정적 메서드는 묵시적인 첫 번째 인자를 받지 않습니다. 정적 메서드를 선언하려면, 이 관용구를 사용하세요:

class C:
    @staticmethod
    def f(arg1, arg2, argN): ...

@staticmethod 형식은 함수 데코레이터 입니다 – 자세한 내용은 함수 정의를 보세요.

A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()). Moreover, they can be called as regular functions (such as f()).

Static methods in Python are similar to those found in Java or C++. Also, see classmethod() for a variant that is useful for creating alternate class constructors.

모든 데코레이터와 마찬가지로, staticmethod 를 정규 함수로 호출하여 그 결과로 어떤 일을 할 수도 있습니다. 이것은 클래스 바디에서 함수에 대한 참조가 필요하고 인스턴스 메서드로 자동 변환되는 것을 피하고자 할 때 필요합니다. 이 경우 다음 관용구를 사용하세요:

def regular_function():
    ...

class C:
    method = staticmethod(regular_function)

정적 메서드에 대한 더 자세한 정보는, 표준형 계층을 참조하세요.

버전 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(object='')
class str(object=b'', encoding='utf-8', errors='strict')

objectstr 버전을 돌려줍니다. 자세한 내용은 str() 을 보세요.

str 은 내장 문자열 클래스 입니다. 문자열에 대한 일반적인 정보는 텍스트 시퀀스 형 — str 를 보세요.

sum(iterable, /, start=0)

startiterable 의 항목들을 왼쪽에서 오른쪽으로 합하고 합계를 돌려줍니다. iterable 의 항목은 일반적으로 숫자며 시작 값은 문자열이 될 수 없습니다.

어떤 경우에는 sum() 에 대한 좋은 대안이 있습니다. 문자열의 시퀀스를 연결하는 가장 선호되고 빠른 방법은 ''.join(sequence) 를 호출하는 것입니다. 확장된 정밀도로 부동 소수점 값을 더하려면 math.fsum() 를 보세요. 일련의 이터러블들을 연결하려면 itertools.chain() 를 고려해보세요.

버전 3.8에서 변경: start 매개 변수는 키워드 인자로만 지정될 수 있습니다.

버전 3.12에서 변경: Summation of floats switched to an algorithm that gives higher accuracy on most builds.

class super
class super(type, object_or_type=None)

메서드 호출을 type 의 부모나 형제 클래스에 위임하는 프락시 객체를 돌려줍니다. 이는 클래스에서 재정의된 상속 된 메서드를 액세스할 때 유용합니다.

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 is D -> B -> C -> A -> object and the value of type is B, then super() searches C -> A -> object.

The __mro__ attribute of the object_or_type lists the method resolution search order used by both getattr() and super(). The attribute is dynamic and can change whenever the inheritance hierarchy is updated.

두 번째 인자가 생략되면, 반환되는 슈퍼 객체는 연결되지 않았습니다(unbound). 두 번째 인자가 객체면, isinstance(obj, type) 는 참이어야 합니다. 두 번째 인자가 형이면, issubclass(type2, type) 는 참이어야 합니다 (이것은 클래스 메서드에 유용합니다).

super 에는 두 가지 일반적인 사용 사례가 있습니다. 단일 상속 클래스 계층 구조에서는, super 를 사용하여 명시적으로 이름을 지정하지 않고 부모 클래스를 참조할 수 있으므로, 코드를 더 유지 관리하기 쉽게 만들 수 있습니다. 이 사용은 다른 프로그래밍 언어에서 super 를 쓰는 것과 매우 유사합니다.

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).

두 경우 모두, 일반적인 슈퍼 클래스 호출은 이런 식입니다:

class C(B):
    def method(self, arg):
        super().method(arg)    # This does the same thing as:
                               # super(C, self).method(arg)

메서드 조회 외에, super()는 어트리뷰트 조회에도 작동합니다. 한가지 가능한 사용 사례는 부모나 형제 클래스에 있는 디스크립터를 호출하는 것입니다.

Note that super() is implemented as part of the binding process for explicit dotted attribute lookups such as super().__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 as super()[name].

또한, 인자가 없는 형식을 제외하고는, super() 는 메서드 내부에서만 사용하도록 제한되지 않는다는 점에 유의하세요. 두 개의 인자 형식은 인자를 정확하게 지정하고 적절한 참조를 만듭니다. 인자가 없는 형식은 클래스 정의 내에서만 작동하는데, 컴파일러가 정의되고 있는 클래스를 올바르게 가져오고 일반 메서드에서 현재 인스턴스에 액세스하는 데 필요한 세부 정보를 채우기 때문입니다.

super()를 사용하여 협력적 클래스를 설계하는 방법에 대한 실용적인 제안은 super() 사용 안내 를 보세요.

class tuple
class tuple(iterable)

함수이기보다, tuple 은 실제로 튜플시퀀스 형 — list, tuple, range 에 문서화 된 것처럼 불변 시퀀스 형입니다.

class type(object)
class type(name, bases, dict, **kwds)

인자 하나의 경우, object 의 형을 돌려줍니다. 반환 값은 형 객체며 일반적으로 object.__class__ 가 돌려주는 것과 같은 객체입니다.

객체의 형을 검사하는 데는 isinstance() 내장 함수가 권장되는데, 서브 클래스를 고려하기 때문입니다.

세 개의 인자를 주는 경우, 새 형 객체를 돌려줍니다. 이것은 본래 class 문의 동적인 형태입니다. name 문자열은 클래스 이름이고 __name__ 어트리뷰트가 됩니다. bases 튜플은 베이스 클래스들을 포함하고 __bases__ 어트리뷰트가 됩니다; 비어 있으면, object, 모든 클래스의 궁극적인 베이스가 추가됩니다. dict 딕셔너리는 클래스 바디의 어트리뷰트와 메서드 정의들을 포함합니다; __dict__ 어트리뷰트가 되기 전에 복사되거나 감싸질 수 있습니다. 다음 두 문장은 같은 type 객체를 만듭니다:

>>> class X:
...     a = 1
...
>>> X = type('X', (), dict(a=1))

형 객체를 보세요.

세 인자 형식에 제공된 키워드 인자는 클래스 정의의 (metaclass 를 제외한) 키워드와 같은 방식으로 적절한 메타 클래스 장치(일반적으로 __init_subclass__())에 전달됩니다.

클래스 생성 커스터마이제이션 도 보세요.

버전 3.6에서 변경: type.__new__ 를 재정의하지 않는 type 의 서브 클래스는 이제 객체의 형을 얻기 위해 하나의 인자 형식을 사용할 수 없습니다.

vars()
vars(object)

모듈, 클래스, 인스턴스 또는 __dict__ 어트리뷰트가 있는 다른 객체의 __dict__ 어트리뷰트를 돌려줍니다.

모듈 및 인스턴스와 같은 객체는 업데이트 가능한 __dict__ 어트리뷰트를 갖습니다; 그러나, 다른 객체는 __dict__ 어트리뷰트에 쓰기 제한을 가질 수 있습니다 (예를 들어, 클래스는 직접적인 딕셔너리 갱신을 방지하기 위해 types.MappingProxyType 를 사용합니다).

인자가 없으면, vars()locals() 처럼 동작합니다. locals 딕셔너리에 대한 변경이 무시되기 때문에 locals 딕셔너리는 읽기에만 유용하다는 것에 주의하세요.

객체가 지정되었지만 __dict__ 어트리뷰트가 없으면 TypeError 예외가 발생합니다 (예를 들어, 해당 클래스가 __slots__ 어트리뷰트를 정의하면).

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 a for loop or by wrapping in a list.

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 the strict=True option. Its output is the same as regular zip():

    >>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True))
    [('a', 1), ('b', 2), ('c', 3)]
    

    Unlike the default behavior, it raises a ValueError if 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=True argument, 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 iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks.

  • zip()* 연산자와 함께 쓰면 리스트를 unzip 할 수 있습니다:

    >>> 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 strict argument.

__import__(name, globals=None, locals=None, fromlist=(), level=0)

참고

이것은 importlib.import_module() 과 달리 일상적인 파이썬 프로그래밍에서는 필요하지 않은 고급 함수입니다.

이 함수는 import 문에 의해 호출됩니다. import 문의 의미를 변경하기 위해 대체할 수 있습니다 (builtins 모듈을 임포트하고 builtins .__ import__ 에 대입합니다). 그러나 그렇게 하지 말 것을 강하게 권고하는데, 보통 같은 목적을 달성하는데 임포트 훅(PEP 302 를 보세요)을 사용하는 것이 더 간단하고 기본 임포트 구현이 사용될 것이라고 가정하는 코드들과 문제를 일으키지 않기 때문입니다. __import__() 의 직접 사용 역시 피하고 importlib.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 import statement.

level 은 절대 또는 상대 임포트를 사용할지를 지정합니다. 0 (기본값)은 오직 절대 임포트를 수행한다는 것을 의미합니다. 양수 값 level__import__() 를 호출하는 모듈 디렉터리에 상대적으로 검색할 상위 디렉터리들의 개수를 가리킵니다 (자세한 내용은 PEP 328을 보세요).

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으로 변경합니다).

버전 3.9에서 변경: 명령 줄 옵션 -E-I를 사용 중일 때, 환경 변수 PYTHONCASEOK는 이제 무시됩니다.

각주