summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Ffunctions.html
blob: 9e7ce083dd2e6e3c6ac8b9ab188a764bfb4caa41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
 <span id="built-in-funcs"></span><h1>Built-in Functions</h1> <p>The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.</p> <table class="docutils align-default">  <thead> <tr>
<th class="head" colspan="4"><p>Built-in Functions</p></th> </tr> </thead>  <tr>
<td> </td> <td> </td> <td> </td> <td> </td> </tr>  </table> <dl class="py function"> <dt class="sig sig-object py" id="abs">
<code>abs(x)</code> </dt> <dd>
<p>Return the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing <a class="reference internal" href="../reference/datamodel#object.__abs__" title="object.__abs__"><code>__abs__()</code></a>. If the argument is a complex number, its magnitude is returned.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="aiter">
<code>aiter(async_iterable)</code> </dt> <dd>
<p>Return an <a class="reference internal" href="../glossary#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a> for an <a class="reference internal" href="../glossary#term-asynchronous-iterable"><span class="xref std std-term">asynchronous iterable</span></a>. Equivalent to calling <code>x.__aiter__()</code>.</p> <p>Note: Unlike <a class="reference internal" href="#iter" title="iter"><code>iter()</code></a>, <a class="reference internal" href="#aiter" title="aiter"><code>aiter()</code></a> has no 2-argument variant.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="all">
<code>all(iterable)</code> </dt> <dd>
<p>Return <code>True</code> if all elements of the <em>iterable</em> are true (or if the iterable is empty). Equivalent to:</p> <pre data-language="python">def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
</pre> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="anext">
<code>awaitable anext(async_iterator)</code> </dt> <dt class="sig sig-object py"> <em class="property">awaitable </em><span class="sig-name descname">anext</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">async_iterator</span></em>, <em class="sig-param"><span class="n">default</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>When awaited, return the next item from the given <a class="reference internal" href="../glossary#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a>, or <em>default</em> if given and the iterator is exhausted.</p> <p>This is the async variant of the <a class="reference internal" href="#next" title="next"><code>next()</code></a> builtin, and behaves similarly.</p> <p>This calls the <a class="reference internal" href="../reference/datamodel#object.__anext__" title="object.__anext__"><code>__anext__()</code></a> method of <em>async_iterator</em>, returning an <a class="reference internal" href="../glossary#term-awaitable"><span class="xref std std-term">awaitable</span></a>. Awaiting this returns the next value of the iterator. If <em>default</em> is given, it is returned if the iterator is exhausted, otherwise <a class="reference internal" href="exceptions#StopAsyncIteration" title="StopAsyncIteration"><code>StopAsyncIteration</code></a> is raised.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="any">
<code>any(iterable)</code> </dt> <dd>
<p>Return <code>True</code> if any element of the <em>iterable</em> is true. If the iterable is empty, return <code>False</code>. Equivalent to:</p> <pre data-language="python">def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
</pre> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ascii">
<code>ascii(object)</code> </dt> <dd>
<p>As <a class="reference internal" href="#repr" title="repr"><code>repr()</code></a>, return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by <a class="reference internal" href="#repr" title="repr"><code>repr()</code></a> using <code>\x</code>, <code>\u</code>, or <code>\U</code> escapes. This generates a string similar to that returned by <a class="reference internal" href="#repr" title="repr"><code>repr()</code></a> in Python 2.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="bin">
<code>bin(x)</code> </dt> <dd>
<p>Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If <em>x</em> is not a Python <a class="reference internal" href="#int" title="int"><code>int</code></a> object, it has to define an <a class="reference internal" href="../reference/datamodel#object.__index__" title="object.__index__"><code>__index__()</code></a> method that returns an integer. Some examples:</p> <pre data-language="python">&gt;&gt;&gt; bin(3)
'0b11'
&gt;&gt;&gt; bin(-10)
'-0b1010'
</pre> <p>If the prefix “0b” is desired or not, you can use either of the following ways.</p> <pre data-language="python">&gt;&gt;&gt; format(14, '#b'), format(14, 'b')
('0b1110', '1110')
&gt;&gt;&gt; f'{14:#b}', f'{14:b}'
('0b1110', '1110')
</pre> <p>See also <a class="reference internal" href="#format" title="format"><code>format()</code></a> for more information.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="bool">
<code>class bool(x=False)</code> </dt> <dd>
<p>Return a Boolean value, i.e. one of <code>True</code> or <code>False</code>. <em>x</em> is converted using the standard <a class="reference internal" href="stdtypes#truth"><span class="std std-ref">truth testing procedure</span></a>. If <em>x</em> is false or omitted, this returns <code>False</code>; otherwise, it returns <code>True</code>. The <a class="reference internal" href="#bool" title="bool"><code>bool</code></a> class is a subclass of <a class="reference internal" href="#int" title="int"><code>int</code></a> (see <a class="reference internal" href="stdtypes#typesnumeric"><span class="std std-ref">Numeric Types — int, float, complex</span></a>). It cannot be subclassed further. Its only instances are <code>False</code> and <code>True</code> (see <a class="reference internal" href="stdtypes#typebool"><span class="std std-ref">Boolean Type - bool</span></a>).</p> <div class="versionchanged" id="index-0"> <p><span class="versionmodified changed">Changed in version 3.7: </span><em>x</em> is now a positional-only parameter.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="breakpoint">
<code>breakpoint(*args, **kws)</code> </dt> <dd>
<p>This function drops you into the debugger at the call site. Specifically, it calls <a class="reference internal" href="sys#sys.breakpointhook" title="sys.breakpointhook"><code>sys.breakpointhook()</code></a>, passing <code>args</code> and <code>kws</code> straight through. By default, <code>sys.breakpointhook()</code> calls <a class="reference internal" href="pdb#pdb.set_trace" title="pdb.set_trace"><code>pdb.set_trace()</code></a> expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import <a class="reference internal" href="pdb#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code>pdb</code></a> or type as much code to enter the debugger. However, <a class="reference internal" href="sys#sys.breakpointhook" title="sys.breakpointhook"><code>sys.breakpointhook()</code></a> can be set to some other function and <a class="reference internal" href="#breakpoint" title="breakpoint"><code>breakpoint()</code></a> will automatically call that, allowing you to drop into the debugger of choice. If <a class="reference internal" href="sys#sys.breakpointhook" title="sys.breakpointhook"><code>sys.breakpointhook()</code></a> is not accessible, this function will raise <a class="reference internal" href="exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a>.</p> <p>By default, the behavior of <a class="reference internal" href="#breakpoint" title="breakpoint"><code>breakpoint()</code></a> can be changed with the <span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline#envvar-PYTHONBREAKPOINT"><code>PYTHONBREAKPOINT</code></a> environment variable. See <a class="reference internal" href="sys#sys.breakpointhook" title="sys.breakpointhook"><code>sys.breakpointhook()</code></a> for usage details.</p> <p>Note that this is not guaranteed if <a class="reference internal" href="sys#sys.breakpointhook" title="sys.breakpointhook"><code>sys.breakpointhook()</code></a> has been replaced.</p> <p class="audit-hook">Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>builtins.breakpoint</code> with argument <code>breakpointhook</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <span class="target" id="func-bytearray"></span><dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">bytearray</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">source</span><span class="o">=</span><span class="default_value">b''</span></em><span class="sig-paren">)</span>
</dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">bytearray</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">source</span></em>, <em class="sig-param"><span class="n">encoding</span></em><span class="sig-paren">)</span>
</dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">bytearray</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">source</span></em>, <em class="sig-param"><span class="n">encoding</span></em>, <em class="sig-param"><span class="n">errors</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return a new array of bytes. The <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a> class is a mutable sequence of integers in the range 0 &lt;= x &lt; 256. It has most of the usual methods of mutable sequences, described in <a class="reference internal" href="stdtypes#typesseq-mutable"><span class="std std-ref">Mutable Sequence Types</span></a>, as well as most methods that the <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> type has, see <a class="reference internal" href="stdtypes#bytes-methods"><span class="std std-ref">Bytes and Bytearray Operations</span></a>.</p> <p>The optional <em>source</em> parameter can be used to initialize the array in a few different ways:</p> <ul class="simple"> <li>If it is a <em>string</em>, you must also give the <em>encoding</em> (and optionally, <em>errors</em>) parameters; <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray()</code></a> then converts the string to bytes using <a class="reference internal" href="stdtypes#str.encode" title="str.encode"><code>str.encode()</code></a>.</li> <li>If it is an <em>integer</em>, the array will have that size and will be initialized with null bytes.</li> <li>If it is an object conforming to the <a class="reference internal" href="../c-api/buffer#bufferobjects"><span class="std std-ref">buffer interface</span></a>, a read-only buffer of the object will be used to initialize the bytes array.</li> <li>If it is an <em>iterable</em>, it must be an iterable of integers in the range <code>0 &lt;= x &lt; 256</code>, which are used as the initial contents of the array.</li> </ul> <p>Without an argument, an array of size 0 is created.</p> <p>See also <a class="reference internal" href="stdtypes#binaryseq"><span class="std std-ref">Binary Sequence Types — bytes, bytearray, memoryview</span></a> and <a class="reference internal" href="stdtypes#typebytearray"><span class="std std-ref">Bytearray Objects</span></a>.</p> </dd>
</dl> <span class="target" id="func-bytes"></span><dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">bytes</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">source</span><span class="o">=</span><span class="default_value">b''</span></em><span class="sig-paren">)</span>
</dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">bytes</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">source</span></em>, <em class="sig-param"><span class="n">encoding</span></em><span class="sig-paren">)</span>
</dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">bytes</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">source</span></em>, <em class="sig-param"><span class="n">encoding</span></em>, <em class="sig-param"><span class="n">errors</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return a new “bytes” object which is an immutable sequence of integers in the range <code>0 &lt;= x &lt; 256</code>. <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> is an immutable version of <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a> – it has the same non-mutating methods and the same indexing and slicing behavior.</p> <p>Accordingly, constructor arguments are interpreted as for <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray()</code></a>.</p> <p>Bytes objects can also be created with literals, see <a class="reference internal" href="../reference/lexical_analysis#strings"><span class="std std-ref">String and Bytes literals</span></a>.</p> <p>See also <a class="reference internal" href="stdtypes#binaryseq"><span class="std std-ref">Binary Sequence Types — bytes, bytearray, memoryview</span></a>, <a class="reference internal" href="stdtypes#typebytes"><span class="std std-ref">Bytes Objects</span></a>, and <a class="reference internal" href="stdtypes#bytes-methods"><span class="std std-ref">Bytes and Bytearray Operations</span></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="callable">
<code>callable(object)</code> </dt> <dd>
<p>Return <a class="reference internal" href="constants#True" title="True"><code>True</code></a> if the <em>object</em> argument appears callable, <a class="reference internal" href="constants#False" title="False"><code>False</code></a> if not. If this returns <code>True</code>, it is still possible that a call fails, but if it is <code>False</code>, calling <em>object</em> will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a <a class="reference internal" href="../reference/datamodel#object.__call__" title="object.__call__"><code>__call__()</code></a> method.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2: </span>This function was first removed in Python 3.0 and then brought back in Python 3.2.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="chr">
<code>chr(i)</code> </dt> <dd>
<p>Return the string representing a character whose Unicode code point is the integer <em>i</em>. For example, <code>chr(97)</code> returns the string <code>'a'</code>, while <code>chr(8364)</code> returns the string <code>'€'</code>. This is the inverse of <a class="reference internal" href="#ord" title="ord"><code>ord()</code></a>.</p> <p>The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> will be raised if <em>i</em> is outside that range.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="classmethod">
<code>@classmethod</code> </dt> <dd>
<p>Transform a method into a class method.</p> <p>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:</p> <pre data-language="python">class C:
    @classmethod
    def f(cls, arg1, arg2): ...
</pre> <p>The <code>@classmethod</code> form is a function <a class="reference internal" href="../glossary#term-decorator"><span class="xref std std-term">decorator</span></a> – see <a class="reference internal" href="../reference/compound_stmts#function"><span class="std std-ref">Function definitions</span></a> for details.</p> <p>A class method can be called either on the class (such as <code>C.f()</code>) or on an instance (such as <code>C().f()</code>). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.</p> <p>Class methods are different than C++ or Java static methods. If you want those, see <a class="reference internal" href="#staticmethod" title="staticmethod"><code>staticmethod()</code></a> in this section. For more information on class methods, see <a class="reference internal" href="../reference/datamodel#types"><span class="std std-ref">The standard type hierarchy</span></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Class methods can now wrap other <a class="reference internal" href="../glossary#term-descriptor"><span class="xref std std-term">descriptors</span></a> such as <a class="reference internal" href="#property" title="property"><code>property()</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Class methods now inherit the method attributes (<code>__module__</code>, <code>__name__</code>, <code>__qualname__</code>, <code>__doc__</code> and <code>__annotations__</code>) and have a new <code>__wrapped__</code> attribute.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Class methods can no longer wrap other <a class="reference internal" href="../glossary#term-descriptor"><span class="xref std std-term">descriptors</span></a> such as <a class="reference internal" href="#property" title="property"><code>property()</code></a>.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="compile">
<code>compile(source, filename, mode, flags=0, dont_inherit=False, optimize=- 1)</code> </dt> <dd>
<p>Compile the <em>source</em> into a code or AST object. Code objects can be executed by <a class="reference internal" href="#exec" title="exec"><code>exec()</code></a> or <a class="reference internal" href="#eval" title="eval"><code>eval()</code></a>. <em>source</em> can either be a normal string, a byte string, or an AST object. Refer to the <a class="reference internal" href="ast#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code>ast</code></a> module documentation for information on how to work with AST objects.</p> <p>The <em>filename</em> argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file (<code>'&lt;string&gt;'</code> is commonly used).</p> <p>The <em>mode</em> argument specifies what kind of code must be compiled; it can be <code>'exec'</code> if <em>source</em> consists of a sequence of statements, <code>'eval'</code> if it consists of a single expression, or <code>'single'</code> if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than <code>None</code> will be printed).</p> <p>The optional arguments <em>flags</em> and <em>dont_inherit</em> control which <a class="reference internal" href="ast#ast-compiler-flags"><span class="std std-ref">compiler options</span></a> should be activated and which <a class="reference internal" href="../reference/simple_stmts#future"><span class="std std-ref">future features</span></a> should be allowed. If neither is present (or both are zero) the code is compiled with the same flags that affect the code that is calling <a class="reference internal" href="#compile" title="compile"><code>compile()</code></a>. If the <em>flags</em> argument is given and <em>dont_inherit</em> is not (or is zero) then the compiler options and the future statements specified by the <em>flags</em> argument are used in addition to those that would be used anyway. If <em>dont_inherit</em> is a non-zero integer then the <em>flags</em> argument is it – the flags (future features and compiler options) in the surrounding code are ignored.</p> <p>Compiler options and future statements are specified by bits which can be bitwise ORed together to specify multiple options. The bitfield required to specify a given future feature can be found as the <a class="reference internal" href="__future__#future__._Feature.compiler_flag" title="__future__._Feature.compiler_flag"><code>compiler_flag</code></a> attribute on the <a class="reference internal" href="__future__#future__._Feature" title="__future__._Feature"><code>_Feature</code></a> instance in the <a class="reference internal" href="__future__#module-__future__" title="__future__: Future statement definitions"><code>__future__</code></a> module. <a class="reference internal" href="ast#ast-compiler-flags"><span class="std std-ref">Compiler flags</span></a> can be found in <a class="reference internal" href="ast#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code>ast</code></a> module, with <code>PyCF_</code> prefix.</p> <p>The argument <em>optimize</em> specifies the optimization level of the compiler; the default value of <code>-1</code> selects the optimization level of the interpreter as given by <a class="reference internal" href="../using/cmdline#cmdoption-O"><code>-O</code></a> options. Explicit levels are <code>0</code> (no optimization; <code>__debug__</code> is true), <code>1</code> (asserts are removed, <code>__debug__</code> is false) or <code>2</code> (docstrings are removed too).</p> <p>This function raises <a class="reference internal" href="exceptions#SyntaxError" title="SyntaxError"><code>SyntaxError</code></a> if the compiled source is invalid, and <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> if the source contains null bytes.</p> <p>If you want to parse Python code into its AST representation, see <a class="reference internal" href="ast#ast.parse" title="ast.parse"><code>ast.parse()</code></a>.</p> <p class="audit-hook"></p>
<p>Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>compile</code> with arguments <code>source</code> and <code>filename</code>. This event may also be raised by implicit compilation.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>When compiling a string with multi-line code in <code>'single'</code> or <code>'eval'</code> mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the <a class="reference internal" href="code#module-code" title="code: Facilities to implement read-eval-print loops."><code>code</code></a> module.</p> </div> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>It is possible to crash the Python interpreter with a sufficiently large/complex string when compiling to an AST object due to stack depth limitations in Python’s AST compiler.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Allowed use of Windows and Mac newlines. Also, input in <code>'exec'</code> mode does not have to end in a newline anymore. Added the <em>optimize</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Previously, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> was raised when null bytes were encountered in <em>source</em>.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8: </span><code>ast.PyCF_ALLOW_TOP_LEVEL_AWAIT</code> can now be passed in flags to enable support for top-level <code>await</code>, <code>async for</code>, and <code>async with</code>.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="complex">
<code>class complex(real=0, imag=0)</code> </dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">complex</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">string</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return a complex number with the value <em>real</em> + <em>imag</em>*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If <em>imag</em> is omitted, it defaults to zero and the constructor serves as a numeric conversion like <a class="reference internal" href="#int" title="int"><code>int</code></a> and <a class="reference internal" href="#float" title="float"><code>float</code></a>. If both arguments are omitted, returns <code>0j</code>.</p> <p>For a general Python object <code>x</code>, <code>complex(x)</code> delegates to <code>x.__complex__()</code>. If <a class="reference internal" href="../reference/datamodel#object.__complex__" title="object.__complex__"><code>__complex__()</code></a> is not defined then it falls back to <a class="reference internal" href="../reference/datamodel#object.__float__" title="object.__float__"><code>__float__()</code></a>. If <code>__float__()</code> is not defined then it falls back to <a class="reference internal" href="../reference/datamodel#object.__index__" title="object.__index__"><code>__index__()</code></a>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>When converting from a string, the string must not contain whitespace around the central <code>+</code> or <code>-</code> operator. For example, <code>complex('1+2j')</code> is fine, but <code>complex('1 + 2j')</code> raises <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a>.</p> </div> <p>The complex type is described in <a class="reference internal" href="stdtypes#typesnumeric"><span class="std std-ref">Numeric Types — int, float, complex</span></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Grouping digits with underscores as in code literals is allowed.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Falls back to <a class="reference internal" href="../reference/datamodel#object.__index__" title="object.__index__"><code>__index__()</code></a> if <a class="reference internal" href="../reference/datamodel#object.__complex__" title="object.__complex__"><code>__complex__()</code></a> and <a class="reference internal" href="../reference/datamodel#object.__float__" title="object.__float__"><code>__float__()</code></a> are not defined.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="delattr">
<code>delattr(object, name)</code> </dt> <dd>
<p>This is a relative of <a class="reference internal" href="#setattr" title="setattr"><code>setattr()</code></a>. 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, <code>delattr(x, 'foobar')</code> is equivalent to <code>del x.foobar</code>. <em>name</em> need not be a Python identifier (see <a class="reference internal" href="#setattr" title="setattr"><code>setattr()</code></a>).</p> </dd>
</dl> <span class="target" id="func-dict"></span><dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">dict</span><span class="sig-paren">(</span><em class="sig-param"><span class="o">**</span><span class="n">kwarg</span></em><span class="sig-paren">)</span>
</dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">dict</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">mapping</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwarg</span></em><span class="sig-paren">)</span>
</dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">dict</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">iterable</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwarg</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Create a new dictionary. The <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> object is the dictionary class. See <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> and <a class="reference internal" href="stdtypes#typesmapping"><span class="std std-ref">Mapping Types — dict</span></a> for documentation about this class.</p> <p>For other containers see the built-in <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a>, <a class="reference internal" href="stdtypes#set" title="set"><code>set</code></a>, and <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> classes, as well as the <a class="reference internal" href="collections#module-collections" title="collections: Container datatypes"><code>collections</code></a> module.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="dir">
<code>dir()</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">dir</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">object</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.</p> <p>If the object has a method named <a class="reference internal" href="../reference/datamodel#object.__dir__" title="object.__dir__"><code>__dir__()</code></a>, this method will be called and must return the list of attributes. This allows objects that implement a custom <a class="reference internal" href="../reference/datamodel#object.__getattr__" title="object.__getattr__"><code>__getattr__()</code></a> or <a class="reference internal" href="../reference/datamodel#object.__getattribute__" title="object.__getattribute__"><code>__getattribute__()</code></a> function to customize the way <a class="reference internal" href="#dir" title="dir"><code>dir()</code></a> reports their attributes.</p> <p>If the object does not provide <a class="reference internal" href="../reference/datamodel#object.__dir__" title="object.__dir__"><code>__dir__()</code></a>, the function tries its best to gather information from the object’s <a class="reference internal" href="stdtypes#object.__dict__" title="object.__dict__"><code>__dict__</code></a> 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 <a class="reference internal" href="../reference/datamodel#object.__getattr__" title="object.__getattr__"><code>__getattr__()</code></a>.</p> <p>The default <a class="reference internal" href="#dir" title="dir"><code>dir()</code></a> mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:</p> <ul class="simple"> <li>If the object is a module object, the list contains the names of the module’s attributes.</li> <li>If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.</li> <li>Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.</li> </ul> <p>The resulting list is sorted alphabetically. For example:</p> <pre data-language="python">&gt;&gt;&gt; import struct
&gt;&gt;&gt; dir()   # show the names in the module namespace  
['__builtins__', '__name__', 'struct']
&gt;&gt;&gt; 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']
&gt;&gt;&gt; class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
...
&gt;&gt;&gt; s = Shape()
&gt;&gt;&gt; dir(s)
['area', 'location', 'perimeter']
</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Because <a class="reference internal" href="#dir" title="dir"><code>dir()</code></a> is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="divmod">
<code>divmod(a, b)</code> </dt> <dd>
<p>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 <code>(a // b, a % b)</code>. For floating point numbers the result is <code>(q, a % b)</code>, where <em>q</em> is usually <code>math.floor(a /
b)</code> but may be 1 less than that. In any case <code>q * b + a % b</code> is very close to <em>a</em>, if <code>a % b</code> is non-zero it has the same sign as <em>b</em>, and <code>0
&lt;= abs(a % b) &lt; abs(b)</code>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="enumerate">
<code>enumerate(iterable, start=0)</code> </dt> <dd>
<p>Return an enumerate object. <em>iterable</em> must be a sequence, an <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a>, or some other object which supports iteration. The <a class="reference internal" href="stdtypes#iterator.__next__" title="iterator.__next__"><code>__next__()</code></a> method of the iterator returned by <a class="reference internal" href="#enumerate" title="enumerate"><code>enumerate()</code></a> returns a tuple containing a count (from <em>start</em> which defaults to 0) and the values obtained from iterating over <em>iterable</em>.</p> <pre data-language="python">&gt;&gt;&gt; seasons = ['Spring', 'Summer', 'Fall', 'Winter']
&gt;&gt;&gt; list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
&gt;&gt;&gt; list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
</pre> <p>Equivalent to:</p> <pre data-language="python">def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1
</pre> </dd>
</dl> <span class="target" id="func-eval"></span><dl class="py function"> <dt class="sig sig-object py" id="eval">
<code>eval(expression, globals=None, locals=None)</code> </dt> <dd>
<p>The arguments are a string and optional globals and locals. If provided, <em>globals</em> must be a dictionary. If provided, <em>locals</em> can be any mapping object.</p> <p>The <em>expression</em> argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the <em>globals</em> and <em>locals</em> dictionaries as global and local namespace. If the <em>globals</em> dictionary is present and does not contain a value for the key <code>__builtins__</code>, a reference to the dictionary of the built-in module <a class="reference internal" href="builtins#module-builtins" title="builtins: The module that provides the built-in namespace."><code>builtins</code></a> is inserted under that key before <em>expression</em> is parsed. That way you can control what builtins are available to the executed code by inserting your own <code>__builtins__</code> dictionary into <em>globals</em> before passing it to <a class="reference internal" href="#eval" title="eval"><code>eval()</code></a>. If the <em>locals</em> dictionary is omitted it defaults to the <em>globals</em> dictionary. If both dictionaries are omitted, the expression is executed with the <em>globals</em> and <em>locals</em> in the environment where <a class="reference internal" href="#eval" title="eval"><code>eval()</code></a> is called. Note, <em>eval()</em> does not have access to the <a class="reference internal" href="../glossary#term-nested-scope"><span class="xref std std-term">nested scopes</span></a> (non-locals) in the enclosing environment.</p> <p>The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:</p> <pre data-language="python">&gt;&gt;&gt; x = 1
&gt;&gt;&gt; eval('x+1')
2
</pre> <p>This function can also be used to execute arbitrary code objects (such as those created by <a class="reference internal" href="#compile" title="compile"><code>compile()</code></a>). In this case, pass a code object instead of a string. If the code object has been compiled with <code>'exec'</code> as the <em>mode</em> argument, <a class="reference internal" href="#eval" title="eval"><code>eval()</code></a>'s return value will be <code>None</code>.</p> <p>Hints: dynamic execution of statements is supported by the <a class="reference internal" href="#exec" title="exec"><code>exec()</code></a> function. The <a class="reference internal" href="#globals" title="globals"><code>globals()</code></a> and <a class="reference internal" href="#locals" title="locals"><code>locals()</code></a> functions return the current global and local dictionary, respectively, which may be useful to pass around for use by <a class="reference internal" href="#eval" title="eval"><code>eval()</code></a> or <a class="reference internal" href="#exec" title="exec"><code>exec()</code></a>.</p> <p>If the given source is a string, then leading and trailing spaces and tabs are stripped.</p> <p>See <a class="reference internal" href="ast#ast.literal_eval" title="ast.literal_eval"><code>ast.literal_eval()</code></a> for a function that can safely evaluate strings with expressions containing only literals.</p> <p class="audit-hook"></p>
<p>Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>exec</code> with the code object as the argument. Code compilation events may also be raised.</p> </dd>
</dl> <span class="target" id="index-2"></span><dl class="py function"> <dt class="sig sig-object py" id="exec">
<code>exec(object, globals=None, locals=None, /, *, closure=None)</code> </dt> <dd>
<p>This function supports dynamic execution of Python code. <em>object</em> 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). <a class="footnote-reference brackets" href="#id2" id="id1">1</a> 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 <a class="reference internal" href="../reference/toplevel_components#file-input"><span class="std std-ref">File input</span></a> in the Reference Manual). Be aware that the <a class="reference internal" href="../reference/simple_stmts#nonlocal"><code>nonlocal</code></a>, <a class="reference internal" href="../reference/simple_stmts#yield"><code>yield</code></a>, and <a class="reference internal" href="../reference/simple_stmts#return"><code>return</code></a> statements may not be used outside of function definitions even within the context of code passed to the <a class="reference internal" href="#exec" title="exec"><code>exec()</code></a> function. The return value is <code>None</code>.</p> <p>In all cases, if the optional parts are omitted, the code is executed in the current scope. If only <em>globals</em> 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 <em>globals</em> and <em>locals</em> are given, they are used for the global and local variables, respectively. If provided, <em>locals</em> 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 <em>globals</em> and <em>locals</em>, the code will be executed as if it were embedded in a class definition.</p> <p>If the <em>globals</em> dictionary does not contain a value for the key <code>__builtins__</code>, a reference to the dictionary of the built-in module <a class="reference internal" href="builtins#module-builtins" title="builtins: The module that provides the built-in namespace."><code>builtins</code></a> is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own <code>__builtins__</code> dictionary into <em>globals</em> before passing it to <a class="reference internal" href="#exec" title="exec"><code>exec()</code></a>.</p> <p>The <em>closure</em> argument specifies a closure–a tuple of cellvars. It’s only valid when the <em>object</em> 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.</p> <p class="audit-hook"></p>
<p>Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>exec</code> with the code object as the argument. Code compilation events may also be raised.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The built-in functions <a class="reference internal" href="#globals" title="globals"><code>globals()</code></a> and <a class="reference internal" href="#locals" title="locals"><code>locals()</code></a> return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to <a class="reference internal" href="#exec" title="exec"><code>exec()</code></a>.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The default <em>locals</em> act as described for function <a class="reference internal" href="#locals" title="locals"><code>locals()</code></a> below: modifications to the default <em>locals</em> dictionary should not be attempted. Pass an explicit <em>locals</em> dictionary if you need to see effects of the code on <em>locals</em> after function <a class="reference internal" href="#exec" title="exec"><code>exec()</code></a> returns.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>closure</em> parameter.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="filter">
<code>filter(function, iterable)</code> </dt> <dd>
<p>Construct an iterator from those elements of <em>iterable</em> for which <em>function</em> is true. <em>iterable</em> may be either a sequence, a container which supports iteration, or an iterator. If <em>function</em> is <code>None</code>, the identity function is assumed, that is, all elements of <em>iterable</em> that are false are removed.</p> <p>Note that <code>filter(function, iterable)</code> is equivalent to the generator expression <code>(item for item in iterable if function(item))</code> if function is not <code>None</code> and <code>(item for item in iterable if item)</code> if function is <code>None</code>.</p> <p>See <a class="reference internal" href="itertools#itertools.filterfalse" title="itertools.filterfalse"><code>itertools.filterfalse()</code></a> for the complementary function that returns elements of <em>iterable</em> for which <em>function</em> is false.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="float">
<code>class float(x=0.0)</code> </dt> <dd>
<p id="index-3">Return a floating point number constructed from a number or string <em>x</em>.</p> <p>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 <code>'+'</code> or <code>'-'</code>; a <code>'+'</code> 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 <code>floatvalue</code> production rule in the following grammar, after leading and trailing whitespace characters are removed:</p> <pre>
<strong id="grammar-token-float-sign"><span id="grammar-token-sign"></span>sign       </strong> ::=  "+" | "-"
<strong id="grammar-token-float-infinity"><span id="grammar-token-infinity"></span>infinity   </strong> ::=  "Infinity" | "inf"
<strong id="grammar-token-float-nan"><span id="grammar-token-nan"></span>nan        </strong> ::=  "nan"
<strong id="grammar-token-float-digitpart"><span id="grammar-token-digitpart"></span>digitpart  </strong> ::=  `!digit` (["_"] `!digit`)*
<strong id="grammar-token-float-number"><span id="grammar-token-number"></span>number     </strong> ::=  [<a class="reference internal" href="#grammar-token-float-digitpart">digitpart</a>] "." <a class="reference internal" href="#grammar-token-float-digitpart">digitpart</a> | <a class="reference internal" href="#grammar-token-float-digitpart">digitpart</a> ["."]
<strong id="grammar-token-float-exponent"><span id="grammar-token-exponent"></span>exponent   </strong> ::=  ("e" | "E") ["+" | "-"] <a class="reference internal" href="#grammar-token-float-digitpart">digitpart</a>
<strong id="grammar-token-float-floatnumber"><span id="grammar-token-floatnumber"></span>floatnumber</strong> ::=  number [<a class="reference internal" href="#grammar-token-float-exponent">exponent</a>]
<strong id="grammar-token-float-floatvalue"><span id="grammar-token-floatvalue"></span>floatvalue </strong> ::=  [<a class="reference internal" href="#grammar-token-float-sign">sign</a>] (<a class="reference internal" href="#grammar-token-float-floatnumber">floatnumber</a> | <a class="reference internal" href="#grammar-token-float-infinity">infinity</a> | <a class="reference internal" href="#grammar-token-float-nan">nan</a>)
</pre> <p>Here <code>digit</code> is a Unicode decimal digit (character in the Unicode general category <code>Nd</code>). Case is not significant, so, for example, “inf”, “Inf”, “INFINITY”, and “iNfINity” are all acceptable spellings for positive infinity.</p> <p>Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a> will be raised.</p> <p>For a general Python object <code>x</code>, <code>float(x)</code> delegates to <code>x.__float__()</code>. If <a class="reference internal" href="../reference/datamodel#object.__float__" title="object.__float__"><code>__float__()</code></a> is not defined then it falls back to <a class="reference internal" href="../reference/datamodel#object.__index__" title="object.__index__"><code>__index__()</code></a>.</p> <p>If no argument is given, <code>0.0</code> is returned.</p> <p>Examples:</p> <pre data-language="python">&gt;&gt;&gt; float('+1.23')
1.23
&gt;&gt;&gt; float('   -12345\n')
-12345.0
&gt;&gt;&gt; float('1e-003')
0.001
&gt;&gt;&gt; float('+1E6')
1000000.0
&gt;&gt;&gt; float('-Infinity')
-inf
</pre> <p>The float type is described in <a class="reference internal" href="stdtypes#typesnumeric"><span class="std std-ref">Numeric Types — int, float, complex</span></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Grouping digits with underscores as in code literals is allowed.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><em>x</em> is now a positional-only parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Falls back to <a class="reference internal" href="../reference/datamodel#object.__index__" title="object.__index__"><code>__index__()</code></a> if <a class="reference internal" href="../reference/datamodel#object.__float__" title="object.__float__"><code>__float__()</code></a> is not defined.</p> </div> </dd>
</dl> <span class="target" id="index-4"></span><dl class="py function"> <dt class="sig sig-object py" id="format">
<code>format(value, format_spec='')</code> </dt> <dd>
<p>Convert a <em>value</em> to a “formatted” representation, as controlled by <em>format_spec</em>. The interpretation of <em>format_spec</em> will depend on the type of the <em>value</em> argument; however, there is a standard formatting syntax that is used by most built-in types: <a class="reference internal" href="string#formatspec"><span class="std std-ref">Format Specification Mini-Language</span></a>.</p> <p>The default <em>format_spec</em> is an empty string which usually gives the same effect as calling <a class="reference internal" href="stdtypes#str" title="str"><code>str(value)</code></a>.</p> <p>A call to <code>format(value, format_spec)</code> is translated to <code>type(value).__format__(value, format_spec)</code> which bypasses the instance dictionary when searching for the value’s <a class="reference internal" href="../reference/datamodel#object.__format__" title="object.__format__"><code>__format__()</code></a> method. A <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised if the method search reaches <a class="reference internal" href="#object" title="object"><code>object</code></a> and the <em>format_spec</em> is non-empty, or if either the <em>format_spec</em> or the return value are not strings.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span><code>object().__format__(format_spec)</code> raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if <em>format_spec</em> is not an empty string.</p> </div> </dd>
</dl> <span class="target" id="func-frozenset"></span><dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">frozenset</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">iterable</span><span class="o">=</span><span class="default_value">set()</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return a new <a class="reference internal" href="stdtypes#frozenset" title="frozenset"><code>frozenset</code></a> object, optionally with elements taken from <em>iterable</em>. <code>frozenset</code> is a built-in class. See <a class="reference internal" href="stdtypes#frozenset" title="frozenset"><code>frozenset</code></a> and <a class="reference internal" href="stdtypes#types-set"><span class="std std-ref">Set Types — set, frozenset</span></a> for documentation about this class.</p> <p>For other containers see the built-in <a class="reference internal" href="stdtypes#set" title="set"><code>set</code></a>, <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a>, <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a>, and <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> classes, as well as the <a class="reference internal" href="collections#module-collections" title="collections: Container datatypes"><code>collections</code></a> module.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="getattr">
<code>getattr(object, name)</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">getattr</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">object</span></em>, <em class="sig-param"><span class="n">name</span></em>, <em class="sig-param"><span class="n">default</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return the value of the named attribute of <em>object</em>. <em>name</em> 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, <code>getattr(x, 'foobar')</code> is equivalent to <code>x.foobar</code>. If the named attribute does not exist, <em>default</em> is returned if provided, otherwise <a class="reference internal" href="exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a> is raised. <em>name</em> need not be a Python identifier (see <a class="reference internal" href="#setattr" title="setattr"><code>setattr()</code></a>).</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Since <a class="reference internal" href="../reference/expressions#private-name-mangling"><span class="std std-ref">private name mangling</span></a> happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with <a class="reference internal" href="#getattr" title="getattr"><code>getattr()</code></a>.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="globals">
<code>globals()</code> </dt> <dd>
<p>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.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="hasattr">
<code>hasattr(object, name)</code> </dt> <dd>
<p>The arguments are an object and a string. The result is <code>True</code> if the string is the name of one of the object’s attributes, <code>False</code> if not. (This is implemented by calling <code>getattr(object, name)</code> and seeing whether it raises an <a class="reference internal" href="exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a> or not.)</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="hash">
<code>hash(object)</code> </dt> <dd>
<p>Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>For objects with custom <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> methods, note that <a class="reference internal" href="#hash" title="hash"><code>hash()</code></a> truncates the return value based on the bit width of the host machine.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="help">
<code>help()</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">help</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">request</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.</p> <p>Note that if a slash(/) appears in the parameter list of a function when invoking <a class="reference internal" href="#help" title="help"><code>help()</code></a>, it means that the parameters prior to the slash are positional-only. For more info, see <a class="reference internal" href="../faq/programming#faq-positional-only-arguments"><span class="std std-ref">the FAQ entry on positional-only parameters</span></a>.</p> <p>This function is added to the built-in namespace by the <a class="reference internal" href="site#module-site" title="site: Module responsible for site-specific configuration."><code>site</code></a> module.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Changes to <a class="reference internal" href="pydoc#module-pydoc" title="pydoc: Documentation generator and online help system."><code>pydoc</code></a> and <a class="reference internal" href="inspect#module-inspect" title="inspect: Extract information and source code from live objects."><code>inspect</code></a> mean that the reported signatures for callables are now more comprehensive and consistent.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="hex">
<code>hex(x)</code> </dt> <dd>
<p>Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If <em>x</em> is not a Python <a class="reference internal" href="#int" title="int"><code>int</code></a> object, it has to define an <a class="reference internal" href="../reference/datamodel#object.__index__" title="object.__index__"><code>__index__()</code></a> method that returns an integer. Some examples:</p> <pre data-language="python">&gt;&gt;&gt; hex(255)
'0xff'
&gt;&gt;&gt; hex(-42)
'-0x2a'
</pre> <p>If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways:</p> <pre data-language="python">&gt;&gt;&gt; '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
&gt;&gt;&gt; format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
&gt;&gt;&gt; f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')
</pre> <p>See also <a class="reference internal" href="#format" title="format"><code>format()</code></a> for more information.</p> <p>See also <a class="reference internal" href="#int" title="int"><code>int()</code></a> for converting a hexadecimal string to an integer using a base of 16.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>To obtain a hexadecimal string representation for a float, use the <a class="reference internal" href="stdtypes#float.hex" title="float.hex"><code>float.hex()</code></a> method.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="id">
<code>id(object)</code> </dt> <dd>
<p>Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same <a class="reference internal" href="#id" title="id"><code>id()</code></a> value.</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> This is the address of the object in memory.</p> </div> <p class="audit-hook">Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>builtins.id</code> with argument <code>id</code>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="input">
<code>input()</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">input</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">prompt</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>If the <em>prompt</em> argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, <a class="reference internal" href="exceptions#EOFError" title="EOFError"><code>EOFError</code></a> is raised. Example:</p> <pre data-language="python">&gt;&gt;&gt; s = input('--&gt; ')  
--&gt; Monty Python's Flying Circus
&gt;&gt;&gt; s  
"Monty Python's Flying Circus"
</pre> <p>If the <a class="reference internal" href="readline#module-readline" title="readline: GNU readline support for Python. (Unix)"><code>readline</code></a> module was loaded, then <a class="reference internal" href="#input" title="input"><code>input()</code></a> will use it to provide elaborate line editing and history features.</p> <p class="audit-hook"></p>
<p>Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>builtins.input</code> with argument <code>prompt</code> before reading input</p> <p class="audit-hook"></p>
<p>Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>builtins.input/result</code> with the result after successfully reading input.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="int">
<code>class int(x=0)</code> </dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">int</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">x</span></em>, <em class="sig-param"><span class="n">base</span><span class="o">=</span><span class="default_value">10</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return an integer object constructed from a number or string <em>x</em>, or return <code>0</code> if no arguments are given. If <em>x</em> defines <a class="reference internal" href="../reference/datamodel#object.__int__" title="object.__int__"><code>__int__()</code></a>, <code>int(x)</code> returns <code>x.__int__()</code>. If <em>x</em> defines <a class="reference internal" href="../reference/datamodel#object.__index__" title="object.__index__"><code>__index__()</code></a>, it returns <code>x.__index__()</code>. If <em>x</em> defines <a class="reference internal" href="../reference/datamodel#object.__trunc__" title="object.__trunc__"><code>__trunc__()</code></a>, it returns <code>x.__trunc__()</code>. For floating point numbers, this truncates towards zero.</p> <p>If <em>x</em> is not a number or if <em>base</em> is given, then <em>x</em> must be a string, <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a>, or <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a> instance representing an integer in radix <em>base</em>. Optionally, the string can be preceded by <code>+</code> or <code>-</code> (with no space in between), have leading zeros, be surrounded by whitespace, and have single underscores interspersed between digits.</p> <p>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 <code>a</code> to <code>z</code> (or <code>A</code> to <code>Z</code>). The default <em>base</em> is 10. The allowed bases are 0 and 2–36. Base-2, -8, and -16 strings can be optionally prefixed with <code>0b</code>/<code>0B</code>, <code>0o</code>/<code>0O</code>, or <code>0x</code>/<code>0X</code>, as with integer literals in code. For base 0, the string is interpreted in a similar way to an <a class="reference internal" href="../reference/lexical_analysis#integers"><span class="std std-ref">integer literal in code</span></a>, in that the actual base is 2, 8, 10, or 16 as determined by the prefix. Base 0 also disallows leading zeros: <code>int('010', 0)</code> is not legal, while <code>int('010')</code> and <code>int('010', 8)</code> are.</p> <p>The integer type is described in <a class="reference internal" href="stdtypes#typesnumeric"><span class="std std-ref">Numeric Types — int, float, complex</span></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>If <em>base</em> is not an instance of <a class="reference internal" href="#int" title="int"><code>int</code></a> and the <em>base</em> object has a <a class="reference internal" href="../reference/datamodel#object.__index__" title="object.__index__"><code>base.__index__</code></a> method, that method is called to obtain an integer for the base. Previous versions used <a class="reference internal" href="../reference/datamodel#object.__int__" title="object.__int__"><code>base.__int__</code></a> instead of <a class="reference internal" href="../reference/datamodel#object.__index__" title="object.__index__"><code>base.__index__</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Grouping digits with underscores as in code literals is allowed.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><em>x</em> is now a positional-only parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Falls back to <a class="reference internal" href="../reference/datamodel#object.__index__" title="object.__index__"><code>__index__()</code></a> if <a class="reference internal" href="../reference/datamodel#object.__int__" title="object.__int__"><code>__int__()</code></a> is not defined.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The delegation to <a class="reference internal" href="../reference/datamodel#object.__trunc__" title="object.__trunc__"><code>__trunc__()</code></a> is deprecated.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span><a class="reference internal" href="#int" title="int"><code>int</code></a> string inputs and string representations can be limited to help avoid denial of service attacks. A <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised when the limit is exceeded while converting a string <em>x</em> to an <a class="reference internal" href="#int" title="int"><code>int</code></a> or when converting an <a class="reference internal" href="#int" title="int"><code>int</code></a> into a string would exceed the limit. See the <a class="reference internal" href="stdtypes#int-max-str-digits"><span class="std std-ref">integer string conversion length limitation</span></a> documentation.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="isinstance">
<code>isinstance(object, classinfo)</code> </dt> <dd>
<p>Return <code>True</code> if the <em>object</em> argument is an instance of the <em>classinfo</em> argument, or of a (direct, indirect, or <a class="reference internal" href="../glossary#term-abstract-base-class"><span class="xref std std-term">virtual</span></a>) subclass thereof. If <em>object</em> is not an object of the given type, the function always returns <code>False</code>. If <em>classinfo</em> is a tuple of type objects (or recursively, other such tuples) or a <a class="reference internal" href="stdtypes#types-union"><span class="std std-ref">Union Type</span></a> of multiple types, return <code>True</code> if <em>object</em> is an instance of any of the types. If <em>classinfo</em> is not a type or tuple of types and such tuples, a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised. <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> may not be raised for an invalid type if an earlier check succeeds.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><em>classinfo</em> can be a <a class="reference internal" href="stdtypes#types-union"><span class="std std-ref">Union Type</span></a>.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="issubclass">
<code>issubclass(class, classinfo)</code> </dt> <dd>
<p>Return <code>True</code> if <em>class</em> is a subclass (direct, indirect, or <a class="reference internal" href="../glossary#term-abstract-base-class"><span class="xref std std-term">virtual</span></a>) of <em>classinfo</em>. A class is considered a subclass of itself. <em>classinfo</em> may be a tuple of class objects (or recursively, other such tuples) or a <a class="reference internal" href="stdtypes#types-union"><span class="std std-ref">Union Type</span></a>, in which case return <code>True</code> if <em>class</em> is a subclass of any entry in <em>classinfo</em>. In any other case, a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><em>classinfo</em> can be a <a class="reference internal" href="stdtypes#types-union"><span class="std std-ref">Union Type</span></a>.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="iter">
<code>iter(object)</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">iter</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">object</span></em>, <em class="sig-param"><span class="n">sentinel</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return an <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a> object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, <em>object</em> must be a collection object which supports the <a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a> protocol (the <a class="reference internal" href="../reference/datamodel#object.__iter__" title="object.__iter__"><code>__iter__()</code></a> method), or it must support the sequence protocol (the <a class="reference internal" href="../reference/datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a> method with integer arguments starting at <code>0</code>). If it does not support either of those protocols, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised. If the second argument, <em>sentinel</em>, is given, then <em>object</em> must be a callable object. The iterator created in this case will call <em>object</em> with no arguments for each call to its <a class="reference internal" href="stdtypes#iterator.__next__" title="iterator.__next__"><code>__next__()</code></a> method; if the value returned is equal to <em>sentinel</em>, <a class="reference internal" href="exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a> will be raised, otherwise the value will be returned.</p> <p>See also <a class="reference internal" href="stdtypes#typeiter"><span class="std std-ref">Iterator Types</span></a>.</p> <p>One useful application of the second form of <a class="reference internal" href="#iter" title="iter"><code>iter()</code></a> is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:</p> <pre data-language="python">from functools import partial
with open('mydata.db', 'rb') as f:
    for block in iter(partial(f.read, 64), b''):
        process_block(block)
</pre> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="len">
<code>len(s)</code> </dt> <dd>
<p>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).</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> <code>len</code> raises <a class="reference internal" href="exceptions#OverflowError" title="OverflowError"><code>OverflowError</code></a> on lengths larger than <a class="reference internal" href="sys#sys.maxsize" title="sys.maxsize"><code>sys.maxsize</code></a>, such as <a class="reference internal" href="stdtypes#range" title="range"><code>range(2 ** 100)</code></a>.</p> </div> </dd>
</dl> <span class="target" id="func-list"></span><dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">list</span>
</dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">list</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">iterable</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Rather than being a function, <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> is actually a mutable sequence type, as documented in <a class="reference internal" href="stdtypes#typesseq-list"><span class="std std-ref">Lists</span></a> and <a class="reference internal" href="stdtypes#typesseq"><span class="std std-ref">Sequence Types — list, tuple, range</span></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="locals">
<code>locals()</code> </dt> <dd>
<p>Update and return a dictionary representing the current local symbol table. Free variables are returned by <a class="reference internal" href="#locals" title="locals"><code>locals()</code></a> when it is called in function blocks, but not in class blocks. Note that at the module level, <a class="reference internal" href="#locals" title="locals"><code>locals()</code></a> and <a class="reference internal" href="#globals" title="globals"><code>globals()</code></a> are the same dictionary.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="map">
<code>map(function, iterable, *iterables)</code> </dt> <dd>
<p>Return an iterator that applies <em>function</em> to every item of <em>iterable</em>, yielding the results. If additional <em>iterables</em> arguments are passed, <em>function</em> 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 <a class="reference internal" href="itertools#itertools.starmap" title="itertools.starmap"><code>itertools.starmap()</code></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="max">
<code>max(iterable, *, key=None)</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">max</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">iterable</span></em>, <em class="sig-param"><span class="o">*</span></em>, <em class="sig-param"><span class="n">default</span></em>, <em class="sig-param"><span class="n">key</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span>
</dt> <dt class="sig sig-object py"> <span class="sig-name descname">max</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">arg1</span></em>, <em class="sig-param"><span class="n">arg2</span></em>, <em class="sig-param"><span class="o">*</span><span class="n">args</span></em>, <em class="sig-param"><span class="n">key</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return the largest item in an iterable or the largest of two or more arguments.</p> <p>If one positional argument is provided, it should be an <a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a>. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.</p> <p>There are two optional keyword-only arguments. The <em>key</em> argument specifies a one-argument ordering function like that used for <a class="reference internal" href="stdtypes#list.sort" title="list.sort"><code>list.sort()</code></a>. The <em>default</em> argument specifies an object to return if the provided iterable is empty. If the iterable is empty and <em>default</em> is not provided, a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised.</p> <p>If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as <code>sorted(iterable, key=keyfunc, reverse=True)[0]</code> and <code>heapq.nlargest(1, iterable, key=keyfunc)</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4: </span>The <em>default</em> keyword-only argument.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>key</em> can be <code>None</code>.</p> </div> </dd>
</dl> <span class="target" id="func-memoryview"></span><dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">memoryview</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">object</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return a “memory view” object created from the given argument. See <a class="reference internal" href="stdtypes#typememoryview"><span class="std std-ref">Memory Views</span></a> for more information.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="min">
<code>min(iterable, *, key=None)</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">min</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">iterable</span></em>, <em class="sig-param"><span class="o">*</span></em>, <em class="sig-param"><span class="n">default</span></em>, <em class="sig-param"><span class="n">key</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span>
</dt> <dt class="sig sig-object py"> <span class="sig-name descname">min</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">arg1</span></em>, <em class="sig-param"><span class="n">arg2</span></em>, <em class="sig-param"><span class="o">*</span><span class="n">args</span></em>, <em class="sig-param"><span class="n">key</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return the smallest item in an iterable or the smallest of two or more arguments.</p> <p>If one positional argument is provided, it should be an <a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a>. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.</p> <p>There are two optional keyword-only arguments. The <em>key</em> argument specifies a one-argument ordering function like that used for <a class="reference internal" href="stdtypes#list.sort" title="list.sort"><code>list.sort()</code></a>. The <em>default</em> argument specifies an object to return if the provided iterable is empty. If the iterable is empty and <em>default</em> is not provided, a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised.</p> <p>If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as <code>sorted(iterable, key=keyfunc)[0]</code> and <code>heapq.nsmallest(1,
iterable, key=keyfunc)</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4: </span>The <em>default</em> keyword-only argument.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>key</em> can be <code>None</code>.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="next">
<code>next(iterator)</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">next</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">iterator</span></em>, <em class="sig-param"><span class="n">default</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Retrieve the next item from the <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a> by calling its <a class="reference internal" href="stdtypes#iterator.__next__" title="iterator.__next__"><code>__next__()</code></a> method. If <em>default</em> is given, it is returned if the iterator is exhausted, otherwise <a class="reference internal" href="exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a> is raised.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="object">
<code>class object</code> </dt> <dd>
<p>Return a new featureless object. <a class="reference internal" href="#object" title="object"><code>object</code></a> 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.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p><a class="reference internal" href="#object" title="object"><code>object</code></a> does <em>not</em> have a <a class="reference internal" href="stdtypes#object.__dict__" title="object.__dict__"><code>__dict__</code></a>, so you can’t assign arbitrary attributes to an instance of the <a class="reference internal" href="#object" title="object"><code>object</code></a> class.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="oct">
<code>oct(x)</code> </dt> <dd>
<p>Convert an integer number to an octal string prefixed with “0o”. The result is a valid Python expression. If <em>x</em> is not a Python <a class="reference internal" href="#int" title="int"><code>int</code></a> object, it has to define an <a class="reference internal" href="../reference/datamodel#object.__index__" title="object.__index__"><code>__index__()</code></a> method that returns an integer. For example:</p> <pre data-language="python">&gt;&gt;&gt; oct(8)
'0o10'
&gt;&gt;&gt; oct(-56)
'-0o70'
</pre> <p>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.</p> <pre data-language="python">&gt;&gt;&gt; '%#o' % 10, '%o' % 10
('0o12', '12')
&gt;&gt;&gt; format(10, '#o'), format(10, 'o')
('0o12', '12')
&gt;&gt;&gt; f'{10:#o}', f'{10:o}'
('0o12', '12')
</pre> <p>See also <a class="reference internal" href="#format" title="format"><code>format()</code></a> for more information.</p> </dd>
</dl> <span class="target" id="index-5"></span><dl class="py function"> <dt class="sig sig-object py" id="open">
<code>open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)</code> </dt> <dd>
<p>Open <em>file</em> and return a corresponding <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a>. If the file cannot be opened, an <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> is raised. See <a class="reference internal" href="../tutorial/inputoutput#tut-files"><span class="std std-ref">Reading and Writing Files</span></a> for more examples of how to use this function.</p> <p><em>file</em> is a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a> 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 <em>closefd</em> is set to <code>False</code>.)</p> <p><em>mode</em> is an optional string that specifies the mode in which the file is opened. It defaults to <code>'r'</code> which means open for reading in text mode. Other common values are <code>'w'</code> for writing (truncating the file if it already exists), <code>'x'</code> for exclusive creation, and <code>'a'</code> for appending (which on <em>some</em> Unix systems, means that <em>all</em> writes append to the end of the file regardless of the current seek position). In text mode, if <em>encoding</em> is not specified the encoding used is platform-dependent: <a class="reference internal" href="locale#locale.getencoding" title="locale.getencoding"><code>locale.getencoding()</code></a> is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave <em>encoding</em> unspecified.) The available modes are:</p> <span class="target" id="filemodes"></span><table class="docutils align-default" id="index-6">  <thead> <tr>
<th class="head"><p>Character</p></th> <th class="head"><p>Meaning</p></th> </tr> </thead>  <tr>
<td><p><code>'r'</code></p></td> <td><p>open for reading (default)</p></td> </tr> <tr>
<td><p><code>'w'</code></p></td> <td><p>open for writing, truncating the file first</p></td> </tr> <tr>
<td><p><code>'x'</code></p></td> <td><p>open for exclusive creation, failing if the file already exists</p></td> </tr> <tr>
<td><p><code>'a'</code></p></td> <td><p>open for writing, appending to the end of file if it exists</p></td> </tr> <tr>
<td><p><code>'b'</code></p></td> <td><p>binary mode</p></td> </tr> <tr>
<td><p><code>'t'</code></p></td> <td><p>text mode (default)</p></td> </tr> <tr>
<td><p><code>'+'</code></p></td> <td><p>open for updating (reading and writing)</p></td> </tr>  </table> <p>The default mode is <code>'r'</code> (open for reading text, a synonym of <code>'rt'</code>). Modes <code>'w+'</code> and <code>'w+b'</code> open and truncate the file. Modes <code>'r+'</code> and <code>'r+b'</code> open the file with no truncation.</p> <p>As mentioned in the <a class="reference internal" href="io#io-overview"><span class="std std-ref">Overview</span></a>, Python distinguishes between binary and text I/O. Files opened in binary mode (including <code>'b'</code> in the <em>mode</em> argument) return contents as <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> objects without any decoding. In text mode (the default, or when <code>'t'</code> is included in the <em>mode</em> argument), the contents of the file are returned as <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, the bytes having been first decoded using a platform-dependent encoding or using the specified <em>encoding</em> if given.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>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.</p> </div> <p><em>buffering</em> 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 &gt; 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 <code>TextIOWrapper</code> (i.e., files opened with <code>mode='r+'</code>) would have another buffering. To disable buffering in <code>TextIOWrapper</code>, consider using the <code>write_through</code> flag for <a class="reference internal" href="io#io.TextIOWrapper.reconfigure" title="io.TextIOWrapper.reconfigure"><code>io.TextIOWrapper.reconfigure()</code></a>. When no <em>buffering</em> argument is given, the default buffering policy works as follows:</p> <ul class="simple"> <li>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 <a class="reference internal" href="io#io.DEFAULT_BUFFER_SIZE" title="io.DEFAULT_BUFFER_SIZE"><code>io.DEFAULT_BUFFER_SIZE</code></a>. On many systems, the buffer will typically be 4096 or 8192 bytes long.</li> <li>“Interactive” text files (files for which <a class="reference internal" href="io#io.IOBase.isatty" title="io.IOBase.isatty"><code>isatty()</code></a> returns <code>True</code>) use line buffering. Other text files use the policy described above for binary files.</li> </ul> <p><em>encoding</em> 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 <a class="reference internal" href="locale#locale.getencoding" title="locale.getencoding"><code>locale.getencoding()</code></a> returns), but any <a class="reference internal" href="../glossary#term-text-encoding"><span class="xref std std-term">text encoding</span></a> supported by Python can be used. See the <a class="reference internal" href="codecs#module-codecs" title="codecs: Encode and decode data and streams."><code>codecs</code></a> module for the list of supported encodings.</p> <p><em>errors</em> 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 (listed under <a class="reference internal" href="codecs#error-handlers"><span class="std std-ref">Error Handlers</span></a>), though any error handling name that has been registered with <a class="reference internal" href="codecs#codecs.register_error" title="codecs.register_error"><code>codecs.register_error()</code></a> is also valid. The standard names include:</p> <ul class="simple"> <li>
<code>'strict'</code> to raise a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> exception if there is an encoding error. The default value of <code>None</code> has the same effect.</li> <li>
<code>'ignore'</code> ignores errors. Note that ignoring encoding errors can lead to data loss.</li> <li>
<code>'replace'</code> causes a replacement marker (such as <code>'?'</code>) to be inserted where there is malformed data.</li> <li>
<code>'surrogateescape'</code> 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 <code>surrogateescape</code> error handler is used when writing data. This is useful for processing files in an unknown encoding.</li> <li>
<code>'xmlcharrefreplace'</code> is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference <code>&amp;#<em>nnn</em>;</code>.</li> <li>
<code>'backslashreplace'</code> replaces malformed data by Python’s backslashed escape sequences.</li> <li>
<code>'namereplace'</code> (also only supported when writing) replaces unsupported characters with <code>\N{...}</code> escape sequences.</li> </ul> <p id="open-newline-parameter"><span id="index-7"></span><em>newline</em> determines how to parse newline characters from the stream. It can be <code>None</code>, <code>''</code>, <code>'\n'</code>, <code>'\r'</code>, and <code>'\r\n'</code>. It works as follows:</p> <ul class="simple"> <li>When reading input from the stream, if <em>newline</em> is <code>None</code>, universal newlines mode is enabled. Lines in the input can end in <code>'\n'</code>, <code>'\r'</code>, or <code>'\r\n'</code>, and these are translated into <code>'\n'</code> before being returned to the caller. If it is <code>''</code>, 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.</li> <li>When writing output to the stream, if <em>newline</em> is <code>None</code>, any <code>'\n'</code> characters written are translated to the system default line separator, <a class="reference internal" href="os#os.linesep" title="os.linesep"><code>os.linesep</code></a>. If <em>newline</em> is <code>''</code> or <code>'\n'</code>, no translation takes place. If <em>newline</em> is any of the other legal values, any <code>'\n'</code> characters written are translated to the given string.</li> </ul> <p>If <em>closefd</em> is <code>False</code> 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 <em>closefd</em> must be <code>True</code> (the default); otherwise, an error will be raised.</p> <p>A custom opener can be used by passing a callable as <em>opener</em>. The underlying file descriptor for the file object is then obtained by calling <em>opener</em> with (<em>file</em>, <em>flags</em>). <em>opener</em> must return an open file descriptor (passing <a class="reference internal" href="os#os.open" title="os.open"><code>os.open</code></a> as <em>opener</em> results in functionality similar to passing <code>None</code>).</p> <p>The newly created file is <a class="reference internal" href="os#fd-inheritance"><span class="std std-ref">non-inheritable</span></a>.</p> <p>The following example uses the <a class="reference internal" href="os#dir-fd"><span class="std std-ref">dir_fd</span></a> parameter of the <a class="reference internal" href="os#os.open" title="os.open"><code>os.open()</code></a> function to open a file relative to a given directory:</p> <pre data-language="python">&gt;&gt;&gt; import os
&gt;&gt;&gt; dir_fd = os.open('somedir', os.O_RDONLY)
&gt;&gt;&gt; def opener(path, flags):
...     return os.open(path, flags, dir_fd=dir_fd)
...
&gt;&gt;&gt; with open('spamspam.txt', 'w', opener=opener) as f:
...     print('This will be written to somedir/spamspam.txt', file=f)
...
&gt;&gt;&gt; os.close(dir_fd)  # don't leak a file descriptor
</pre> <p>The type of <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a> returned by the <a class="reference internal" href="#open" title="open"><code>open()</code></a> function depends on the mode. When <a class="reference internal" href="#open" title="open"><code>open()</code></a> is used to open a file in a text mode (<code>'w'</code>, <code>'r'</code>, <code>'wt'</code>, <code>'rt'</code>, etc.), it returns a subclass of <a class="reference internal" href="io#io.TextIOBase" title="io.TextIOBase"><code>io.TextIOBase</code></a> (specifically <a class="reference internal" href="io#io.TextIOWrapper" title="io.TextIOWrapper"><code>io.TextIOWrapper</code></a>). When used to open a file in a binary mode with buffering, the returned class is a subclass of <a class="reference internal" href="io#io.BufferedIOBase" title="io.BufferedIOBase"><code>io.BufferedIOBase</code></a>. The exact class varies: in read binary mode, it returns an <a class="reference internal" href="io#io.BufferedReader" title="io.BufferedReader"><code>io.BufferedReader</code></a>; in write binary and append binary modes, it returns an <a class="reference internal" href="io#io.BufferedWriter" title="io.BufferedWriter"><code>io.BufferedWriter</code></a>, and in read/write mode, it returns an <a class="reference internal" href="io#io.BufferedRandom" title="io.BufferedRandom"><code>io.BufferedRandom</code></a>. When buffering is disabled, the raw stream, a subclass of <a class="reference internal" href="io#io.RawIOBase" title="io.RawIOBase"><code>io.RawIOBase</code></a>, <a class="reference internal" href="io#io.FileIO" title="io.FileIO"><code>io.FileIO</code></a>, is returned.</p> <p id="index-8">See also the file handling modules, such as <a class="reference internal" href="fileinput#module-fileinput" title="fileinput: Loop over standard input or a list of files."><code>fileinput</code></a>, <a class="reference internal" href="io#module-io" title="io: Core tools for working with streams."><code>io</code></a> (where <a class="reference internal" href="#open" title="open"><code>open()</code></a> is declared), <a class="reference internal" href="os#module-os" title="os: Miscellaneous operating system interfaces."><code>os</code></a>, <a class="reference internal" href="os.path#module-os.path" title="os.path: Operations on pathnames."><code>os.path</code></a>, <a class="reference internal" href="tempfile#module-tempfile" title="tempfile: Generate temporary files and directories."><code>tempfile</code></a>, and <a class="reference internal" href="shutil#module-shutil" title="shutil: High-level file operations, including copying."><code>shutil</code></a>.</p> <p class="audit-hook">Raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>open</code> with arguments <code>file</code>, <code>mode</code>, <code>flags</code>.</p> <p>The <code>mode</code> and <code>flags</code> arguments may have been modified or inferred from the original call.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span></p> <ul class="simple"> <li>The <em>opener</em> parameter was added.</li> <li>The <code>'x'</code> mode was added.</li> <li>
<a class="reference internal" href="exceptions#IOError" title="IOError"><code>IOError</code></a> used to be raised, it is now an alias of <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a>.</li> <li>
<a class="reference internal" href="exceptions#FileExistsError" title="FileExistsError"><code>FileExistsError</code></a> is now raised if the file opened in exclusive creation mode (<code>'x'</code>) already exists.</li> </ul> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span></p> <ul class="simple"> <li>The file is now non-inheritable.</li> </ul> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span></p> <ul class="simple"> <li>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 <a class="reference internal" href="exceptions#InterruptedError" title="InterruptedError"><code>InterruptedError</code></a> exception (see <span class="target" id="index-9"></span><a class="pep reference external" href="https://peps.python.org/pep-0475/"><strong>PEP 475</strong></a> for the rationale).</li> <li>The <code>'namereplace'</code> error handler was added.</li> </ul> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span></p> <ul class="simple"> <li>Support added to accept objects implementing <a class="reference internal" href="os#os.PathLike" title="os.PathLike"><code>os.PathLike</code></a>.</li> <li>On Windows, opening a console buffer may return a subclass of <a class="reference internal" href="io#io.RawIOBase" title="io.RawIOBase"><code>io.RawIOBase</code></a> other than <a class="reference internal" href="io#io.FileIO" title="io.FileIO"><code>io.FileIO</code></a>.</li> </ul> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The <code>'U'</code> mode has been removed.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ord">
<code>ord(c)</code> </dt> <dd>
<p>Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, <code>ord('a')</code> returns the integer <code>97</code> and <code>ord('€')</code> (Euro sign) returns <code>8364</code>. This is the inverse of <a class="reference internal" href="#chr" title="chr"><code>chr()</code></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="pow">
<code>pow(base, exp, mod=None)</code> </dt> <dd>
<p>Return <em>base</em> to the power <em>exp</em>; if <em>mod</em> is present, return <em>base</em> to the power <em>exp</em>, modulo <em>mod</em> (computed more efficiently than <code>pow(base, exp) % mod</code>). The two-argument form <code>pow(base, exp)</code> is equivalent to using the power operator: <code>base**exp</code>.</p> <p>The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For <a class="reference internal" href="#int" title="int"><code>int</code></a> 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, <code>pow(10, 2)</code> returns <code>100</code>, but <code>pow(10, -2)</code> returns <code>0.01</code>. For a negative base of type <a class="reference internal" href="#int" title="int"><code>int</code></a> or <a class="reference internal" href="#float" title="float"><code>float</code></a> and a non-integral exponent, a complex result is delivered. For example, <code>pow(-9, 0.5)</code> returns a value close to <code>3j</code>.</p> <p>For <a class="reference internal" href="#int" title="int"><code>int</code></a> operands <em>base</em> and <em>exp</em>, if <em>mod</em> is present, <em>mod</em> must also be of integer type and <em>mod</em> must be nonzero. If <em>mod</em> is present and <em>exp</em> is negative, <em>base</em> must be relatively prime to <em>mod</em>. In that case, <code>pow(inv_base, -exp, mod)</code> is returned, where <em>inv_base</em> is an inverse to <em>base</em> modulo <em>mod</em>.</p> <p>Here’s an example of computing an inverse for <code>38</code> modulo <code>97</code>:</p> <pre data-language="python">&gt;&gt;&gt; pow(38, -1, mod=97)
23
&gt;&gt;&gt; 23 * 38 % 97 == 1
True
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>For <a class="reference internal" href="#int" title="int"><code>int</code></a> operands, the three-argument form of <code>pow</code> now allows the second argument to be negative, permitting computation of modular inverses.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Allow keyword arguments. Formerly, only positional arguments were supported.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="print">
<code>print(*objects, sep=' ', end='\n', file=None, flush=False)</code> </dt> <dd>
<p>Print <em>objects</em> to the text stream <em>file</em>, separated by <em>sep</em> and followed by <em>end</em>. <em>sep</em>, <em>end</em>, <em>file</em>, and <em>flush</em>, if present, must be given as keyword arguments.</p> <p>All non-keyword arguments are converted to strings like <a class="reference internal" href="stdtypes#str" title="str"><code>str()</code></a> does and written to the stream, separated by <em>sep</em> and followed by <em>end</em>. Both <em>sep</em> and <em>end</em> must be strings; they can also be <code>None</code>, which means to use the default values. If no <em>objects</em> are given, <a class="reference internal" href="#print" title="print"><code>print()</code></a> will just write <em>end</em>.</p> <p>The <em>file</em> argument must be an object with a <code>write(string)</code> method; if it is not present or <code>None</code>, <a class="reference internal" href="sys#sys.stdout" title="sys.stdout"><code>sys.stdout</code></a> will be used. Since printed arguments are converted to text strings, <a class="reference internal" href="#print" title="print"><code>print()</code></a> cannot be used with binary mode file objects. For these, use <code>file.write(...)</code> instead.</p> <p>Output buffering is usually determined by <em>file</em>. However, if <em>flush</em> is true, the stream is forcibly flushed.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Added the <em>flush</em> keyword argument.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="property">
<code>class property(fget=None, fset=None, fdel=None, doc=None)</code> </dt> <dd>
<p>Return a property attribute.</p> <p><em>fget</em> is a function for getting an attribute value. <em>fset</em> is a function for setting an attribute value. <em>fdel</em> is a function for deleting an attribute value. And <em>doc</em> creates a docstring for the attribute.</p> <p>A typical use is to define a managed attribute <code>x</code>:</p> <pre data-language="python">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.")
</pre> <p>If <em>c</em> is an instance of <em>C</em>, <code>c.x</code> will invoke the getter, <code>c.x = value</code> will invoke the setter, and <code>del c.x</code> the deleter.</p> <p>If given, <em>doc</em> will be the docstring of the property attribute. Otherwise, the property will copy <em>fget</em>’s docstring (if it exists). This makes it possible to create read-only properties easily using <a class="reference internal" href="#property" title="property"><code>property()</code></a> as a <a class="reference internal" href="../glossary#term-decorator"><span class="xref std std-term">decorator</span></a>:</p> <pre data-language="python">class Parrot:
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage
</pre> <p>The <code>@property</code> decorator turns the <code>voltage()</code> method into a “getter” for a read-only attribute with the same name, and it sets the docstring for <em>voltage</em> to “Get the current voltage.”</p> <dl class="py function"> <dt class="sig sig-object py" id="property.getter">
<code>@getter</code> </dt> <dd></dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="property.setter">
<code>@setter</code> </dt> <dd></dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="property.deleter">
<code>@deleter</code> </dt> <dd>
<p>A property object has <code>getter</code>, <code>setter</code>, and <code>deleter</code> 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:</p> <pre data-language="python">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
</pre> <p>This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (<code>x</code> in this case.)</p> <p>The returned property object also has the attributes <code>fget</code>, <code>fset</code>, and <code>fdel</code> corresponding to the constructor arguments.</p> </dd>
</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The docstrings of property objects are now writeable.</p> </div> </dd>
</dl> <span class="target" id="func-range"></span><dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">range</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">stop</span></em><span class="sig-paren">)</span>
</dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">range</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">start</span></em>, <em class="sig-param"><span class="n">stop</span></em>, <em class="sig-param"><span class="n">step</span><span class="o">=</span><span class="default_value">1</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Rather than being a function, <a class="reference internal" href="stdtypes#range" title="range"><code>range</code></a> is actually an immutable sequence type, as documented in <a class="reference internal" href="stdtypes#typesseq-range"><span class="std std-ref">Ranges</span></a> and <a class="reference internal" href="stdtypes#typesseq"><span class="std std-ref">Sequence Types — list, tuple, range</span></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="repr">
<code>repr(object)</code> </dt> <dd>
<p>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 <a class="reference internal" href="#eval" title="eval"><code>eval()</code></a>; 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 <a class="reference internal" href="../reference/datamodel#object.__repr__" title="object.__repr__"><code>__repr__()</code></a> method. If <a class="reference internal" href="sys#sys.displayhook" title="sys.displayhook"><code>sys.displayhook()</code></a> is not accessible, this function will raise <a class="reference internal" href="exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="reversed">
<code>reversed(seq)</code> </dt> <dd>
<p>Return a reverse <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a>. <em>seq</em> must be an object which has a <a class="reference internal" href="../reference/datamodel#object.__reversed__" title="object.__reversed__"><code>__reversed__()</code></a> method or supports the sequence protocol (the <a class="reference internal" href="../reference/datamodel#object.__len__" title="object.__len__"><code>__len__()</code></a> method and the <a class="reference internal" href="../reference/datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a> method with integer arguments starting at <code>0</code>).</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="round">
<code>round(number, ndigits=None)</code> </dt> <dd>
<p>Return <em>number</em> rounded to <em>ndigits</em> precision after the decimal point. If <em>ndigits</em> is omitted or is <code>None</code>, it returns the nearest integer to its input.</p> <p>For the built-in types supporting <a class="reference internal" href="#round" title="round"><code>round()</code></a>, values are rounded to the closest multiple of 10 to the power minus <em>ndigits</em>; if two multiples are equally close, rounding is done toward the even choice (so, for example, both <code>round(0.5)</code> and <code>round(-0.5)</code> are <code>0</code>, and <code>round(1.5)</code> is <code>2</code>). Any integer value is valid for <em>ndigits</em> (positive, zero, or negative). The return value is an integer if <em>ndigits</em> is omitted or <code>None</code>. Otherwise, the return value has the same type as <em>number</em>.</p> <p>For a general Python object <code>number</code>, <code>round</code> delegates to <code>number.__round__</code>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The behavior of <a class="reference internal" href="#round" title="round"><code>round()</code></a> for floats can be surprising: for example, <code>round(2.675, 2)</code> gives <code>2.67</code> instead of the expected <code>2.68</code>. 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 <a class="reference internal" href="../tutorial/floatingpoint#tut-fp-issues"><span class="std std-ref">Floating Point Arithmetic: Issues and Limitations</span></a> for more information.</p> </div> </dd>
</dl> <span class="target" id="func-set"></span><dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">set</span>
</dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">set</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">iterable</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return a new <a class="reference internal" href="stdtypes#set" title="set"><code>set</code></a> object, optionally with elements taken from <em>iterable</em>. <code>set</code> is a built-in class. See <a class="reference internal" href="stdtypes#set" title="set"><code>set</code></a> and <a class="reference internal" href="stdtypes#types-set"><span class="std std-ref">Set Types — set, frozenset</span></a> for documentation about this class.</p> <p>For other containers see the built-in <a class="reference internal" href="stdtypes#frozenset" title="frozenset"><code>frozenset</code></a>, <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a>, <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a>, and <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> classes, as well as the <a class="reference internal" href="collections#module-collections" title="collections: Container datatypes"><code>collections</code></a> module.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="setattr">
<code>setattr(object, name, value)</code> </dt> <dd>
<p>This is the counterpart of <a class="reference internal" href="#getattr" title="getattr"><code>getattr()</code></a>. 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, <code>setattr(x, 'foobar', 123)</code> is equivalent to <code>x.foobar = 123</code>.</p> <p><em>name</em> need not be a Python identifier as defined in <a class="reference internal" href="../reference/lexical_analysis#identifiers"><span class="std std-ref">Identifiers and keywords</span></a> unless the object chooses to enforce that, for example in a custom <a class="reference internal" href="../reference/datamodel#object.__getattribute__" title="object.__getattribute__"><code>__getattribute__()</code></a> or via <a class="reference internal" href="../reference/datamodel#object.__slots__" title="object.__slots__"><code>__slots__</code></a>. An attribute whose name is not an identifier will not be accessible using the dot notation, but is accessible through <a class="reference internal" href="#getattr" title="getattr"><code>getattr()</code></a> etc..</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Since <a class="reference internal" href="../reference/expressions#private-name-mangling"><span class="std std-ref">private name mangling</span></a> happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to set it with <a class="reference internal" href="#setattr" title="setattr"><code>setattr()</code></a>.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="slice">
<code>class slice(stop)</code> </dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">slice</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">start</span></em>, <em class="sig-param"><span class="n">stop</span></em>, <em class="sig-param"><span class="n">step</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return a <a class="reference internal" href="../glossary#term-slice"><span class="xref std std-term">slice</span></a> object representing the set of indices specified by <code>range(start, stop, step)</code>. The <em>start</em> and <em>step</em> arguments default to <code>None</code>.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="slice.start">
<code>start</code> </dt> <dd></dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="slice.stop">
<code>stop</code> </dt> <dd></dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="slice.step">
<code>step</code> </dt> <dd>
<p>Slice objects have read-only data attributes <code>start</code>, <code>stop</code>, and <code>step</code> 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.</p> </dd>
</dl> <p>Slice objects are also generated when extended indexing syntax is used. For example: <code>a[start:stop:step]</code> or <code>a[start:stop, i]</code>. See <a class="reference internal" href="itertools#itertools.islice" title="itertools.islice"><code>itertools.islice()</code></a> for an alternate version that returns an <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Slice objects are now <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a> (provided <a class="reference internal" href="#slice.start" title="slice.start"><code>start</code></a>, <a class="reference internal" href="#slice.stop" title="slice.stop"><code>stop</code></a>, and <a class="reference internal" href="#slice.step" title="slice.step"><code>step</code></a> are hashable).</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="sorted">
<code>sorted(iterable, /, *, key=None, reverse=False)</code> </dt> <dd>
<p>Return a new sorted list from the items in <em>iterable</em>.</p> <p>Has two optional arguments which must be specified as keyword arguments.</p> <p><em>key</em> specifies a function of one argument that is used to extract a comparison key from each element in <em>iterable</em> (for example, <code>key=str.lower</code>). The default value is <code>None</code> (compare the elements directly).</p> <p><em>reverse</em> is a boolean value. If set to <code>True</code>, then the list elements are sorted as if each comparison were reversed.</p> <p>Use <a class="reference internal" href="functools#functools.cmp_to_key" title="functools.cmp_to_key"><code>functools.cmp_to_key()</code></a> to convert an old-style <em>cmp</em> function to a <em>key</em> function.</p> <p>The built-in <a class="reference internal" href="#sorted" title="sorted"><code>sorted()</code></a> 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).</p> <p>The sort algorithm uses only <code>&lt;</code> comparisons between items. While defining an <a class="reference internal" href="../reference/datamodel#object.__lt__" title="object.__lt__"><code>__lt__()</code></a> method will suffice for sorting, <span class="target" id="index-10"></span><a class="pep reference external" href="https://peps.python.org/pep-0008/"><strong>PEP 8</strong></a> recommends that all six <a class="reference internal" href="../reference/expressions#comparisons"><span class="std std-ref">rich comparisons</span></a> be implemented. This will help avoid bugs when using the same data with other ordering tools such as <a class="reference internal" href="#max" title="max"><code>max()</code></a> that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call reflected the <a class="reference internal" href="../reference/datamodel#object.__gt__" title="object.__gt__"><code>__gt__()</code></a> method.</p> <p>For sorting examples and a brief sorting tutorial, see <a class="reference internal" href="../howto/sorting#sortinghowto"><span class="std std-ref">Sorting HOW TO</span></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="staticmethod">
<code>@staticmethod</code> </dt> <dd>
<p>Transform a method into a static method.</p> <p>A static method does not receive an implicit first argument. To declare a static method, use this idiom:</p> <pre data-language="python">class C:
    @staticmethod
    def f(arg1, arg2, argN): ...
</pre> <p>The <code>@staticmethod</code> form is a function <a class="reference internal" href="../glossary#term-decorator"><span class="xref std std-term">decorator</span></a> – see <a class="reference internal" href="../reference/compound_stmts#function"><span class="std std-ref">Function definitions</span></a> for details.</p> <p>A static method can be called either on the class (such as <code>C.f()</code>) or on an instance (such as <code>C().f()</code>). Moreover, they can be called as regular functions (such as <code>f()</code>).</p> <p>Static methods in Python are similar to those found in Java or C++. Also, see <a class="reference internal" href="#classmethod" title="classmethod"><code>classmethod()</code></a> for a variant that is useful for creating alternate class constructors.</p> <p>Like all decorators, it is also possible to call <code>staticmethod</code> as 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:</p> <pre data-language="python">def regular_function():
    ...

class C:
    method = staticmethod(regular_function)
</pre> <p>For more information on static methods, see <a class="reference internal" href="../reference/datamodel#types"><span class="std std-ref">The standard type hierarchy</span></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Static methods now inherit the method attributes (<code>__module__</code>, <code>__name__</code>, <code>__qualname__</code>, <code>__doc__</code> and <code>__annotations__</code>), have a new <code>__wrapped__</code> attribute, and are now callable as regular functions.</p> </div> </dd>
</dl> <span class="target" id="func-str"><span id="index-11"></span></span><dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">str</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">object</span><span class="o">=</span><span class="default_value">''</span></em><span class="sig-paren">)</span>
</dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">str</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">object</span><span class="o">=</span><span class="default_value">b''</span></em>, <em class="sig-param"><span class="n">encoding</span><span class="o">=</span><span class="default_value">'utf-8'</span></em>, <em class="sig-param"><span class="n">errors</span><span class="o">=</span><span class="default_value">'strict'</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> version of <em>object</em>. See <a class="reference internal" href="stdtypes#str" title="str"><code>str()</code></a> for details.</p> <p><code>str</code> is the built-in string <a class="reference internal" href="../glossary#term-class"><span class="xref std std-term">class</span></a>. For general information about strings, see <a class="reference internal" href="stdtypes#textseq"><span class="std std-ref">Text Sequence Type — str</span></a>.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="sum">
<code>sum(iterable, /, start=0)</code> </dt> <dd>
<p>Sums <em>start</em> and the items of an <em>iterable</em> from left to right and returns the total. The <em>iterable</em>’s items are normally numbers, and the start value is not allowed to be a string.</p> <p>For some use cases, there are good alternatives to <a class="reference internal" href="#sum" title="sum"><code>sum()</code></a>. The preferred, fast way to concatenate a sequence of strings is by calling <code>''.join(sequence)</code>. To add floating point values with extended precision, see <a class="reference internal" href="math#math.fsum" title="math.fsum"><code>math.fsum()</code></a>. To concatenate a series of iterables, consider using <a class="reference internal" href="itertools#itertools.chain" title="itertools.chain"><code>itertools.chain()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <em>start</em> parameter can be specified as a keyword argument.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Summation of floats switched to an algorithm that gives higher accuracy on most builds.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="super">
<code>class super</code> </dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">super</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">type</span></em>, <em class="sig-param"><span class="n">object_or_type</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return a proxy object that delegates method calls to a parent or sibling class of <em>type</em>. This is useful for accessing inherited methods that have been overridden in a class.</p> <p>The <em>object_or_type</em> determines the <a class="reference internal" href="../glossary#term-method-resolution-order"><span class="xref std std-term">method resolution order</span></a> to be searched. The search starts from the class right after the <em>type</em>.</p> <p>For example, if <a class="reference internal" href="stdtypes#class.__mro__" title="class.__mro__"><code>__mro__</code></a> of <em>object_or_type</em> is <code>D -&gt; B -&gt; C -&gt; A -&gt; object</code> and the value of <em>type</em> is <code>B</code>, then <a class="reference internal" href="#super" title="super"><code>super()</code></a> searches <code>C -&gt; A -&gt; object</code>.</p> <p>The <a class="reference internal" href="stdtypes#class.__mro__" title="class.__mro__"><code>__mro__</code></a> attribute of the <em>object_or_type</em> lists the method resolution search order used by both <a class="reference internal" href="#getattr" title="getattr"><code>getattr()</code></a> and <a class="reference internal" href="#super" title="super"><code>super()</code></a>. The attribute is dynamic and can change whenever the inheritance hierarchy is updated.</p> <p>If the second argument is omitted, the super object returned is unbound. If the second argument is an object, <code>isinstance(obj, type)</code> must be true. If the second argument is a type, <code>issubclass(type2, type)</code> must be true (this is useful for classmethods).</p> <p>There are two typical use cases for <em>super</em>. In a class hierarchy with single inheritance, <em>super</em> 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 <em>super</em> in other programming languages.</p> <p>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).</p> <p>For both use cases, a typical superclass call looks like this:</p> <pre data-language="python">class C(B):
    def method(self, arg):
        super().method(arg)    # This does the same thing as:
                               # super(C, self).method(arg)
</pre> <p>In addition to method lookups, <a class="reference internal" href="#super" title="super"><code>super()</code></a> also works for attribute lookups. One possible use case for this is calling <a class="reference internal" href="../glossary#term-descriptor"><span class="xref std std-term">descriptors</span></a> in a parent or sibling class.</p> <p>Note that <a class="reference internal" href="#super" title="super"><code>super()</code></a> is implemented as part of the binding process for explicit dotted attribute lookups such as <code>super().__getitem__(name)</code>. It does so by implementing its own <a class="reference internal" href="../reference/datamodel#object.__getattribute__" title="object.__getattribute__"><code>__getattribute__()</code></a> method for searching classes in a predictable order that supports cooperative multiple inheritance. Accordingly, <a class="reference internal" href="#super" title="super"><code>super()</code></a> is undefined for implicit lookups using statements or operators such as <code>super()[name]</code>.</p> <p>Also note that, aside from the zero argument form, <a class="reference internal" href="#super" title="super"><code>super()</code></a> 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.</p> <p>For practical suggestions on how to design cooperative classes using <a class="reference internal" href="#super" title="super"><code>super()</code></a>, see <a class="reference external" href="https://rhettinger.wordpress.com/2011/05/26/super-considered-super/">guide to using super()</a>.</p> </dd>
</dl> <span class="target" id="func-tuple"></span><dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">tuple</span>
</dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">tuple</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">iterable</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Rather than being a function, <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> is actually an immutable sequence type, as documented in <a class="reference internal" href="stdtypes#typesseq-tuple"><span class="std std-ref">Tuples</span></a> and <a class="reference internal" href="stdtypes#typesseq"><span class="std std-ref">Sequence Types — list, tuple, range</span></a>.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="type">
<code>class type(object)</code> </dt> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-name descname">type</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">name</span></em>, <em class="sig-param"><span class="n">bases</span></em>, <em class="sig-param"><span class="n">dict</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwds</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p id="index-12">With one argument, return the type of an <em>object</em>. The return value is a type object and generally the same object as returned by <a class="reference internal" href="stdtypes#instance.__class__" title="instance.__class__"><code>object.__class__</code></a>.</p> <p>The <a class="reference internal" href="#isinstance" title="isinstance"><code>isinstance()</code></a> built-in function is recommended for testing the type of an object, because it takes subclasses into account.</p> <p>With three arguments, return a new type object. This is essentially a dynamic form of the <a class="reference internal" href="../reference/compound_stmts#class"><code>class</code></a> statement. The <em>name</em> string is the class name and becomes the <a class="reference internal" href="stdtypes#definition.__name__" title="definition.__name__"><code>__name__</code></a> attribute. The <em>bases</em> tuple contains the base classes and becomes the <a class="reference internal" href="stdtypes#class.__bases__" title="class.__bases__"><code>__bases__</code></a> attribute; if empty, <a class="reference internal" href="#object" title="object"><code>object</code></a>, the ultimate base of all classes, is added. The <em>dict</em> dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming the <a class="reference internal" href="stdtypes#object.__dict__" title="object.__dict__"><code>__dict__</code></a> attribute. The following two statements create identical <a class="reference internal" href="#type" title="type"><code>type</code></a> objects:</p> <pre data-language="python">&gt;&gt;&gt; class X:
...     a = 1
...
&gt;&gt;&gt; X = type('X', (), dict(a=1))
</pre> <p>See also <a class="reference internal" href="stdtypes#bltin-type-objects"><span class="std std-ref">Type Objects</span></a>.</p> <p>Keyword arguments provided to the three argument form are passed to the appropriate metaclass machinery (usually <a class="reference internal" href="../reference/datamodel#object.__init_subclass__" title="object.__init_subclass__"><code>__init_subclass__()</code></a>) in the same way that keywords in a class definition (besides <em>metaclass</em>) would.</p> <p>See also <a class="reference internal" href="../reference/datamodel#class-customization"><span class="std std-ref">Customizing class creation</span></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Subclasses of <a class="reference internal" href="#type" title="type"><code>type</code></a> which don’t override <code>type.__new__</code> may no longer use the one-argument form to get the type of an object.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="vars">
<code>vars()</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">vars</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">object</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Return the <a class="reference internal" href="stdtypes#object.__dict__" title="object.__dict__"><code>__dict__</code></a> attribute for a module, class, instance, or any other object with a <a class="reference internal" href="stdtypes#object.__dict__" title="object.__dict__"><code>__dict__</code></a> attribute.</p> <p>Objects such as modules and instances have an updateable <a class="reference internal" href="stdtypes#object.__dict__" title="object.__dict__"><code>__dict__</code></a> attribute; however, other objects may have write restrictions on their <a class="reference internal" href="stdtypes#object.__dict__" title="object.__dict__"><code>__dict__</code></a> attributes (for example, classes use a <a class="reference internal" href="types#types.MappingProxyType" title="types.MappingProxyType"><code>types.MappingProxyType</code></a> to prevent direct dictionary updates).</p> <p>Without an argument, <a class="reference internal" href="#vars" title="vars"><code>vars()</code></a> acts like <a class="reference internal" href="#locals" title="locals"><code>locals()</code></a>. Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.</p> <p>A <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised if an object is specified but it doesn’t have a <a class="reference internal" href="stdtypes#object.__dict__" title="object.__dict__"><code>__dict__</code></a> attribute (for example, if its class defines the <a class="reference internal" href="../reference/datamodel#object.__slots__" title="object.__slots__"><code>__slots__</code></a> attribute).</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="zip">
<code>zip(*iterables, strict=False)</code> </dt> <dd>
<p>Iterate over several iterables in parallel, producing tuples with an item from each one.</p> <p>Example:</p> <pre data-language="python">&gt;&gt;&gt; for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
...     print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
</pre> <p>More formally: <a class="reference internal" href="#zip" title="zip"><code>zip()</code></a> returns an iterator of tuples, where the <em>i</em>-th tuple contains the <em>i</em>-th element from each of the argument iterables.</p> <p>Another way to think of <a class="reference internal" href="#zip" title="zip"><code>zip()</code></a> is that it turns rows into columns, and columns into rows. This is similar to <a class="reference external" href="https://en.wikipedia.org/wiki/Transpose">transposing a matrix</a>.</p> <p><a class="reference internal" href="#zip" title="zip"><code>zip()</code></a> is lazy: The elements won’t be processed until the iterable is iterated on, e.g. by a <code>for</code> loop or by wrapping in a <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a>.</p> <p>One thing to consider is that the iterables passed to <a class="reference internal" href="#zip" title="zip"><code>zip()</code></a> 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:</p> <ul> <li>
<p>By default, <a class="reference internal" href="#zip" title="zip"><code>zip()</code></a> 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:</p> <pre data-language="python">&gt;&gt;&gt; list(zip(range(3), ['fee', 'fi', 'fo', 'fum']))
[(0, 'fee'), (1, 'fi'), (2, 'fo')]
</pre> </li> <li>
<p><a class="reference internal" href="#zip" title="zip"><code>zip()</code></a> is often used in cases where the iterables are assumed to be of equal length. In such cases, it’s recommended to use the <code>strict=True</code> option. Its output is the same as regular <a class="reference internal" href="#zip" title="zip"><code>zip()</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True))
[('a', 1), ('b', 2), ('c', 3)]
</pre> <p>Unlike the default behavior, it raises a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> if one iterable is exhausted before the others:</p> <pre data-language="python">&gt;&gt;&gt; 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
</pre> <p>Without the <code>strict=True</code> 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.</p> </li> <li>Shorter iterables can be padded with a constant value to make all the iterables have the same length. This is done by <a class="reference internal" href="itertools#itertools.zip_longest" title="itertools.zip_longest"><code>itertools.zip_longest()</code></a>.</li> </ul> <p>Edge cases: With a single iterable argument, <a class="reference internal" href="#zip" title="zip"><code>zip()</code></a> returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.</p> <p>Tips and tricks:</p> <ul> <li>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 <code>zip(*[iter(s)]*n, strict=True)</code>. This repeats the <em>same</em> iterator <code>n</code> times so that each output tuple has the result of <code>n</code> calls to the iterator. This has the effect of dividing the input into n-length chunks.</li> <li>
<p><a class="reference internal" href="#zip" title="zip"><code>zip()</code></a> in conjunction with the <code>*</code> operator can be used to unzip a list:</p> <pre data-language="python">&gt;&gt;&gt; x = [1, 2, 3]
&gt;&gt;&gt; y = [4, 5, 6]
&gt;&gt;&gt; list(zip(x, y))
[(1, 4), (2, 5), (3, 6)]
&gt;&gt;&gt; x2, y2 = zip(*zip(x, y))
&gt;&gt;&gt; x == list(x2) and y == list(y2)
True
</pre> </li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Added the <code>strict</code> argument.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="import__">
<code>__import__(name, globals=None, locals=None, fromlist=(), level=0)</code> </dt> <dd>
<div class="admonition note" id="index-13"> <p class="admonition-title">Note</p> <p>This is an advanced function that is not needed in everyday Python programming, unlike <a class="reference internal" href="importlib#importlib.import_module" title="importlib.import_module"><code>importlib.import_module()</code></a>.</p> </div> <p>This function is invoked by the <a class="reference internal" href="../reference/simple_stmts#import"><code>import</code></a> statement. It can be replaced (by importing the <a class="reference internal" href="builtins#module-builtins" title="builtins: The module that provides the built-in namespace."><code>builtins</code></a> module and assigning to <code>builtins.__import__</code>) in order to change semantics of the <code>import</code> statement, but doing so is <strong>strongly</strong> discouraged as it is usually simpler to use import hooks (see <span class="target" id="index-14"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a>) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of <a class="reference internal" href="#import__" title="__import__"><code>__import__()</code></a> is also discouraged in favor of <a class="reference internal" href="importlib#importlib.import_module" title="importlib.import_module"><code>importlib.import_module()</code></a>.</p> <p>The function imports the module <em>name</em>, potentially using the given <em>globals</em> and <em>locals</em> to determine how to interpret the name in a package context. The <em>fromlist</em> gives the names of objects or submodules that should be imported from the module given by <em>name</em>. The standard implementation does not use its <em>locals</em> argument at all and uses its <em>globals</em> only to determine the package context of the <a class="reference internal" href="../reference/simple_stmts#import"><code>import</code></a> statement.</p> <p><em>level</em> specifies whether to use absolute or relative imports. <code>0</code> (the default) means only perform absolute imports. Positive values for <em>level</em> indicate the number of parent directories to search relative to the directory of the module calling <a class="reference internal" href="#import__" title="__import__"><code>__import__()</code></a> (see <span class="target" id="index-15"></span><a class="pep reference external" href="https://peps.python.org/pep-0328/"><strong>PEP 328</strong></a> for the details).</p> <p>When the <em>name</em> variable is of the form <code>package.module</code>, normally, the top-level package (the name up till the first dot) is returned, <em>not</em> the module named by <em>name</em>. However, when a non-empty <em>fromlist</em> argument is given, the module named by <em>name</em> is returned.</p> <p>For example, the statement <code>import spam</code> results in bytecode resembling the following code:</p> <pre data-language="python">spam = __import__('spam', globals(), locals(), [], 0)
</pre> <p>The statement <code>import spam.ham</code> results in this call:</p> <pre data-language="python">spam = __import__('spam.ham', globals(), locals(), [], 0)
</pre> <p>Note how <a class="reference internal" href="#import__" title="__import__"><code>__import__()</code></a> returns the toplevel module here because this is the object that is bound to a name by the <a class="reference internal" href="../reference/simple_stmts#import"><code>import</code></a> statement.</p> <p>On the other hand, the statement <code>from spam.ham import eggs, sausage as
saus</code> results in</p> <pre data-language="python">_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage
</pre> <p>Here, the <code>spam.ham</code> module is returned from <a class="reference internal" href="#import__" title="__import__"><code>__import__()</code></a>. From this object, the names to import are retrieved and assigned to their respective names.</p> <p>If you simply want to import a module (potentially within a package) by name, use <a class="reference internal" href="importlib#importlib.import_module" title="importlib.import_module"><code>importlib.import_module()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Negative values for <em>level</em> are no longer supported (which also changes the default value to 0).</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>When the command line options <a class="reference internal" href="../using/cmdline#cmdoption-E"><code>-E</code></a> or <a class="reference internal" href="../using/cmdline#cmdoption-I"><code>-I</code></a> are being used, the environment variable <span class="target" id="index-16"></span><a class="reference internal" href="../using/cmdline#envvar-PYTHONCASEOK"><code>PYTHONCASEOK</code></a> is now ignored.</p> </div> </dd>
</dl> <h4 class="rubric">Footnotes</h4> <dl class="footnote brackets"> <dt class="label" id="id2">
<code>1</code> </dt> <dd>
<p>Note that the parser only accepts the Unix-style end of line convention. If you are reading the code from a file, make sure to use newline conversion mode to convert Windows or Mac-style newlines.</p> </dd> </dl> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/library/functions.html" class="_attribution-link">https://docs.python.org/3.12/library/functions.html</a>
  </p>
</div>