Notice: While JavaScript is not essential for this website, your interaction with the content will be limited. Please turn JavaScript on for the full experience.
...classmethod def classname(cls): return cls.__name__ To instead be explained as roughly equivalent to: classname = .d1(classname) given: d1 = classmethod def classname(cls): return cls.__name__ Anticipated Objections Two Ways To Do It A lot of code may now be written with values defined either before the expression where they are used or afterwards in a given clause, creating two ways to do it, perhaps without an obvious way of choosing between them. On reflection, I fee...
...classmethod decorator (similar to __init_subclass__) and is inherited like normal attributes. For example: class MyList: def __getitem__(self, index): return index + 1 def __class_getitem__(cls, item): return f"{cls.__name__}[{item.__name__}]" class MyOtherList(MyList): pass assert MyList()[0] == 1 assert MyList[int] == "MyList[int]" assert MyOtherList()[0] == 1 assert MyOtherList[int] == "MyOtherList[int]" Note that this method is used as a fallback, so if a met...
...classmethod def __instancecheck__(cls, x): return hasattr(x, "__len__") @classmethod def __subclasscheck__(cls, C): return hasattr(C, "__bases__") and hasattr(C, "__len__") This has the advantage of not requiring explicit registration. However, the semantics are hard to get exactly right given the confusing semantics of instance attributes vs. class attributes, and that a class is an instance of its metaclass; the check for __bases__ is only an approximation of the d...
...classmethod def __prepare__(cls, *args, **kwargs): return OrderedDict() class Spam(metaclass=Meta): ham = None eggs = 5 __definition_order__ = tuple(locals()) Why a tuple? Use of a tuple reflects the fact that we are exposing the order in which attributes on the class were defined. Since the definition is already complete by the time __definition_order__ is set, the content and order of the value won't be changing. Thus we use a type that communicates that state of i...
...classmethod something like dict.fromblock that could be used like: make dict.fromblock params: x = 1 y = 2 So the question is, will many types want to use the make-statement as an alternate constructor? And if so, does that alternate constructor need to have the same name as the original constructor? Customizing the dict in which the block is executed Should users of the make-statement be able to determine in which dict object the code is executed? This would allow the make-stateme...
...classmethod or staticmethod, zd will succeed, and zm will silently yield nothing (which is the problem we are trying to avoid in the first place). This proposal is further complicated by the fact that CPython's actual zip type is currently an undocumented implementation detail. This means that choosing one of the above behaviors will effectively "lock in" the current implementation (or at least require it to be emulated) going forward. Change The Default Behavior Of zip There is nothing "wron...
...classmethod Path.cwd, by instantiating the class with a string representing a path or by using the default constructor which is equivalent to Path("."). Path provides common pathname manipulation, pattern expansion, pattern matching and other high-level file operations including copying. Basically Path provides everything path-related except the manipulation of file contents, for which file objects are better suited. Platform incompatibilities are dealt with by not instantiating system specific...
...classmethod: Load a snapshot from a file. See also dump(). statistics(group_by: str, cumulative: bool=False) method: Get statistics as a sorted list of Statistic instances grouped by group_by: group_by description 'filename' filename 'lineno' filename and line number 'traceback' traceback If cumulative is True, cumulate size and count of memory blocks of all frames of the traceback of a trace, not only the most recent frame. The cumulative mode can only be used with group_by equ...
...classmethod def favorite_mood(cls): # cls here is the enumeration return cls.happy Then: >>> Mood.favorite_mood() <Mood.happy: 3> >>> Mood.happy.describe() ('happy', 3) >>> str(Mood.funky) 'my custom str! 1' The rules for what is allowed are as follows: all attributes defined within an enumeration will become members of this enumeration, with the exception of __dunder__ names and descriptors [9]; methods are descriptors too. Restricted subclassing ...
...classmethod that problem would pass undetected while it might cause subtle errors when running the code. History 23-Jul-2015: Added type flag Py_TPFLAGS_GETDESCRIPTOR after talking with Guido. The new flag is primarily useful to avoid crashing when loading an extension for an older version of CPython and could have positive speed implications as well. Jul-2014: renamed slot to __getdescriptor__, the old name didn't match the naming style of other slots and was less descriptive. Discussi...
...classmethod and staticmethod in class bodies. It's not really clear if it needs to, however. Copyright This document has been placed in the public domain. Source: https://github.com/python/peps/blob/master/pep-3124.txt
...classmethods on ModuleSpec. However that would expose them on all modules via __spec__, which has the potential to unnecessarily confuse non-advanced Python users. The factory functions have a specific use case, to support finder authors. See ModuleSpec Users. Likewise, several other methods could be added to ModuleSpec that expose the specific uses of module specs by the import machinery: create() - a wrapper around Loader.create_module(). exec(module) - a wrapper around Loader.exec_module(...
...classmethod. It would need to be public (but not necessarily a builtin) for those needing to override the method. There is a proof of concept. It isn't an operator. Guido discusses why operators are useful. For another viewpoint, see Nick Coghlan's blog post. Use a Function Instead of a method, use a new built-in function merged(). One possible implementation could be something like this: def merged(*mappings, **kw): if mappings and isinstance(mappings[0], dict): # If the fi...
...classmethod. Type Definition Syntax The syntax leverages PEP 3107-style annotations with a number of extensions described in sections below. In its basic form, type hinting is used by filling function annotation slots with classes: def greeting(name: str) -> str: return 'Hello ' + name This states that the expected type of the name argument is str. Analogically, the expected return type is str. Expressions whose type is a subtype of a specific argument type are also accepted for tha...