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(foo) This becomes less readable with longer methods. It also seems less than pythonic to name the function three times for what is conceptually a single declaration. A solution to this problem is to move the transformation of the method closer to the method's own declaration. The intent of the new syntax is to replace def foo(cls): pass foo = synchronized(lock)(foo) foo = classmethod(foo) with an alternative that places the decoration in the function's declaration: @classme...
...Classmethod Signatures The Self type annotation is also useful for classmethods that return an instance of the class that they operate on. For example, from_config in the following snippet builds a Shape object from a given config. class Shape: def __init__(self, scale: float) -> None: ... @classmethod def from_config(cls, config: dict[str, float]) -> Shape: return cls(config["scale"]) However, this means that Circle.from_config(...) is inferred to return a value of ...
...classmethod(init) self = super().__new__(cls, name, bases, ns) for k, v in self.__dict__.items(): func = getattr(v, '__set_name__', None) if func is not None: func(self, k) super(self, self).__init_subclass__(**kwargs) return self def __init__(self, name, bases, ns, **kwargs): super().__init__(name, bases, ns) class NewObject(object): @classmethod def __init_subclass__(cls): pass Reference Im...
...classmethod and a subclass has two factory classmethods, both of which needing to properly make super calls to the one in the base- class. super.foo(self, *args) This variation actually eliminates the problems with locating the proper instance, and if any of the alternatives were pushed into the spotlight, I would want it to be this one. super(*p, **kw) There has been the proposal that directly calling super(*p, **kw) would be equivalent to calling the method on the super object with the sam...
...classmethod. Second, class methods of extension types are already callable: >>> fromhex = float.__dict__["fromhex"] >>> type(fromhex) <class 'classmethod_descriptor'> >>> fromhex(float, "0xff") 255.0 Third, one can see function, staticmethod and classmethod as different kinds of unbound methods: they all become method when bound, but the implementation of __get__ is slightly different. From this point of view, it looks strange that function is callable but the ...
...classmethod", cls, y foo = classmethod(foo) C.foo(1) c = C() c.foo(1) Both the call C.foo(1) and the call c.foo(1) end up calling foo() with two arguments, and print "classmethod __main__.C 1". The first argument of foo() is implied, and it is the class, even if the method was invoked via an instance. Now let's continue the example: class D(C): pass D.foo(1) d = D() d.foo(1) This prints "classmethod __main__.D 1" both ti...
...classmethod", cls, y foo = classmethod(foo) C.foo(1) c = C() c.foo(1) Both the call C.foo(1) and the call c.foo(1) end up calling foo() with two arguments, and print "classmethod __main__.C 1". The first argument of foo() is implied, and it is the class, even if the method was invoked via an instance. Now let's continue the example: class D(C): pass D.foo(1) d = D() d.foo(1) This prints "classmethod __main__.D 1" both times; in other words, the class pass...
...classmethod", cls, y foo = classmethod(foo) C.foo(1) c = C() c.foo(1) Both the call C.foo(1) and the call c.foo(1) end up calling foo() with two arguments, and print "classmethod __main__.C 1". The first argument of foo() is implied, and it is the class, even if the method was invoked via an instance. Now let's continue the example: class D(C): pass D.foo(1) d = D() d.foo(1) This prints "classmethod __main__.D 1" both times; in other words, the class passed as the first argument o...
...classmethod and a subclass has two factory classmethods, both of which needing to properly make super calls to the one in the base- class. super.foo(self, *args) This variation actually eliminates the problems with locating the proper instance, and if any of the alternatives were pushed into the spotlight, I would want it to be this one. super or super() This proposal leaves no room for different names, signatures, or application to other classes, or instances. A way to allow some similar us...
...classmethod on the __autodecorate__ decorator. It was made implicit since there's no sensible interpretation for leaving it out, and that case would need to be detected anyway in order to give a useful error message. This decision was reinforced after noticing that the user experience of defining __prepare__ and forgetting the @classmethod method decorator is singularly incomprehensible (particularly since PEP 3115 documents it as an ordinary method, and the current documentation doesn't explici...
...classmethod constructor. For example: @dataclass class C: x: int @classmethod def from_file(cls, filename): with open(filename) as fl: file_value = int(fl.read()) return C(file_value) c = C.from_file('file.txt') Because the __post_init__ function is the last thing called in the generated __init__, having a classmethod constructor (which can also execute code immediately after constructing the object) is functionally equivalent to being able to pass par...
...classmethod def module_repr(cls, module): return "<module '{}' (namespace)>".format(module.__name__) Built-in module reprs would no longer need to be hard-coded, but instead would come from their loader as well: class BuiltinImporter: @classmethod def module_repr(cls, module): return "<module '{}' (built-in)>".format(module.__name__) Here are some example reprs of different types of modules with different sets of the related attributes: >>> im...
...classmethod and staticmethod are supported too. Since both are descriptors, the former returns a bound method, and the latter returns its wrapped function.) If the object is an instance of functools.partial, construct a new Signature from its partial.func attribute, and account for already bound partial.args and partial.kwargs If the object is a class or metaclass: If the object's type has a __call__ method defined in its MRO, return a Signature for it If the object has a __new__ method defined...
...classmethod and classmethod_descriptor. It would certainly make sense to put these in the base_function class hierarchy and unify classmethod and classmethod_descriptor. However, this PEP is already big enough and this is left as a possible future improvement. Slot wrappers for extension types like __init__ or __eq__ are quite different from normal methods. They are also typically not called directly because you would normally write foo[i] instead of foo.__getitem__(i). So these are left outside...
...classmethod .fromhex() that takes a string of characters from the set [0-9a-fA-F ] and returns a bytes object (similar to binascii.unhexlify). For example: >>> bytes.fromhex('5c5350ff') b'\\SP\xff' >>> bytes.fromhex('5c 53 50 ff') b'\\SP\xff' The object has a .hex() method that does the reverse conversion (similar to binascii.hexlify): >> bytes([92, 83, 80, 255]).hex() '5c5350ff' The bytes object has some methods similar to list methods, and others similar to str met...
...classmethod def adapt(cls, obj): pass class E(AdaptingProtocol): ''' >>> a = A() >>> a is adapt(a, E) # case (c) True >>> b = A() >>> b is adapt(b, E) # case (c) True >>> c = C() >>> c is adapt(c, E) # a failure case Traceback (most recent call last): ... AdaptationError ''' @classmethod def adapt(cls, obj): if isinstance(obj, A): return obj...
...classmethod on concrete paths): >>> PurePosixPath() PurePosixPath('.') Representing To represent a path (e.g. to pass it to third-party libraries), just call str() on it: >>> p = PurePath('/home/antoine/pathlib/setup.py') >>> str(p) '/home/antoine/pathlib/setup.py' >>> p = PureWindowsPath('c:/windows') >>> str(p) 'c:\\windows' To force the string representation with forward slashes, use the as_posix() method: >>> p.as_posix() 'c:/windo...
...classmethod def __prepare__(metacls, name, bases): # No keywords in this case return member_table() # The metaclass invocation def __new__(cls, name, bases, classdict): # Note that we replace the classdict with a regular # dict before passing it to the superclass, so that we # don't continue to record member names after the class # has been created. result = type.__new__(cls, name, bases, dict(classdict)) result.member_names = ...