Created
August 31, 2021 14:48
-
-
Save dutc/9c7a25d8129802c5d7ab0b2c8424f3ca to your computer and use it in GitHub Desktop.
“Python Expert” Newsletter (Sep 22, 2021): Learning Corner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def foo(self, _): | |
pass | |
class T: | |
from json import dumps | |
from itertools import repeat | |
foo = foo | |
def bar(self, _): | |
pass | |
if __name__ == '__main__': | |
obj = T() | |
print( | |
f'{obj.bar("") = }', | |
f'{obj.foo("") = }', | |
# f'{obj.dumps("") = }', | |
f'{obj.repeat("") = }', | |
sep='\n' | |
) | |
from json import dumps | |
from itertools import repeat | |
print( | |
f'{dumps.__get__ = }', | |
# f'{repeat.__get__ = }', | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from types import FunctionType | |
from functools import wraps | |
@dataclass | |
class instancemethod: | |
f : FunctionType | |
def __get__(self, instance, _): | |
return wraps(self.f)(lambda *args, **kwargs: self.f(instance, *args, **kwargs)) | |
@dataclass | |
class classmethod_: | |
f : FunctionType | |
def __get__(self, _, owner): | |
return wraps(self.f)(lambda *args, **kwargs: self.f(owner, *args, **kwargs)) | |
@dataclass | |
class staticmethod_: | |
f : FunctionType | |
def __get__(self, _, __): | |
return self.f | |
# # or you could consider `staticmethod` to be | |
# # the absence of the descriptor protocol… | |
# @dataclass | |
# class staticmethod_: | |
# f : FunctionType | |
# __call__ = lambda s, *args, **kwargs: s.f(*args, **kwargs) | |
@dataclass | |
class property_: | |
f : FunctionType | |
def __get__(self, instance, _): | |
return self.f(instance) | |
class T: | |
@instancemethod | |
def foo(self): | |
return f'T.foo({self})' | |
@classmethod_ | |
def bar(cls): | |
return f'T.foo({cls})' | |
@staticmethod_ | |
def baz(): | |
return f'T.foo()' | |
@property_ | |
def quux(self): | |
return f'T.foo({self})' | |
if __name__ == '__main__': | |
obj = T() | |
print(f'{obj.foo() = }') | |
print(f'{obj.bar() = }') | |
print(f'{obj.baz() = }') | |
print(f'{obj.quux = }') |
For the full write-up and discussion, sign up for the “Python Expert” newsletter!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As you can see:
@classmethod
,@staticmethod
, and@property
all work!