The Python Language Reference Release 3.9.7

Total Page:16

File Type:pdf, Size:1020Kb

The Python Language Reference Release 3.9.7 The Python Language Reference Release 3.9.7 Guido van Rossum and the Python development team August 30, 2021 Python Software Foundation Email: [email protected] CONTENTS 1 Introduction 3 1.1 Alternate Implementations ...................................... 3 1.2 Notation ............................................... 4 2 Lexical analysis 5 2.1 Line structure ............................................. 5 2.1.1 Logical lines ......................................... 5 2.1.2 Physical lines ........................................ 5 2.1.3 Comments .......................................... 5 2.1.4 Encoding declarations .................................... 6 2.1.5 Explicit line joining ..................................... 6 2.1.6 Implicit line joining ..................................... 6 2.1.7 Blank lines .......................................... 7 2.1.8 Indentation ......................................... 7 2.1.9 Whitespace between tokens ................................. 8 2.2 Other tokens ............................................. 8 2.3 Identifiers and keywords ....................................... 8 2.3.1 Keywords .......................................... 9 2.3.2 Reserved classes of identifiers ................................ 9 2.4 Literals ................................................ 9 2.4.1 String and Bytes literals ................................... 10 2.4.2 String literal concatenation ................................. 12 2.4.3 Formatted string literals ................................... 12 2.4.4 Numeric literals ....................................... 14 2.4.5 Integer literals ........................................ 14 2.4.6 Floating point literals .................................... 15 2.4.7 Imaginary literals ...................................... 15 2.5 Operators ............................................... 15 2.6 Delimiters ............................................... 15 3 Data model 17 3.1 Objects, values and types ....................................... 17 3.2 The standard type hierarchy ..................................... 18 3.3 Special method names ........................................ 26 3.3.1 Basic customization ..................................... 26 3.3.2 Customizing attribute access ................................ 29 3.3.3 Customizing class creation ................................. 33 3.3.4 Customizing instance and subclass checks .......................... 36 3.3.5 Emulating generic types ................................... 36 3.3.6 Emulating callable objects .................................. 37 3.3.7 Emulating container types .................................. 37 3.3.8 Emulating numeric types .................................. 39 3.3.9 With Statement Context Managers ............................. 41 3.3.10 Special method lookup ................................... 41 i 3.4 Coroutines .............................................. 42 3.4.1 Awaitable Objects ...................................... 42 3.4.2 Coroutine Objects ...................................... 43 3.4.3 Asynchronous Iterators ................................... 43 3.4.4 Asynchronous Context Managers .............................. 44 4 Execution model 45 4.1 Structure of a program ........................................ 45 4.2 Naming and binding ......................................... 45 4.2.1 Binding of names ...................................... 45 4.2.2 Resolution of names ..................................... 46 4.2.3 Builtins and restricted execution ............................... 46 4.2.4 Interaction with dynamic features .............................. 47 4.3 Exceptions .............................................. 47 5 The import system 49 5.1 importlib ............................................. 49 5.2 Packages ............................................... 50 5.2.1 Regular packages ...................................... 50 5.2.2 Namespace packages .................................... 50 5.3 Searching ............................................... 51 5.3.1 The module cache ...................................... 51 5.3.2 Finders and loaders ..................................... 51 5.3.3 Import hooks ........................................ 52 5.3.4 The meta path ........................................ 52 5.4 Loading ................................................ 53 5.4.1 Loaders ........................................... 54 5.4.2 Submodules ......................................... 54 5.4.3 Module spec ......................................... 55 5.4.4 Import-related module attributes .............................. 55 5.4.5 module.__path__ ...................................... 56 5.4.6 Module reprs ........................................ 56 5.4.7 Cached bytecode invalidation ................................ 57 5.5 The Path Based Finder ........................................ 57 5.5.1 Path entry finders ...................................... 58 5.5.2 Path entry finder protocol .................................. 59 5.6 Replacing the standard import system ................................ 59 5.7 Package Relative Imports ....................................... 59 5.8 Special considerations for __main__ ................................. 60 5.8.1 __main__.__spec__ ..................................... 60 5.9 Open issues .............................................. 61 5.10 References .............................................. 61 6 Expressions 63 6.1 Arithmetic conversions ........................................ 63 6.2 Atoms ................................................. 63 6.2.1 Identifiers (Names) ..................................... 64 6.2.2 Literals ........................................... 64 6.2.3 Parenthesized forms ..................................... 64 6.2.4 Displays for lists, sets and dictionaries ............................ 65 6.2.5 List displays ......................................... 65 6.2.6 Set displays ......................................... 66 6.2.7 Dictionary displays ..................................... 66 6.2.8 Generator expressions .................................... 66 6.2.9 Yield expressions ...................................... 67 6.3 Primaries ............................................... 71 6.3.1 Attribute references ..................................... 71 6.3.2 Subscriptions ........................................ 71 6.3.3 Slicings ........................................... 72 ii 6.3.4 Calls ............................................. 72 6.4 Await expression ........................................... 74 6.5 The power operator .......................................... 74 6.6 Unary arithmetic and bitwise operations ............................... 74 6.7 Binary arithmetic operations ..................................... 75 6.8 Shifting operations .......................................... 76 6.9 Binary bitwise operations ....................................... 76 6.10 Comparisons ............................................. 76 6.10.1 Value comparisons ..................................... 77 6.10.2 Membership test operations ................................. 79 6.10.3 Identity comparisons .................................... 79 6.11 Boolean operations .......................................... 79 6.12 Assignment expressions ........................................ 80 6.13 Conditional expressions ........................................ 80 6.14 Lambdas ............................................... 80 6.15 Expression lists ............................................ 81 6.16 Evaluation order ........................................... 81 6.17 Operator precedence ......................................... 81 7 Simple statements 83 7.1 Expression statements ........................................ 83 7.2 Assignment statements ........................................ 84 7.2.1 Augmented assignment statements ............................. 86 7.2.2 Annotated assignment statements .............................. 86 7.3 The assert statement ........................................ 87 7.4 The pass statement ......................................... 87 7.5 The del statement .......................................... 87 7.6 The return statement ........................................ 88 7.7 The yield statement ........................................ 88 7.8 The raise statement ........................................ 89 7.9 The break statement ........................................ 90 7.10 The continue statement ...................................... 90 7.11 The import statement ........................................ 90 7.11.1 Future statements ...................................... 92 7.12 The global statement ........................................ 93 7.13 The nonlocal statement ...................................... 93 8 Compound statements 95 8.1 The if statement ........................................... 96 8.2 The while statement ........................................ 96 8.3 The for statement .......................................... 96 8.4 The try statement .......................................... 97 8.5 The with statement ......................................... 99 8.6 Function definitions .......................................... 100 8.7 Class definitions ............................................ 102 8.8 Coroutines .............................................. 103 8.8.1 Coroutine function definition ................................ 103 8.8.2 The async for statement ................................ 103 8.8.3 The async with
Recommended publications
  • ISO/IEC JTC 1/SC 22/WG4 N 0163 Information Technology
    ISO/IEC JTC 1/SC 22/WG4 N 0163 Date: 2002-05-21 Reference number of document: WDTR 19755 Version 1.1 Committee identification: ISO/IEC JTC 1/SC 22 /WG 4 Secretariat: ANSI Information Technology — Programming languages, their environments and system software interfaces — Object finalization for programming language COBOL Warning This document is an ISO/IEC proposed draft Technical Report. It is not an ISO/IEC International Technical Report. It is distributed for review and comment. It is subject to change without notice and shall not be referred to as an International Technical Report or International Standard. Recipients of this document are invited to submit, with their comments, notification of any relevant patent rights of which they are aware and to provide supporting documentation. Document type: Technical report Document subtype: n/a Document stage: (20) Preparation Document language: E ISO/WDTR 19755 Copyright notice This ISO/IEC document is a working draft and is copyright-protected by ISO/IEC. Requests for permission to reproduce this document for the purpose of selling it should be addressed as shown below or to ISO’s member body in the country of the requester: Copyright manager ISO Central Secretariat 1 rue de Varembé 1211 Geneva 20 Switzerland tel: +41 22 749 0111 fax: +41 22 734 0179 email: [email protected] Reproduction for sales purposes may be subject to royalty payments or a licensing agreement. Violators may be prosecuted. ii © ISO/IEC 2002 – All rights reserved ISO/IEC WDTR 19755 Acknowledgement notice COBOL originated in 1959 as a common business oriented language developed by the Conference on Data Systems Languages (CODASYL).
    [Show full text]
  • Preview Objective-C Tutorial (PDF Version)
    Objective-C Objective-C About the Tutorial Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. This is the main programming language used by Apple for the OS X and iOS operating systems and their respective APIs, Cocoa and Cocoa Touch. This reference will take you through simple and practical approach while learning Objective-C Programming language. Audience This reference has been prepared for the beginners to help them understand basic to advanced concepts related to Objective-C Programming languages. Prerequisites Before you start doing practice with various types of examples given in this reference, I'm making an assumption that you are already aware about what is a computer program, and what is a computer programming language? Copyright & Disclaimer © Copyright 2015 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book can retain a copy for future reference but commercial use of this data is not allowed. Distribution or republishing any content or a part of the content of this e-book in any manner is also not allowed without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at [email protected] ii Objective-C Table of Contents About the Tutorial ..................................................................................................................................
    [Show full text]
  • Stable/Build) • --Port PORT - Set the PORT Number (Default: 8000)
    Pyodide Release 0.18.1 unknown Sep 16, 2021 CONTENTS 1 Using Pyodide 3 1.1 Getting started..............................................3 1.2 Downloading and deploying Pyodide..................................6 1.3 Using Pyodide..............................................7 1.4 Loading packages............................................ 12 1.5 Type translations............................................. 14 1.6 Pyodide Python compatibility...................................... 25 1.7 API Reference.............................................. 26 1.8 Frequently Asked Questions....................................... 50 2 Development 55 2.1 Building from sources.......................................... 55 2.2 Creating a Pyodide package....................................... 57 2.3 How to Contribute............................................ 64 2.4 Testing and benchmarking........................................ 74 2.5 Interactive Debugging.......................................... 76 3 Project 79 3.1 About Pyodide.............................................. 79 3.2 Roadmap................................................. 80 3.3 Code of Conduct............................................. 82 3.4 Governance and Decision-making.................................... 83 3.5 Change Log............................................... 85 3.6 Related Projects............................................. 95 4 Indices and tables 97 Python Module Index 99 Index 101 i ii Pyodide, Release 0.18.1 Python with the scientific stack, compiled to WebAssembly.
    [Show full text]
  • Strings in C++
    Programming Abstractions C S 1 0 6 X Cynthia Lee Today’s Topics Introducing C++ from the Java Programmer’s Perspective . Absolute value example, continued › C++ strings and streams ADTs: Abstract Data Types . Introduction: What are ADTs? . Queen safety example › Grid data structure › Passing objects by reference • const reference parameters › Loop over “neighbors” in a grid Strings in C++ STRING LITERAL VS STRING CLASS CONCATENATION STRING CLASS METHODS 4 Using cout and strings int main(){ int n = absoluteValue(-5); string s = "|-5|"; s += " = "; • This prints |-5| = 5 cout << s << n << endl; • The + operator return 0; concatenates strings, } and += works in the way int absoluteValue(int n) { you’d expect. if (n<0){ n = -n; } return n; } 5 Using cout and strings int main(){ int n = absoluteValue(-5); But SURPRISE!…this one string s = "|-5|" + " = "; doesn’t work. cout << s << n << endl; return 0; } int absoluteValue(int n) { if (n<0){ n = -n; } return n; } C++ string objects and string literals . In this class, we will interact with two types of strings: › String literals are just hard-coded string values: • "hello!" "1234" "#nailedit" • They have no methods that do things for us • Think of them like integer literals: you can’t do "4.add(5);" //no › String objects are objects with lots of helpful methods and operators: • string s; • string piece = s.substr(0,3); • s.append(t); //or, equivalently: s+= t; String object member functions (3.2) Member function name Description s.append(str) add text to the end of a string s.compare(str) return
    [Show full text]
  • Visual Smalltalk Enterprise ™ ™
    Visual Smalltalk Enterprise ™ ™ Language Reference P46-0201-00 Copyright © 1999–2000 Cincom Systems, Inc. All rights reserved. Copyright © 1999–2000 Seagull Systems, Inc. All rights reserved. This product contains copyrighted third-party software. Part Number: P46-0201-00 Software Release 3.2 This document is subject to change without notice. RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013. Trademark acknowledgments: CINCOM, CINCOM SYSTEMS, and the Cincom logo are registered trademarks of Cincom Systems, Inc. Visual Smalltalk is a trademark of Cincom Systems, Inc., its subsidiaries, or successors and are registered in the United States and other countries. Microsoft Windows is a registered trademark of Microsoft, Inc. Win32 is a trademark of Microsoft, Inc. OS/2 is a registered trademark of IBM Corporation. Other product names mentioned herein are used for identification purposes only, and may be trademarks of their respective companies. The following copyright notices apply to software that accompanies this documentation: Visual Smalltalk is furnished under a license and may not be used, copied, disclosed, and/or distributed except in accordance with the terms of said license. No class names, hierarchies, or protocols may be copied for implementation in other systems. This manual set and online system documentation copyright © 1999–2000 by Cincom Systems, Inc. All rights reserved. No part of it may be copied, photocopied, reproduced, translated, or reduced to any electronic medium or machine-readable form without prior written consent from Cincom.
    [Show full text]
  • Gnu Smalltalk Library Reference Version 3.2.5 24 November 2017
    gnu Smalltalk Library Reference Version 3.2.5 24 November 2017 by Paolo Bonzini Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled \GNU Free Documentation License". 1 3 1 Base classes 1.1 Tree Classes documented in this manual are boldfaced. Autoload Object Behavior ClassDescription Class Metaclass BlockClosure Boolean False True CObject CAggregate CArray CPtr CString CCallable CCallbackDescriptor CFunctionDescriptor CCompound CStruct CUnion CScalar CChar CDouble CFloat CInt CLong CLongDouble CLongLong CShort CSmalltalk CUChar CByte CBoolean CUInt CULong CULongLong CUShort ContextPart 4 GNU Smalltalk Library Reference BlockContext MethodContext Continuation CType CPtrCType CArrayCType CScalarCType CStringCType Delay Directory DLD DumperProxy AlternativeObjectProxy NullProxy VersionableObjectProxy PluggableProxy SingletonProxy DynamicVariable Exception Error ArithmeticError ZeroDivide MessageNotUnderstood SystemExceptions.InvalidValue SystemExceptions.EmptyCollection SystemExceptions.InvalidArgument SystemExceptions.AlreadyDefined SystemExceptions.ArgumentOutOfRange SystemExceptions.IndexOutOfRange SystemExceptions.InvalidSize SystemExceptions.NotFound SystemExceptions.PackageNotAvailable SystemExceptions.InvalidProcessState SystemExceptions.InvalidState
    [Show full text]
  • C Constants and Literals Integer Literals Floating-Point Literals
    C Constants and Literals The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. The constants are treated just like regular variables except that their values cannot be modified after their definition. Integer literals An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here are some examples of integer literals: Floating-point literals A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Here are some examples of floating-point literals: 1 | P a g e Character constants Character literals are enclosed in single quotes, e.g., 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').
    [Show full text]
  • Variable Feature Usage Patterns in PHP
    Variable Feature Usage Patterns in PHP Mark Hills East Carolina University, Greenville, NC, USA [email protected] Abstract—PHP allows the names of variables, classes, func- and classes at runtime. Below, we refer to these generally as tions, methods, and properties to be given dynamically, as variable features, and specifically as, e.g., variable functions expressions that, when evaluated, return an identifier as a string. or variable methods. While this provides greater flexibility for programmers, it also makes PHP programs harder to precisely analyze and understand. The main contributions presented in this paper are as follows. In this paper we present a number of patterns designed to First, taking advantage of our prior work, we have developed recognize idiomatic uses of these features that can be statically a number of patterns for detecting idiomatic uses of variable resolved to a precise set of possible names. We then evaluate these features in PHP programs and for resolving these uses to a patterns across a corpus of 20 open-source systems totaling more set of possible names. Written using the Rascal programming than 3.7 million lines of PHP, showing how often these patterns occur in actual PHP code, demonstrating their effectiveness at language [2], [3], these patterns work over the ASTs of the statically determining the names that can be used at runtime, PHP scripts, with more advanced patterns also taking advantage and exploring anti-patterns that indicate when the identifier of control flow graphs and lightweight analysis algorithms for computation is truly dynamic. detecting value flow and reachability. Each of these patterns works generally across all variable features, instead of being I.
    [Show full text]
  • Strings String Literals String Variables Warning!
    Strings String literals • Strings are not a built-in data type. char *name = "csc209h"; printf("This is a string literal\n"); • C provides almost no special means of defining or working with strings. • String literals are stored as character arrays, but • A string is an array of characters you can't change them. terminated with a “null character” ('\0') name[1] = 'c'; /* Error */ • The compiler reserves space for the number of characters in the string plus one to store the null character. 1 2 String Variables Warning! • arrays are used to store strings • Big difference between a string's length • strings are terminated by the null character ('\0') and size! (That's how we know a string's length.) – length is the number of non-null characters • Initializing strings: currently present in the string – char course[8] = "csc209h"; – size if the amount of memory allocated for – char course[8] = {'c','s','c',… – course is an array of characters storing the string – char *s = "csc209h"; • Eg., char s[10] = "abc"; – s is a pointer to a string literal – length of s = 3, size of s = 10 – ensure length+1 ≤ size! 3 4 String functions Copying a string • The library provides a bunch of string char *strncpy(char *dest, functions which you should use (most of the char *src, int size) time). – copy up to size bytes of the string pointed to by src in to dest. Returns a pointer to dest. $ man string – Do not use strcpy (buffer overflow problem!) • int strlen(char *str) – returns the length of the string. Remember that char str1[3]; the storage needed for a string is one plus its char str2[5] = "abcd"; length /*common error*/ strncpy(str1, str2, strlen(str2));/*wrong*/ 5 6 Concatenating strings Comparing strings char *strncat(char *s1, const char *s2, size_t n); int strcmp(const char *s1, const char *s2) – appends the contents of string s2 to the end of s1, and returns s1.
    [Show full text]
  • FME® Desktop Copyright © 1994 – 2018, Safe Software Inc. All Rights Reserved
    FME® Desktop Copyright © 1994 – 2018, Safe Software Inc. All rights reserved. FME® is the registered trademark of Safe Software Inc. All brands and their product names mentioned herein may be trademarks or registered trademarks of their respective holders and should be noted as such. FME Desktop includes components licensed as described below: Autodesk FBX This software contains Autodesk® FBX® code developed by Autodesk, Inc. Copyright 2016 Autodesk, Inc. All rights, reserved. Such code is provided “as is” and Autodesk, Inc. disclaims any and all warranties, whether express or implied, including without limitation the implied warranties of merchantability, fitness for a particular purpose or non-infringement of third party rights. In no event shall Autodesk, Inc. be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of such code. Autodesk Libraries Contains Autodesk® RealDWG by Autodesk, Inc., Copyright © 2017 Autodesk, Inc. All rights reserved. Home page: www.autodesk.com/realdwg Belge72/b.Lambert72A NTv2 Grid Copyright © 2014-2016 Nicolas SIMON and validated by Service Public de Wallonie and Nationaal Geografisch Instituut. Under Creative Commons Attribution license (CC BY). Bentley i-Model SDK This software includes some components from the Bentley i-Model SDK. Copyright © Bentley Systems International Limited CARIS CSAR GDAL Plugin CARIS CSAR GDAL Plugin is owned by and copyright © 2013 Universal Systems Ltd.
    [Show full text]
  • A Tour of the Squeak Object Engine
    A Tour of the Squeak Object Engine A Tour of the Squeak Object Engine Tim Rowledge, [email protected] Introduction This chapter is intended to explain some basics of how a Virtual Machine (VM) works, why a VM is useful, what it does for the Squeak programmer and user, and how the Squeak VM might develop in the future. What is a Virtual Machine and why do we need one? A Virtual Machine provides us with a pretense of being a machine other than the actual hardware in use. Using one allows systems that behave differently than the host hardware to run as if on hardware designed for them. The term Object Engine is less commonly used but is a useful concept that includes the lowest system areas of the langauge environment running on the VM. Since there is often some flux in the definition of which components are within the actual VM and which are part of the supported environment, Object Engine is useful as a more inclusive term. The term Virtual Machine is used in several ways. When IBM refer to VM/CMS they are referring to a way of making a mainframe behave as if it is many machines, so that programs can assume they have total control even though they do not. Intel provide a somewhat similar facility in the x86 architecture(?), referred to as Virtual Mode. This sort of VM is a complete hardware simulation, often supported at the lowest level by the hardware. Another sort of VM is the emulator - SoftWindows for the Mac, Acorn's !PC, Linux's WINE are good examples - where another machine and/or OS is simulated to allow a Mac user to run Windows programs, an Acorn RiscPC or a Linux machine to run Windows98 programs and so on.
    [Show full text]
  • Linux from Scratch 版本 R11.0-36-中⽂翻译版 发布于 2021 年 9 ⽉ 21 ⽇
    Linux From Scratch 版本 r11.0-36-中⽂翻译版 发布于 2021 年 9 ⽉ 21 ⽇ 由 Gerard Beekmans 原著 总编辑:Bruce Dubbs Linux From Scratch: 版本 r11.0-36-中⽂翻译版 : 发布于 2021 年 9 ⽉ 21 ⽇ 由 由 Gerard Beekmans 原著和总编辑:Bruce Dubbs 版权所有 © 1999-2021 Gerard Beekmans 版权所有 © 1999-2021, Gerard Beekmans 保留所有权利。 本书依照 Creative Commons License 许可证发布。 从本书中提取的计算机命令依照 MIT License 许可证发布。 Linux® 是Linus Torvalds 的注册商标。 Linux From Scratch - 版本 r11.0-36-中⽂翻译版 ⽬录 序⾔ .................................................................................................................................... viii i. 前⾔ ............................................................................................................................ viii ii. 本书⾯向的读者 ............................................................................................................ viii iii. LFS 的⽬标架构 ............................................................................................................ ix iv. 阅读本书需要的背景知识 ................................................................................................. ix v. LFS 和标准 ..................................................................................................................... x vi. 本书选择软件包的逻辑 .................................................................................................... xi vii. 排版约定 .................................................................................................................... xvi viii. 本书结构 .................................................................................................................
    [Show full text]