Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(4)

Delta Between Two Patch Sets: Doc/reference/datamodel.rst

Issue 25958: Implicit ABCs have no means of "anti-registration"
Left Patch Set: Created 4 years, 1 month ago
Right Patch Set: Created 3 years, 6 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Doc/library/collections.abc.rst ('k') | Lib/_collections_abc.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 1
2 .. _datamodel: 2 .. _datamodel:
3 3
4 ********** 4 **********
5 Data model 5 Data model
6 ********** 6 **********
7 7
8 8
9 .. _objects: 9 .. _objects:
10 10
(...skipping 436 matching lines...) Expand 10 before | Expand all | Expand 10 after
447 447
448 A user-defined function object is created by a function definition (see 448 A user-defined function object is created by a function definition (see
449 section :ref:`function`). It should be called with an argument list 449 section :ref:`function`). It should be called with an argument list
450 containing the same number of items as the function's formal parameter 450 containing the same number of items as the function's formal parameter
451 list. 451 list.
452 452
453 Special attributes: 453 Special attributes:
454 454
455 .. tabularcolumns:: |l|L|l| 455 .. tabularcolumns:: |l|L|l|
456 456
457 .. index::
458 single: __doc__ (function attribute)
459 single: __name__ (function attribute)
460 single: __module__ (function attribute)
461 single: __dict__ (function attribute)
462 single: __defaults__ (function attribute)
463 single: __closure__ (function attribute)
464 single: __code__ (function attribute)
465 single: __globals__ (function attribute)
466 single: __annotations__ (function attribute)
467 single: __kwdefaults__ (function attribute)
468 pair: global; namespace
469
457 +-------------------------+-------------------------------+-----------+ 470 +-------------------------+-------------------------------+-----------+
458 | Attribute | Meaning | | 471 | Attribute | Meaning | |
459 +=========================+===============================+===========+ 472 +=========================+===============================+===========+
460 | :attr:`__doc__` | The function's documentation | Writable | 473 | :attr:`__doc__` | The function's documentation | Writable |
461 | | string, or ``None`` if | | 474 | | string, or ``None`` if | |
462 | | unavailable; not inherited by | | 475 | | unavailable; not inherited by | |
463 | | subclasses | | 476 | | subclasses | |
464 +-------------------------+-------------------------------+-----------+ 477 +-------------------------+-------------------------------+-----------+
465 | :attr:`__name__` | The function's name | Writable | 478 | :attr:`~definition.\ | The function's name | Writable |
479 | __name__` | | |
466 +-------------------------+-------------------------------+-----------+ 480 +-------------------------+-------------------------------+-----------+
467 | :attr:`__qualname__` | The function's | Writable | 481 | :attr:`~definition.\ | The function's | Writable |
468 | | :term:`qualified name` | | 482 | __qualname__` | :term:`qualified name` | |
469 | | | | 483 | | | |
470 | | .. versionadded:: 3.3 | | 484 | | .. versionadded:: 3.3 | |
471 +-------------------------+-------------------------------+-----------+ 485 +-------------------------+-------------------------------+-----------+
472 | :attr:`__module__` | The name of the module the | Writable | 486 | :attr:`__module__` | The name of the module the | Writable |
473 | | function was defined in, or | | 487 | | function was defined in, or | |
474 | | ``None`` if unavailable. | | 488 | | ``None`` if unavailable. | |
475 +-------------------------+-------------------------------+-----------+ 489 +-------------------------+-------------------------------+-----------+
476 | :attr:`__defaults__` | A tuple containing default | Writable | 490 | :attr:`__defaults__` | A tuple containing default | Writable |
477 | | argument values for those | | 491 | | argument values for those | |
478 | | arguments that have defaults, | | 492 | | arguments that have defaults, | |
479 | | or ``None`` if no arguments | | 493 | | or ``None`` if no arguments | |
480 | | have a default value | | 494 | | have a default value | |
481 +-------------------------+-------------------------------+-----------+ 495 +-------------------------+-------------------------------+-----------+
482 | :attr:`__code__` | The code object representing | Writable | 496 | :attr:`__code__` | The code object representing | Writable |
483 | | the compiled function body. | | 497 | | the compiled function body. | |
484 +-------------------------+-------------------------------+-----------+ 498 +-------------------------+-------------------------------+-----------+
485 | :attr:`__globals__` | A reference to the dictionary | Read-only | 499 | :attr:`__globals__` | A reference to the dictionary | Read-only |
486 | | that holds the function's | | 500 | | that holds the function's | |
487 | | global variables --- the | | 501 | | global variables --- the | |
488 | | global namespace of the | | 502 | | global namespace of the | |
489 | | module in which the function | | 503 | | module in which the function | |
490 | | was defined. | | 504 | | was defined. | |
491 +-------------------------+-------------------------------+-----------+ 505 +-------------------------+-------------------------------+-----------+
492 | :attr:`__dict__` | The namespace supporting | Writable | 506 | :attr:`~object.__dict__`| The namespace supporting | Writable |
493 | | arbitrary function | | 507 | | arbitrary function | |
494 | | attributes. | | 508 | | attributes. | |
495 +-------------------------+-------------------------------+-----------+ 509 +-------------------------+-------------------------------+-----------+
496 | :attr:`__closure__` | ``None`` or a tuple of cells | Read-only | 510 | :attr:`__closure__` | ``None`` or a tuple of cells | Read-only |
497 | | that contain bindings for the | | 511 | | that contain bindings for the | |
498 | | function's free variables. | | 512 | | function's free variables. | |
499 +-------------------------+-------------------------------+-----------+ 513 +-------------------------+-------------------------------+-----------+
500 | :attr:`__annotations__` | A dict containing annotations | Writable | 514 | :attr:`__annotations__` | A dict containing annotations | Writable |
501 | | of parameters. The keys of | | 515 | | of parameters. The keys of | |
502 | | the dict are the parameter | | 516 | | the dict are the parameter | |
503 | | names, and ``'return'`` for | | 517 | | names, and ``'return'`` for | |
504 | | the return annotation, if | | 518 | | the return annotation, if | |
505 | | provided. | | 519 | | provided. | |
506 +-------------------------+-------------------------------+-----------+ 520 +-------------------------+-------------------------------+-----------+
507 | :attr:`__kwdefaults__` | A dict containing defaults | Writable | 521 | :attr:`__kwdefaults__` | A dict containing defaults | Writable |
508 | | for keyword-only parameters. | | 522 | | for keyword-only parameters. | |
509 +-------------------------+-------------------------------+-----------+ 523 +-------------------------+-------------------------------+-----------+
510 524
511 Most of the attributes labelled "Writable" check the type of the assigned value. 525 Most of the attributes labelled "Writable" check the type of the assigned value.
512 526
513 Function objects also support getting and setting arbitrary attributes, wh ich 527 Function objects also support getting and setting arbitrary attributes, wh ich
514 can be used, for example, to attach metadata to functions. Regular attrib ute 528 can be used, for example, to attach metadata to functions. Regular attrib ute
515 dot-notation is used to get and set such attributes. *Note that the curren t 529 dot-notation is used to get and set such attributes. *Note that the curren t
516 implementation only supports function attributes on user-defined functions . 530 implementation only supports function attributes on user-defined functions .
517 Function attributes on built-in functions may be supported in the future.* 531 Function attributes on built-in functions may be supported in the future.*
518 532
519 Additional information about a function's definition can be retrieved from its 533 Additional information about a function's definition can be retrieved from its
520 code object; see the description of internal types below. 534 code object; see the description of internal types below.
521 535
522 .. index::
523 single: __doc__ (function attribute)
524 single: __name__ (function attribute)
525 single: __module__ (function attribute)
526 single: __dict__ (function attribute)
527 single: __defaults__ (function attribute)
528 single: __closure__ (function attribute)
529 single: __code__ (function attribute)
530 single: __globals__ (function attribute)
531 single: __annotations__ (function attribute)
532 single: __kwdefaults__ (function attribute)
533 pair: global; namespace
534
535 Instance methods 536 Instance methods
536 .. index:: 537 .. index::
537 object: method 538 object: method
538 object: user-defined method 539 object: user-defined method
539 pair: user-defined; method 540 pair: user-defined; method
540 541
541 An instance method object combines a class, a class instance and any 542 An instance method object combines a class, a class instance and any
542 callable object (normally a user-defined function). 543 callable object (normally a user-defined function).
543 544
544 .. index:: 545 .. index::
545 single: __func__ (method attribute) 546 single: __func__ (method attribute)
546 single: __self__ (method attribute) 547 single: __self__ (method attribute)
547 single: __doc__ (method attribute) 548 single: __doc__ (method attribute)
548 single: __name__ (method attribute) 549 single: __name__ (method attribute)
549 single: __module__ (method attribute) 550 single: __module__ (method attribute)
550 551
551 Special read-only attributes: :attr:`__self__` is the class instance objec t, 552 Special read-only attributes: :attr:`__self__` is the class instance objec t,
552 :attr:`__func__` is the function object; :attr:`__doc__` is the method's 553 :attr:`__func__` is the function object; :attr:`__doc__` is the method's
553 documentation (same as ``__func__.__doc__``); :attr:`__name__` is the 554 documentation (same as ``__func__.__doc__``); :attr:`~definition.__name__` is the
554 method name (same as ``__func__.__name__``); :attr:`__module__` is the 555 method name (same as ``__func__.__name__``); :attr:`__module__` is the
555 name of the module the method was defined in, or ``None`` if unavailable. 556 name of the module the method was defined in, or ``None`` if unavailable.
556 557
557 Methods also support accessing (but not setting) the arbitrary function 558 Methods also support accessing (but not setting) the arbitrary function
558 attributes on the underlying function object. 559 attributes on the underlying function object.
559 560
560 User-defined method objects may be created when getting an attribute of a 561 User-defined method objects may be created when getting an attribute of a
561 class (perhaps via an instance of that class), if that attribute is a 562 class (perhaps via an instance of that class), if that attribute is a
562 user-defined function object or a class method object. 563 user-defined function object or a class method object.
563 564
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
630 .. index:: 631 .. index::
631 object: built-in function 632 object: built-in function
632 object: function 633 object: function
633 pair: C; language 634 pair: C; language
634 635
635 A built-in function object is a wrapper around a C function. Examples of 636 A built-in function object is a wrapper around a C function. Examples of
636 built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a 637 built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a
637 standard built-in module). The number and type of the arguments are 638 standard built-in module). The number and type of the arguments are
638 determined by the C function. Special read-only attributes: 639 determined by the C function. Special read-only attributes:
639 :attr:`__doc__` is the function's documentation string, or ``None`` if 640 :attr:`__doc__` is the function's documentation string, or ``None`` if
640 unavailable; :attr:`__name__` is the function's name; :attr:`__self__` is 641 unavailable; :attr:`~definition.__name__` is the function's name; :attr:`_ _self__` is
641 set to ``None`` (but see the next item); :attr:`__module__` is the name of 642 set to ``None`` (but see the next item); :attr:`__module__` is the name of
642 the module the function was defined in or ``None`` if unavailable. 643 the module the function was defined in or ``None`` if unavailable.
643 644
644 Built-in methods 645 Built-in methods
645 .. index:: 646 .. index::
646 object: built-in method 647 object: built-in method
647 object: method 648 object: method
648 pair: built-in; method 649 pair: built-in; method
649 650
650 This is really a different disguise of a built-in function, this time cont aining 651 This is really a different disguise of a built-in function, this time cont aining
(...skipping 29 matching lines...) Expand all
680 translated to lookups in this dictionary, e.g., ``m.x`` is equivalent to 681 translated to lookups in this dictionary, e.g., ``m.x`` is equivalent to
681 ``m.__dict__["x"]``. A module object does not contain the code object used 682 ``m.__dict__["x"]``. A module object does not contain the code object used
682 to initialize the module (since it isn't needed once the initialization is 683 to initialize the module (since it isn't needed once the initialization is
683 done). 684 done).
684 685
685 Attribute assignment updates the module's namespace dictionary, e.g., 686 Attribute assignment updates the module's namespace dictionary, e.g.,
686 ``m.x = 1`` is equivalent to ``m.__dict__["x"] = 1``. 687 ``m.x = 1`` is equivalent to ``m.__dict__["x"] = 1``.
687 688
688 .. index:: single: __dict__ (module attribute) 689 .. index:: single: __dict__ (module attribute)
689 690
690 Special read-only attribute: :attr:`__dict__` is the module's namespace as a 691 Special read-only attribute: :attr:`~object.__dict__` is the module's namespa ce as a
691 dictionary object. 692 dictionary object.
692 693
693 .. impl-detail:: 694 .. impl-detail::
694 695
695 Because of the way CPython clears module dictionaries, the module 696 Because of the way CPython clears module dictionaries, the module
696 dictionary will be cleared when the module falls out of scope even if the 697 dictionary will be cleared when the module falls out of scope even if the
697 dictionary still has live references. To avoid this, copy the dictionary 698 dictionary still has live references. To avoid this, copy the dictionary
698 or keep the module around while using its dictionary directly. 699 or keep the module around while using its dictionary directly.
699 700
700 .. index:: 701 .. index::
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
736 single: container 737 single: container
737 object: dictionary 738 object: dictionary
738 pair: class; attribute 739 pair: class; attribute
739 740
740 When a class attribute reference (for class :class:`C`, say) would yield a 741 When a class attribute reference (for class :class:`C`, say) would yield a
741 class method object, it is transformed into an instance method object whose 742 class method object, it is transformed into an instance method object whose
742 :attr:`__self__` attributes is :class:`C`. When it would yield a static 743 :attr:`__self__` attributes is :class:`C`. When it would yield a static
743 method object, it is transformed into the object wrapped by the static method 744 method object, it is transformed into the object wrapped by the static method
744 object. See section :ref:`descriptors` for another way in which attributes 745 object. See section :ref:`descriptors` for another way in which attributes
745 retrieved from a class may differ from those actually contained in its 746 retrieved from a class may differ from those actually contained in its
746 :attr:`__dict__`. 747 :attr:`~object.__dict__`.
747 748
748 .. index:: triple: class; attribute; assignment 749 .. index:: triple: class; attribute; assignment
749 750
750 Class attribute assignments update the class's dictionary, never the dictiona ry 751 Class attribute assignments update the class's dictionary, never the dictiona ry
751 of a base class. 752 of a base class.
752 753
753 .. index:: pair: class object; call 754 .. index:: pair: class object; call
754 755
755 A class object can be called (see above) to yield a class instance (see below ). 756 A class object can be called (see above) to yield a class instance (see below ).
756 757
757 .. index:: 758 .. index::
758 single: __name__ (class attribute) 759 single: __name__ (class attribute)
759 single: __module__ (class attribute) 760 single: __module__ (class attribute)
760 single: __dict__ (class attribute) 761 single: __dict__ (class attribute)
761 single: __bases__ (class attribute) 762 single: __bases__ (class attribute)
762 single: __doc__ (class attribute) 763 single: __doc__ (class attribute)
763 764
764 Special attributes: :attr:`__name__` is the class name; :attr:`__module__` is 765 Special attributes: :attr:`~definition.__name__` is the class name; :attr:`__ module__` is
765 the module name in which the class was defined; :attr:`__dict__` is the 766 the module name in which the class was defined; :attr:`~object.__dict__` is t he
766 dictionary containing the class's namespace; :attr:`~class.__bases__` is a 767 dictionary containing the class's namespace; :attr:`~class.__bases__` is a
767 tuple (possibly empty or a singleton) containing the base classes, in the 768 tuple (possibly empty or a singleton) containing the base classes, in the
768 order of their occurrence in the base class list; :attr:`__doc__` is the 769 order of their occurrence in the base class list; :attr:`__doc__` is the
769 class's documentation string, or None if undefined. 770 class's documentation string, or None if undefined.
770 771
771 Class instances 772 Class instances
772 .. index:: 773 .. index::
773 object: class instance 774 object: class instance
774 object: instance 775 object: instance
775 pair: class; instance 776 pair: class; instance
776 pair: class instance; attribute 777 pair: class instance; attribute
777 778
778 A class instance is created by calling a class object (see above). A class 779 A class instance is created by calling a class object (see above). A class
779 instance has a namespace implemented as a dictionary which is the first place 780 instance has a namespace implemented as a dictionary which is the first place
780 in which attribute references are searched. When an attribute is not found 781 in which attribute references are searched. When an attribute is not found
781 there, and the instance's class has an attribute by that name, the search 782 there, and the instance's class has an attribute by that name, the search
782 continues with the class attributes. If a class attribute is found that is a 783 continues with the class attributes. If a class attribute is found that is a
783 user-defined function object, it is transformed into an instance method 784 user-defined function object, it is transformed into an instance method
784 object whose :attr:`__self__` attribute is the instance. Static method and 785 object whose :attr:`__self__` attribute is the instance. Static method and
785 class method objects are also transformed; see above under "Classes". See 786 class method objects are also transformed; see above under "Classes". See
786 section :ref:`descriptors` for another way in which attributes of a class 787 section :ref:`descriptors` for another way in which attributes of a class
787 retrieved via its instances may differ from the objects actually stored in 788 retrieved via its instances may differ from the objects actually stored in
788 the class's :attr:`__dict__`. If no class attribute is found, and the 789 the class's :attr:`~object.__dict__`. If no class attribute is found, and th e
789 object's class has a :meth:`__getattr__` method, that is called to satisfy 790 object's class has a :meth:`__getattr__` method, that is called to satisfy
790 the lookup. 791 the lookup.
791 792
792 .. index:: triple: class instance; attribute; assignment 793 .. index:: triple: class instance; attribute; assignment
793 794
794 Attribute assignments and deletions update the instance's dictionary, never a 795 Attribute assignments and deletions update the instance's dictionary, never a
795 class's dictionary. If the class has a :meth:`__setattr__` or 796 class's dictionary. If the class has a :meth:`__setattr__` or
796 :meth:`__delattr__` method, this is called instead of updating the instance 797 :meth:`__delattr__` method, this is called instead of updating the instance
797 dictionary directly. 798 dictionary directly.
798 799
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after
839 840
840 Internal types 841 Internal types
841 .. index:: 842 .. index::
842 single: internal type 843 single: internal type
843 single: types, internal 844 single: types, internal
844 845
845 A few types used internally by the interpreter are exposed to the user. Their 846 A few types used internally by the interpreter are exposed to the user. Their
846 definitions may change with future versions of the interpreter, but they are 847 definitions may change with future versions of the interpreter, but they are
847 mentioned here for completeness. 848 mentioned here for completeness.
848 849
850 .. index:: bytecode, object; code, code object
851
849 Code objects 852 Code objects
850 .. index::
851 single: bytecode
852 object: code
853
854 Code objects represent *byte-compiled* executable Python code, or :term:`b ytecode`. 853 Code objects represent *byte-compiled* executable Python code, or :term:`b ytecode`.
855 The difference between a code object and a function object is that the fun ction 854 The difference between a code object and a function object is that the fun ction
856 object contains an explicit reference to the function's globals (the modul e in 855 object contains an explicit reference to the function's globals (the modul e in
857 which it was defined), while a code object contains no context; also the d efault 856 which it was defined), while a code object contains no context; also the d efault
858 argument values are stored in the function object, not in the code object 857 argument values are stored in the function object, not in the code object
859 (because they represent values calculated at run-time). Unlike function 858 (because they represent values calculated at run-time). Unlike function
860 objects, code objects are immutable and contain no references (directly or 859 objects, code objects are immutable and contain no references (directly or
861 indirectly) to mutable objects. 860 indirectly) to mutable objects.
862 861
863 .. index:: 862 .. index::
(...skipping 369 matching lines...) Expand 10 before | Expand all | Expand 10 after
1233 object. This should return a ``bytes`` object. 1232 object. This should return a ``bytes`` object.
1234 1233
1235 .. index:: 1234 .. index::
1236 single: string; __format__() (object method) 1235 single: string; __format__() (object method)
1237 pair: string; conversion 1236 pair: string; conversion
1238 builtin: print 1237 builtin: print
1239 1238
1240 1239
1241 .. method:: object.__format__(self, format_spec) 1240 .. method:: object.__format__(self, format_spec)
1242 1241
1243 Called by the :func:`format` built-in function (and by extension, the 1242 Called by the :func:`format` built-in function,
1244 :meth:`str.format` method of class :class:`str`) to produce a "formatted" 1243 and by extension, evaluation of :ref:`formatted string literals
1244 <f-strings>` and the :meth:`str.format` method, to produce a "formatted"
1245 string representation of an object. The ``format_spec`` argument is 1245 string representation of an object. The ``format_spec`` argument is
1246 a string that contains a description of the formatting options desired. 1246 a string that contains a description of the formatting options desired.
1247 The interpretation of the ``format_spec`` argument is up to the type 1247 The interpretation of the ``format_spec`` argument is up to the type
1248 implementing :meth:`__format__`, however most classes will either 1248 implementing :meth:`__format__`, however most classes will either
1249 delegate formatting to one of the built-in types, or use a similar 1249 delegate formatting to one of the built-in types, or use a similar
1250 formatting option syntax. 1250 formatting option syntax.
1251 1251
1252 See :ref:`formatspec` for a description of the standard formatting syntax. 1252 See :ref:`formatspec` for a description of the standard formatting syntax.
1253 1253
1254 The return value must be a string object. 1254 The return value must be a string object.
(...skipping 212 matching lines...) Expand 10 before | Expand all | Expand 10 after
1467 .. _descriptors: 1467 .. _descriptors:
1468 1468
1469 Implementing Descriptors 1469 Implementing Descriptors
1470 ^^^^^^^^^^^^^^^^^^^^^^^^ 1470 ^^^^^^^^^^^^^^^^^^^^^^^^
1471 1471
1472 The following methods only apply when an instance of the class containing the 1472 The following methods only apply when an instance of the class containing the
1473 method (a so-called *descriptor* class) appears in an *owner* class (the 1473 method (a so-called *descriptor* class) appears in an *owner* class (the
1474 descriptor must be in either the owner's class dictionary or in the class 1474 descriptor must be in either the owner's class dictionary or in the class
1475 dictionary for one of its parents). In the examples below, "the attribute" 1475 dictionary for one of its parents). In the examples below, "the attribute"
1476 refers to the attribute whose name is the key of the property in the owner 1476 refers to the attribute whose name is the key of the property in the owner
1477 class' :attr:`__dict__`. 1477 class' :attr:`~object.__dict__`.
1478 1478
1479 1479
1480 .. method:: object.__get__(self, instance, owner) 1480 .. method:: object.__get__(self, instance, owner)
1481 1481
1482 Called to get the attribute of the owner class (class attribute access) or of an 1482 Called to get the attribute of the owner class (class attribute access) or of an
1483 instance of that class (instance attribute access). *owner* is always the own er 1483 instance of that class (instance attribute access). *owner* is always the own er
1484 class, while *instance* is the instance that the attribute was accessed throu gh, 1484 class, while *instance* is the instance that the attribute was accessed throu gh,
1485 or ``None`` when the attribute is accessed through the *owner*. This method 1485 or ``None`` when the attribute is accessed through the *owner*. This method
1486 should return the (computed) attribute value or raise an :exc:`AttributeError ` 1486 should return the (computed) attribute value or raise an :exc:`AttributeError `
1487 exception. 1487 exception.
1488 1488
1489 1489
1490 .. method:: object.__set__(self, instance, value) 1490 .. method:: object.__set__(self, instance, value)
1491 1491
1492 Called to set the attribute on an instance *instance* of the owner class to a 1492 Called to set the attribute on an instance *instance* of the owner class to a
1493 new value, *value*. 1493 new value, *value*.
1494 1494
1495 1495
1496 .. method:: object.__delete__(self, instance) 1496 .. method:: object.__delete__(self, instance)
1497 1497
1498 Called to delete the attribute on an instance *instance* of the owner class. 1498 Called to delete the attribute on an instance *instance* of the owner class.
1499
1500
1501 .. method:: object.__set_name__(self, owner, name)
1502
1503 Called at the time the owning class *owner* is created. The
1504 descriptor has been assigned to *name*.
1505
1506 .. versionadded:: 3.6
1499 1507
1500 1508
1501 The attribute :attr:`__objclass__` is interpreted by the :mod:`inspect` module 1509 The attribute :attr:`__objclass__` is interpreted by the :mod:`inspect` module
1502 as specifying the class where this object was defined (setting this 1510 as specifying the class where this object was defined (setting this
1503 appropriately can assist in runtime introspection of dynamic class attributes). 1511 appropriately can assist in runtime introspection of dynamic class attributes).
1504 For callables, it may indicate that an instance of the given type (or a 1512 For callables, it may indicate that an instance of the given type (or a
1505 subclass) is expected or required as the first positional argument (for example, 1513 subclass) is expected or required as the first positional argument (for example,
1506 CPython sets this attribute for unbound methods that are implemented in C). 1514 CPython sets this attribute for unbound methods that are implemented in C).
1507 1515
1508 1516
(...skipping 119 matching lines...) Expand 10 before | Expand all | Expand 10 after
1628 * Nonempty *__slots__* does not work for classes derived from "variable-length" 1636 * Nonempty *__slots__* does not work for classes derived from "variable-length"
1629 built-in types such as :class:`int`, :class:`bytes` and :class:`tuple`. 1637 built-in types such as :class:`int`, :class:`bytes` and :class:`tuple`.
1630 1638
1631 * Any non-string iterable may be assigned to *__slots__*. Mappings may also be 1639 * Any non-string iterable may be assigned to *__slots__*. Mappings may also be
1632 used; however, in the future, special meaning may be assigned to the values 1640 used; however, in the future, special meaning may be assigned to the values
1633 corresponding to each key. 1641 corresponding to each key.
1634 1642
1635 * *__class__* assignment works only if both classes have the same *__slots__*. 1643 * *__class__* assignment works only if both classes have the same *__slots__*.
1636 1644
1637 1645
1638 .. _metaclasses: 1646 .. _class-customization:
1639 1647
1640 Customizing class creation 1648 Customizing class creation
1641 -------------------------- 1649 --------------------------
1650
1651 Whenever a class inherits from another class, *__init_subclass__* is
1652 called on that class. This way, it is possible to write classes which
1653 change the behavior of subclasses. This is closely related to class
1654 decorators, but where class decorators only affect the specific class they're
1655 applied to, ``__init_subclass__`` solely applies to future subclasses of the
1656 class defining the method.
1657
1658 .. classmethod:: object.__init_subclass__(cls)
1659
1660 This method is called whenever the containing class is subclassed.
1661 *cls* is then the new subclass. If defined as a normal instance method,
1662 this method is implicitly converted to a class method.
1663
1664 Keyword arguments which are given to a new class are passed to
1665 the parent's class ``__init_subclass__``. For compatibility with
1666 other classes using ``__init_subclass__``, one should take out the
1667 needed keyword arguments and pass the others over to the base
1668 class, as in::
1669
1670 class Philosopher:
1671 def __init_subclass__(cls, default_name, **kwargs):
1672 super().__init_subclass__(**kwargs)
1673 cls.default_name = default_name
1674
1675 class AustralianPhilosopher(Philosopher, default_name="Bruce"):
1676 pass
1677
1678 The default implementation ``object.__init_subclass__`` does
1679 nothing, but raises an error if it is called with any arguments.
1680
1681 .. note::
1682
1683 The metaclass hint ``metaclass`` is consumed by the rest of the type
1684 machinery, and is never passed to ``__init_subclass__`` implementations.
1685 The actual metaclass (rather than the explicit hint) can be accessed as
1686 ``type(cls)``.
1687
1688 .. versionadded:: 3.6
1689
1690
1691 .. _metaclasses:
1692
1693 Metaclasses
1694 ^^^^^^^^^^^
1642 1695
1643 By default, classes are constructed using :func:`type`. The class body is 1696 By default, classes are constructed using :func:`type`. The class body is
1644 executed in a new namespace and the class name is bound locally to the 1697 executed in a new namespace and the class name is bound locally to the
1645 result of ``type(name, bases, namespace)``. 1698 result of ``type(name, bases, namespace)``.
1646 1699
1647 The class creation process can be customised by passing the ``metaclass`` 1700 The class creation process can be customised by passing the ``metaclass``
1648 keyword argument in the class definition line, or by inheriting from an 1701 keyword argument in the class definition line, or by inheriting from an
1649 existing class that included such an argument. In the following example, 1702 existing class that included such an argument. In the following example,
1650 both ``MyClass`` and ``MySubclass`` are instances of ``Meta``:: 1703 both ``MyClass`` and ``MySubclass`` are instances of ``Meta``::
1651 1704
(...skipping 81 matching lines...) Expand 10 before | Expand all | Expand 10 after
1733 created by the compiler if any methods in a class body refer to either 1786 created by the compiler if any methods in a class body refer to either
1734 ``__class__`` or ``super``. This allows the zero argument form of 1787 ``__class__`` or ``super``. This allows the zero argument form of
1735 :func:`super` to correctly identify the class being defined based on 1788 :func:`super` to correctly identify the class being defined based on
1736 lexical scoping, while the class or instance that was used to make the 1789 lexical scoping, while the class or instance that was used to make the
1737 current call is identified based on the first argument passed to the method. 1790 current call is identified based on the first argument passed to the method.
1738 1791
1739 After the class object is created, it is passed to the class decorators 1792 After the class object is created, it is passed to the class decorators
1740 included in the class definition (if any) and the resulting object is bound 1793 included in the class definition (if any) and the resulting object is bound
1741 in the local namespace as the defined class. 1794 in the local namespace as the defined class.
1742 1795
1796 When a new class is created by ``type.__new__``, the object provided as the
1797 namespace parameter is copied to a standard Python dictionary and the original
1798 object is discarded. The new copy becomes the :attr:`~object.__dict__` attribute
1799 of the class object.
1800
1743 .. seealso:: 1801 .. seealso::
1744 1802
1745 :pep:`3135` - New super 1803 :pep:`3135` - New super
1746 Describes the implicit ``__class__`` closure reference 1804 Describes the implicit ``__class__`` closure reference
1747 1805
1748 1806
1749 Metaclass example 1807 Metaclass example
1750 ^^^^^^^^^^^^^^^^^ 1808 ^^^^^^^^^^^^^^^^^
1751 1809
1752 The potential uses for metaclasses are boundless. Some ideas that have been 1810 The potential uses for metaclasses are boundless. Some ideas that have been
1753 explored include logging, interface checking, automatic delegation, automatic 1811 explored include logging, interface checking, automatic delegation, automatic
1754 property creation, proxies, frameworks, and automatic resource 1812 property creation, proxies, frameworks, and automatic resource
1755 locking/synchronization. 1813 locking/synchronization.
1756 1814
1757 Here is an example of a metaclass that uses an :class:`collections.OrderedDict` 1815 Here is an example of a metaclass that uses an :class:`collections.OrderedDict`
1758 to remember the order that class variables are defined:: 1816 to remember the order that class variables are defined::
1759 1817
1760 class OrderedClass(type): 1818 class OrderedClass(type):
1761 1819
1762 @classmethod 1820 @classmethod
1763 def __prepare__(metacls, name, bases, **kwds): 1821 def __prepare__(metacls, name, bases, **kwds):
1764 return collections.OrderedDict() 1822 return collections.OrderedDict()
1765 1823
1766 def __new__(cls, name, bases, namespace, **kwds): 1824 def __new__(cls, name, bases, namespace, **kwds):
1767 result = type.__new__(cls, name, bases, dict(namespace)) 1825 result = type.__new__(cls, name, bases, dict(namespace))
1768 result.members = tuple(namespace) 1826 result.members = tuple(namespace)
1769 return result 1827 return result
1770 1828
1771 class A(metaclass=OrderedClass): 1829 class A(metaclass=OrderedClass):
1772 def one(self): pass 1830 def one(self): pass
1773 def two(self): pass 1831 def two(self): pass
1774 def three(self): pass 1832 def three(self): pass
1775 def four(self): pass 1833 def four(self): pass
1776 1834
(...skipping 410 matching lines...) Expand 10 before | Expand all | Expand 10 after
2187 If an exception is supplied, and the method wishes to suppress the exception 2245 If an exception is supplied, and the method wishes to suppress the exception
2188 (i.e., prevent it from being propagated), it should return a true value. 2246 (i.e., prevent it from being propagated), it should return a true value.
2189 Otherwise, the exception will be processed normally upon exit from this metho d. 2247 Otherwise, the exception will be processed normally upon exit from this metho d.
2190 2248
2191 Note that :meth:`__exit__` methods should not reraise the passed-in exception ; 2249 Note that :meth:`__exit__` methods should not reraise the passed-in exception ;
2192 this is the caller's responsibility. 2250 this is the caller's responsibility.
2193 2251
2194 2252
2195 .. seealso:: 2253 .. seealso::
2196 2254
2197 :pep:`0343` - The "with" statement 2255 :pep:`343` - The "with" statement
2198 The specification, background, and examples for the Python :keyword:`with` 2256 The specification, background, and examples for the Python :keyword:`with`
2199 statement. 2257 statement.
2200 2258
2201 2259
2202 .. _special-lookup: 2260 .. _special-lookup:
2203 2261
2204 Special method lookup 2262 Special method lookup
2205 --------------------- 2263 ---------------------
2206 2264
2207 For custom classes, implicit invocations of special methods are only guaranteed 2265 For custom classes, implicit invocations of special methods are only guaranteed
(...skipping 107 matching lines...) Expand 10 before | Expand all | Expand 10 after
2315 iterating over the result. When the coroutine has finished executing and 2373 iterating over the result. When the coroutine has finished executing and
2316 returns, the iterator raises :exc:`StopIteration`, and the exception's 2374 returns, the iterator raises :exc:`StopIteration`, and the exception's
2317 :attr:`~StopIteration.value` attribute holds the return value. If the 2375 :attr:`~StopIteration.value` attribute holds the return value. If the
2318 coroutine raises an exception, it is propagated by the iterator. Coroutines 2376 coroutine raises an exception, it is propagated by the iterator. Coroutines
2319 should not directly raise unhandled :exc:`StopIteration` exceptions. 2377 should not directly raise unhandled :exc:`StopIteration` exceptions.
2320 2378
2321 Coroutines also have the methods listed below, which are analogous to 2379 Coroutines also have the methods listed below, which are analogous to
2322 those of generators (see :ref:`generator-methods`). However, unlike 2380 those of generators (see :ref:`generator-methods`). However, unlike
2323 generators, coroutines do not directly support iteration. 2381 generators, coroutines do not directly support iteration.
2324 2382
2383 .. versionchanged:: 3.5.2
2384 It is a :exc:`RuntimeError` to await on a coroutine more than once.
2385
2386
2325 .. method:: coroutine.send(value) 2387 .. method:: coroutine.send(value)
2326 2388
2327 Starts or resumes execution of the coroutine. If *value* is ``None``, 2389 Starts or resumes execution of the coroutine. If *value* is ``None``,
2328 this is equivalent to advancing the iterator returned by 2390 this is equivalent to advancing the iterator returned by
2329 :meth:`__await__`. If *value* is not ``None``, this method delegates 2391 :meth:`__await__`. If *value* is not ``None``, this method delegates
2330 to the :meth:`~generator.send` method of the iterator that caused 2392 to the :meth:`~generator.send` method of the iterator that caused
2331 the coroutine to suspend. The result (return value, 2393 the coroutine to suspend. The result (return value,
2332 :exc:`StopIteration`, or other exception) is the same as when 2394 :exc:`StopIteration`, or other exception) is the same as when
2333 iterating over the :meth:`__await__` return value, described above. 2395 iterating over the :meth:`__await__` return value, described above.
2334 2396
(...skipping 14 matching lines...) Expand all
2349 is suspended, this method first delegates to the :meth:`~generator.close` 2411 is suspended, this method first delegates to the :meth:`~generator.close`
2350 method of the iterator that caused the coroutine to suspend, if it 2412 method of the iterator that caused the coroutine to suspend, if it
2351 has such a method. Then it raises :exc:`GeneratorExit` at the 2413 has such a method. Then it raises :exc:`GeneratorExit` at the
2352 suspension point, causing the coroutine to immediately clean itself up. 2414 suspension point, causing the coroutine to immediately clean itself up.
2353 Finally, the coroutine is marked as having finished executing, even if 2415 Finally, the coroutine is marked as having finished executing, even if
2354 it was never started. 2416 it was never started.
2355 2417
2356 Coroutine objects are automatically closed using the above process when 2418 Coroutine objects are automatically closed using the above process when
2357 they are about to be destroyed. 2419 they are about to be destroyed.
2358 2420
2421 .. _async-iterators:
2359 2422
2360 Asynchronous Iterators 2423 Asynchronous Iterators
2361 ---------------------- 2424 ----------------------
2362 2425
2363 An *asynchronous iterable* is able to call asynchronous code in its 2426 An *asynchronous iterable* is able to call asynchronous code in its
2364 ``__aiter__`` implementation, and an *asynchronous iterator* can call 2427 ``__aiter__`` implementation, and an *asynchronous iterator* can call
2365 asynchronous code in its ``__anext__`` method. 2428 asynchronous code in its ``__anext__`` method.
2366 2429
2367 Asynchronous iterators can be used in an :keyword:`async for` statement. 2430 Asynchronous iterators can be used in an :keyword:`async for` statement.
2368 2431
2369 .. method:: object.__aiter__(self) 2432 .. method:: object.__aiter__(self)
2370 2433
2371 Must return an *awaitable* resulting in an *asynchronous iterator* object. 2434 Must return an *asynchronous iterator* object.
2372 2435
2373 .. method:: object.__anext__(self) 2436 .. method:: object.__anext__(self)
2374 2437
2375 Must return an *awaitable* resulting in a next value of the iterator. Should 2438 Must return an *awaitable* resulting in a next value of the iterator. Should
2376 raise a :exc:`StopAsyncIteration` error when the iteration is over. 2439 raise a :exc:`StopAsyncIteration` error when the iteration is over.
2377 2440
2378 An example of an asynchronous iterable object:: 2441 An example of an asynchronous iterable object::
2379 2442
2380 class Reader: 2443 class Reader:
2381 async def readline(self): 2444 async def readline(self):
2382 ... 2445 ...
2383 2446
2384 async def __aiter__(self): 2447 def __aiter__(self):
2385 return self 2448 return self
2386 2449
2387 async def __anext__(self): 2450 async def __anext__(self):
2388 val = await self.readline() 2451 val = await self.readline()
2389 if val == b'': 2452 if val == b'':
2390 raise StopAsyncIteration 2453 raise StopAsyncIteration
2391 return val 2454 return val
2392 2455
2393 .. versionadded:: 3.5 2456 .. versionadded:: 3.5
2394 2457
2458 .. note::
2459
2460 .. versionchanged:: 3.5.2
2461 Starting with CPython 3.5.2, ``__aiter__`` can directly return
2462 :term:`asynchronous iterators <asynchronous iterator>`. Returning
2463 an :term:`awaitable` object will result in a
2464 :exc:`PendingDeprecationWarning`.
2465
2466 The recommended way of writing backwards compatible code in
2467 CPython 3.5.x is to continue returning awaitables from
2468 ``__aiter__``. If you want to avoid the PendingDeprecationWarning
2469 and keep the code backwards compatible, the following decorator
2470 can be used::
2471
2472 import functools
2473 import sys
2474
2475 if sys.version_info < (3, 5, 2):
2476 def aiter_compat(func):
2477 @functools.wraps(func)
2478 async def wrapper(self):
2479 return func(self)
2480 return wrapper
2481 else:
2482 def aiter_compat(func):
2483 return func
2484
2485 Example::
2486
2487 class AsyncIterator:
2488
2489 @aiter_compat
2490 def __aiter__(self):
2491 return self
2492
2493 async def __anext__(self):
2494 ...
2495
2496 Starting with CPython 3.6, the :exc:`PendingDeprecationWarning`
2497 will be replaced with the :exc:`DeprecationWarning`.
2498 In CPython 3.7, returning an awaitable from ``__aiter__`` will
2499 result in a :exc:`RuntimeError`.
2500
2395 2501
2396 Asynchronous Context Managers 2502 Asynchronous Context Managers
2397 ----------------------------- 2503 -----------------------------
2398 2504
2399 An *asynchronous context manager* is a *context manager* that is able to 2505 An *asynchronous context manager* is a *context manager* that is able to
2400 suspend execution in its ``__aenter__`` and ``__aexit__`` methods. 2506 suspend execution in its ``__aenter__`` and ``__aexit__`` methods.
2401 2507
2402 Asynchronous context managers can be used in an :keyword:`async with` statement. 2508 Asynchronous context managers can be used in an :keyword:`async with` statement.
2403 2509
2404 .. method:: object.__aenter__(self) 2510 .. method:: object.__aenter__(self)
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
2436 2542
2437 .. [#] "Does not support" here means that the class has no such method, or 2543 .. [#] "Does not support" here means that the class has no such method, or
2438 the method returns ``NotImplemented``. Do not set the method to 2544 the method returns ``NotImplemented``. Do not set the method to
2439 ``None`` if you want to force fallback to the right operand's reflected 2545 ``None`` if you want to force fallback to the right operand's reflected
2440 method--that will instead have the opposite effect of explicitly 2546 method--that will instead have the opposite effect of explicitly
2441 *blocking* such fallback. 2547 *blocking* such fallback.
2442 2548
2443 .. [#] For operands of the same type, it is assumed that if the non-reflected me thod 2549 .. [#] For operands of the same type, it is assumed that if the non-reflected me thod
2444 (such as :meth:`__add__`) fails the operation is not supported, which is why the 2550 (such as :meth:`__add__`) fails the operation is not supported, which is why the
2445 reflected method is not called. 2551 reflected method is not called.
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+