Python Language ReferenceImplementation实现>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >> CPython >> Jython >> Python for .NET >> IronPython >> PyPy Lexical Analysis词法分析>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Line Structure行结构<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >> Logical Lines 逻辑行 >> Physical Lines 物理行 >> Comments 注释 >> # line comment >> Encoding Declarations 编码声明 >> # -*- coding: utf-8 -*- GNU Emacs >> # vim:fileencoding=<..> VIM >> BOM, byte order mark, \xef\xbb\xbf notepad >> Explicit Line Joining 显式行连接 >> \, backslash >> Implicit Line Joining 隐式行连接 >> parentheses, square brackets or curly braces expression (),[],{}表达式 >> Blank Lines 空行 >> contains only spaces, tabs, formfeeds, comments 仅包含空格,制表符,走纸,注释 >> Indentation 缩进 >> Whitespace between tokens Other tokens<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< 其他标识 >> NEWLINE, INDENT, DEDENT >> identifiers, keywords, literals, operators, delimiters Identifiers and Keywords<<<<<<<<<<<<<<<<<<<< 标识符和关键字 >> Lexical definition identifier ::= (letter|"_") (letter | digit | "_")* letter ::= lowercase | uppercase lowercase ::= "a"..."z" uppercase ::= "A"..."Z" digit ::= "0"..."9" >> Keywords 关键字 >> statement 语句关键词 break, continue if, elif, else for, in, while try, catch, finally, except, raise def, return lambda, yield >> attributes global >> definitions class, True, False, None >> directives print, exec, pass, del >> namespaces as, with import, from >> primary expression and, not, or is >> Reserved classes of identifiers 保留标识符 >> _*, store result of last evaluation in interactive interpreter >> __*__, system-defined names >> __*, class-private names Literals<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< 字面量 >> String Literals stringliteral ::= [stringprefix](shortstring | longstring) stringprefix ::= "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR" | "b" | "B" | "br" | "Br" | "bR" | "BR" shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"' longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""' shortstringitem ::= shortstringchar | escapeseq longstringitem ::= longstringchar | escapeseq shortstringchar ::= <any source character except "\" or newline or the quote> longstringchar ::= <any source character except "\"> escapeseq ::= "\" <any ASCII character> >> Concatenation 连接 >> +, """" >> Numeric Literals >> Integer and Long Integer Literals longinteger ::= integer ("l" | "L") integer ::= decimalinteger | octinteger | hexinteger | bininteger decimalinteger ::= nonzerodigit digit* | "0" octinteger ::= "0" ("o" | "O") octdigit+ | "0" octdigit+ hexinteger ::= "0" ("x" | "X") hexdigit+ bininteger ::= "0" ("b" | "B") bindigit+ nonzerodigit ::= "1"..."9" octdigit ::= "0"..."7" bindigit ::= "0" | "1" hexdigit ::= digit | "a"..."f" | "A"..."F" >> Floating Point Literals floatnumber ::= pointfloat | exponentfloat pointfloat ::= [intpart] fraction | intpart "." exponentfloat ::= (intpart | pointfloat) exponent intpart ::= digit+ fraction ::= "." digit+ exponent ::= ("e" | "E") ["+" | "-"] digit+ >> Imaginary Literals imagnumber ::= (floatnumber | intpart) ("j" | "J") Operators<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< 运算符 >> arithmetic + - * ** / // % >> comparion < > <= >= == != <> >> bitwise << >> & | ^ ~ Delimiters<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< 分隔符 () [] {} @ , : . ` ; = += -= *= /= //= %= &= |= ^= >>= <<= **= >> special meaning with others ' " # \ >> not used $ ?Data Model数据模型>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >> Objects, values and types<<<<<<<<<<<<<<<<<<< 对象,值,类型 >> object has type and value >> object has id >> is compares objects >> id() return object id >> value >> mutable dictionaries, lists >> immutable numbers, strings, tuples >> gc and close >> Standard Type Hierarchy<<<<<<<<<<<<<<<<<<<<< 标准类型体系 >> None None(truth value is false) >> NotImplemented NotImplemented >> Ellipsis Ellipsis(truth value is true) >> numbers.Number >> numbers.Integral >> Plain integers -2^31,2^31-1 >> Long integers unlimited >> Booleans True, False >> numbers.Real(float) >> numbers.Complex .real, .imag >> Sequences<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >> len() return number of items >> slicing [i:j] >> extend slicing [i:j:k] >> Immutable sequences >> Strings 8b,8b+ chr(), ord() >> Unicode 16b,32b, sys.maxunicode unichr(), ord() encode(), unicode() >> Tuples >> Mutable sequences >> del >> Lists >> Byte Arrays bytearray() >> Set types<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >> len() return number of items >> Sets mutable set set(), add() >> Frozen sets frozenset() >> Mappings<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >> del >> len() >> Dictionaries mutable >> Callable types<<<<<<<<<<<<<<<<<<<<<<<<<<<< >> UDF >> func_doc|__doc__ doc_string|None Writable >> func_name|__name__ name_string Writable >> __module__ module_name|None Writable >> func_defaults argument_tuple|None Writable >> func_code func_body_string Writable >> func_globals global_var_dic Read-only >> func_dict namespace Writable >> func_closure var_cells|None Read-only >> UDM, User-defined methods >> Read-only attributes >> im_self, im_func, im_class >> __doc__, __name__, __module__ >> Generator Functions >> yield, next() >> Build-in Functions >> len(), math.sin() >> Special read-only attributes __doc__, __name__, __module__, __self__ >> Built-in Methods >> list.append() >> Read-only attribute __self__ >> Class Types __new__(), __init__() >> Classic Classes __init__() >> Class Instances >> __call__() x.__call__(args) = x(args) >> Modules<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >> import >> Read-only attributes >> __dict__ m.x = m.__dic__["x"] >> Prefefined Attributes(writable) __name__, __doc__, __file__ >> Classes<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< __dict__, __name__, __module__, __bases__, __doc__ >> Class instances<<<<<<<<<<<<<<<<<<<<<<<<<<< __getattr__(), __setattr__(), __delattr__() __dict__, __class__ >> Files<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >> open open(), os.popen(), os.fdopen(), makefile() >> sys.stdin, sys.stdout, sys.stderr >> Interneal types<<<<<<<<<<<<<<<<<<<<<<<<<<< >> Code objects >> bytecode >> co_name, __co_argcount, co_nlocals, co_varnames, co_cellvars, co_freevars, co_code, co_consts, co_names, co_filenames, co_firstlineno, co_lnotab, co_stacksize co_flags >> *arguments, **keywords >> Frame objects >> Read-only attributes f_back, f_code, f_locals, f_globals, f_builtins, f_restricted >> Writable attributes f_trace, f_exc_type, f_exc_value, f_exc_traceback, f_lineno >> Traceback objects sys.exc_traceback, sys.exc_info() tb_next, tb_frame, tb_lineno, tb_lasti >> Slice objects slice(), [i:j], [i:j:k] start, stop, step slice.indices(self, length) >> Static methods objects staticmethod() >> Class method objects classmethod() New-Style and Classic Classes>>>>>>>>>>>>>>>>>>>>Special method names特殊方法名称>>>>>>>>>>>>>>>>>>>>>>> Basic customization<<<<<<<<<<<<<<<<<<<<<<<<<<<< >> object.__new__(cls[,...]) >> object.__init__(self[,...]) >> object.__del__(self) >> object.__repr__(self) >> object.__str__(self) >> object.__lt__(self, other) >> object.__le__(self, other) >> object.__eq__(self, other) >> object.__ne__(self, other) >> object.__gt__(self, other) >> object.__ge__(self, other) >> object.__cmp__(self, other) >> object.__rcmp__(self, other) >> object.__hash__(self) >> object.__nonzero__(self) >> object.__unicode__(self) Customizing attribute access自定义属性访问<<<<<<<<<<<< >> object.__getattr__(self, name) >> object.__setattr__(self, name, value) >> object.__delattr__(self, name) >> more for new-style classes >> object.__getattribute__(self, name) >> implementing descriptors >> object.__get__(self, instance, owner) >> object.__set__(self, instance, value) >> object.__delete__(self, instance) >> invoking descriptors >> Direct Call x.__get__(a) >> Instance Binding type(a).__dict__['x'].__get__(a. type(a)) >> Class Binding A.__dict__['x'],__get__(None, A) >> Super Binding A.__dict__['m'].__get__(obj, obj.__class__) >> __slots__ Customizing class creation自定义类创建<<<<<<<<<<<<<<< >> __metaclass__ Customizaing instance and subclass checks<<<<<< 自定义实例和子类检查 >> class.__instancecheck__(self, instance) >> class.__subclasscheck__(self, instance) Emulating callable objects<<<<<<<<<<<<<<<<<<<<< >> object.__call__(self[,args...]) Emulating container types<<<<<<<<<<<<<<<<<<<<<< >> mappings keys(), values(), items(), has_key(), get(), clear() setdefault(), iterkeys(), itervalues(), iteritems() pop(), popitem(), copy(), update() >> UserDict.DictMixin __getitem__(), __setitem__(), __delitem__(), keys() >> mutable sequences append(), count(), index(), extend(), insert(), pop(), remove(), reverse(), sort() >> sequences __add__(), __radd__(), __iadd__(), __mul__(), __rmul__(), __imul__() >> mappings and sequences __constains__() >> object.__len__(self) >> object.__getitem__(self, key) >> object.__setitem__(self, key, value) >> object.__delitem__(self, key) >> object.__iter__(self) >> object.__reversed__(self) >> object.__contains__(self, item) Additional methods for emulation of sequence types<<<<<<< >> object.__getslice__(self, i, j) >> object.__setslice__(self, i, j, sequence) >> object.__delslice__(self, i, j) Emulating numeric types<<<<<<<<<<<<<<<<<<<<<<<< >> object.__add__(self, other) >> object.__sub__(self, other) >> object.__mul__(self, other) >> object.__floordiv__(self, other) >> object.__mod__(self, other) >> object.__divmod__(self, other) >> object.__pow__(self, other[,module]) >> object.__lshift__(self, other) >> object.__rshift__(self, other) >> object.__and__(self, other) >> object.__xor__(self, other) >> object.__or__(self, other) >> object.__div__(self, other) >> object.__truediv__(self, other) >> object.__radd__(self, other) >> object.__rsub__(self, other) >> object.__rmul__(self, other)¶ >> object.__rdiv__(self, other) >> object.__rtruediv__(self, other) >> object.__rfloordiv__(self, other) >> object.__rmod__(self, other) >> object.__rdivmod__(self, other) >> object.__rpow__(self, other) >> object.__rlshift__(self, other) >> object.__rrshift__(self, other) >> object.__rand__(self, other) >> object.__rxor__(self, other) >> object.__ror__(self, other) >> object.__iadd__(self, other) >> object.__isub__(self, other) >> object.__imul__(self, other) >> object.__idiv__(self, other) >> object.__itruediv__(self, other) >> object.__ifloordiv__(self, other) >> object.__imod__(self, other)¶ >> object.__ipow__(self, other[, modulo]) >> object.__ilshift__(self, other) >> object.__irshift__(self, other) >> object.__iand__(self, other) >> object.__ixor__(self, other) >> object.__ior__(self, other) >> object.__neg__(self) >> object.__pos__(self)¶ >> object.__abs__(self) >> object.__invert__(self) >> object.__complex__(self)¶ >> object.__int__(self) >> object.__long__(self) >> object.__float__(self) >> object.__oct__(self) >> object.__hex__(self) >> object.__index__(self) >> object.__coerce__(self, other) Coercion rules<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< With statement context managers<<<<<<<<<<<<<<<< >> object.__enter__(self) >> object.__exit__(self, exc_type, exc_value, traceback) Execution Model执行模型>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Naming and binding<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >> Names >> block execfile(), eval(), exec, input() >> execution frame >> scope Exceptions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >> try..except >> raise >> finallyExpressions表达式>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> name ::= othername Arithmetic conversions<<<<<<<<<<<<<<<<<<<<<<<<< Atoms<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< atom ::= identifier | literal | enclosure enclosure ::= parenth_form | list_display | generator_expression | dict_display | set_display | string_conversion | yield_atom >> identifers >> literals literal ::= stringliteral | integer | longinteger | floatnumber | imagnumber >> parenthesized forms >> parenth_form ::= "(" [expression_list] ")" >> list displays list_display ::= "[" [expression_list | list_comprehension] "]" list_comprehension ::= expression list_for list_for ::= "for" target_list "in" old_expression_list [list_iter] old_expression_list ::= old_expression [("," old_expression)+ [","]] old_expression ::= or_test | old_lambda_form list_iter ::= list_for | list_if list_if ::= "if" old_expression [list_iter] >> displays for sets and dictionaries comprehension ::= expression comp_for comp_for ::= "for" target_list "in" or_test [comp_iter] comp_iter ::= comp_for | comp_if comp_if ::= "if" expression_nocond [comp_iter] >> generator expressions generator_expression ::= "(" expression comp_for ")" >> dictionary displays dict_display ::= "{" [key_datum_list | dict_comprehension] "}" key_datum_list ::= key_datum ("," key_datum)* [","] key_datum ::= expression ":" expression dict_comprehension ::= expression ":" expression comp_for >> set displays set_display ::= "{" (expression_list | comprehension) "}" >> string conversions string_conversion ::= "`" expression_list "`" >> yield expressions yield_atom ::= "(" yield_expression ")" yield_expression ::= "yield" [expression_list] >> generator-iterator methods >> generator.next() >> generator.send(value) >> generator.throw(type[,value[,traceback]]) >> generator.close() Primaries<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< primary ::= atom | attributeref | subscription | slicing | call >> attribute references attributeref ::= primary "." identifier >> subscriptions subscription ::= primary "[" expression_list "]" >> slicings slicing ::= simple_slicing | extended_slicing simple_slicing ::= primary "[" short_slice "]" extended_slicing ::= primary "[" slice_list "]" slice_list ::= slice_item ("," slice_item)* [","] slice_item ::= expression | proper_slice | ellipsis proper_slice ::= short_slice | long_slice short_slice ::= [lower_bound] ":" [upper_bound] long_slice ::= short_slice ":" [stride] lower_bound ::= expression upper_bound ::= expression stride ::= expression ellipsis ::= "..." >> Calls call ::= primary "(" [argument_list [","] | expression genexpr_for] ")" argument_list ::= positional_arguments ["," keyword_arguments] ["," "*" expression] ["," keyword_arguments] ["," "**" expression] | keyword_arguments ["," "*" expression] ["," "**" expression] | "*" expression ["," "*" expression] ["," "**" expression] | "**" expression positional_arguments ::= expression ("," expression)* keyword_arguments ::= keyword_item ("," keyword_item)* keyword_item ::= identifier "=" expression >> power operator power ::= primary ["**" u_expr] >> unary arithmetic and bitwise operations u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr >> binary arithmetic operations m_expr ::= u_expr | m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr | m_expr "%" u_expr a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr >> shifting operations shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr >> binary bitwise operations and_expr ::= shift_expr | and_expr "&" shift_expr xor_expr ::= and_expr | xor_expr "^" and_expr or_expr ::= xor_expr | or_expr "|" xor_expr >> comparisons comparison ::= or_expr ( comp_operator or_expr )* comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" | "!=" | "is" ["not"] | ["not"] "in" >> boolean operations or_test ::= and_test | or_test "or" and_test and_test ::= not_test | and_test "and" not_test not_test ::= comparison | "not" not_test >> conditional expressions conditional_expression ::= or_test ["if" or_test "else" expression] expression ::= conditional_expression | lambda_form >> lambdas lambda_form ::= "lambda" [parameter_list]: expression old_lambda_form ::= "lambda" [parameter_list]: old_expression >> expression lists expression_list ::= expression ( "," expression )* [","] >> evaluation order expr1, expr2, expr3, expr4 (expr1, expr2, expr3, expr4) {expr1: expr2, expr3: expr4} expr1 + expr2 * (expr3 - expr4) expr1(expr2, expr3, *expr4, **expr5) expr3, expr4 = expr1, expr2 Simple statements简单语句>>>>>>>>>>>>>>>>>>>>>>>>>>>> simple_stmt ::= expression_stmt | assert_stmt | assignment_stmt | augmented_assignment_stmt | pass_stmt | del_stmt | print_stmt | return_stmt | yield_stmt | raise_stmt | break_stmt | continue_stmt | import_stmt | global_stmt | exec_stmt expression statements<<<<<<<<<<<<<<<<<<<<<<<<<< expression_stmt ::= expression_list assignment statements<<<<<<<<<<<<<<<<<<<<<<<<<< assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression) target_list ::= target ("," target)* [","] target ::= identifier | "(" target_list ")" | "[" target_list "]" | attributeref | subscription | slicing >> augmented assignment statements augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression) augtarget ::= identifier | attributeref | subscription | slicing augop ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**=" | ">>=" | "<<=" | "&=" | "^=" | "|=" assert statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< assert_stmt ::= "assert" expression ["," expression] pass statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< pass_stmt ::= "pass" del statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< del_stmt ::= "del" target_list print statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< print_stmt ::= "print" ([expression ("," expression)* [","]] | ">>" expression [("," expression)+ [","]]) return statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< return_stmt ::= "return" [expression_list] yield statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< yield_stmt ::= yield_expression raise statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< raise_stmt ::= "raise" [expression ["," expression ["," expression]]] break statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< break_stmt ::= "break" continue statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<< continue_stmt ::= "continue" import statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< import_stmt ::= "import" module ["as" name] ( "," module ["as" name] )* | "from" relative_module "import" identifier ["as" name] ( "," identifier ["as" name] )* | "from" relative_module "import" "(" identifier ["as" name] ( "," identifier ["as" name] )* [","] ")" | "from" module "import" "*" module ::= (identifier ".")* identifier relative_module ::= "."* module | "."+ name ::= identifier future statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< future_statement ::= "from" "__future__" "import" feature ["as" name] ("," feature ["as" name])* | "from" "__future__" "import" "(" feature ["as" name] ("," feature ["as" name])* [","] ")" feature ::= identifier name ::= identifier global statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< global_stmt ::= "global" identifier ("," identifier)* exec statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< exec_stmt ::= "exec" or_expr ["in" expression ["," expression]]Compound statements复合语句>>>>>>>>>>>>>>>>>>>>>>>>>> compound_stmt ::= if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT statement ::= stmt_list NEWLINE | compound_stmt stmt_list ::= simple_stmt (";" simple_stmt)* [";"] if statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< if_stmt ::= "if" expression ":" suite ( "elif" expression ":" suite )* ["else" ":" suite] while statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< while_stmt ::= "while" expression ":" suite ["else" ":" suite] for statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] try statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< try_stmt ::= try1_stmt | try2_stmt try1_stmt ::= "try" ":" suite ("except" [expression [("as" | ",") target]] ":" suite)+ ["else" ":" suite] ["finally" ":" suite] try2_stmt ::= "try" ":" suite "finally" ":" suite with statement<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< with_stmt ::= "with" with_item ("," with_item)* ":" suite with_item ::= expression ["as" target] function definitions<<<<<<<<<<<<<<<<<<<<<<<<<<< decorated ::= decorators (classdef | funcdef) decorators ::= decorator+ decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite dotted_name ::= identifier ("." identifier)* parameter_list ::= (defparameter ",")* ( "*" identifier [, "**" identifier] | "**" identifier | defparameter [","] ) defparameter ::= parameter ["=" expression] sublist ::= parameter ("," parameter)* [","] parameter ::= identifier | "(" sublist ")" funcname ::= identifier class definitions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< classdef ::= "class" classname [inheritance] ":" suite inheritance ::= "(" [expression_list] ")" classname ::= identifierTop-level components顶层组件>>>>>>>>>>>>>>>>>>>>>>>>> complete python programs<<<<<<<<<<<<<<<<<<<<<<< >> sys >> __builtin__ >> __main__ File Input<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< file_input ::= (NEWLINE | statement)* Interactive Input<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< interactive_input ::= [stmt_list] NEWLINE | compound_stmt NEWLINE Expression Input<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< eval_input ::= expression_list NEWLINE* input_input ::= expression_list NEWLINE