Skip to content

Instantly share code, notes, and snippets.

@dutc
Created August 31, 2021 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dutc/9c7a25d8129802c5d7ab0b2c8424f3ca to your computer and use it in GitHub Desktop.
Save dutc/9c7a25d8129802c5d7ab0b2c8424f3ca to your computer and use it in GitHub Desktop.
“Python Expert” Newsletter (Sep 22, 2021): Learning Corner
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__ = }',
)
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 = }')
@dutc
Copy link
Author

dutc commented Aug 31, 2021

As you can see:

  • the descriptor protocol is the mechanism by which instance methods, @classmethod, @staticmethod, and @property all work!

@dutc
Copy link
Author

dutc commented Aug 31, 2021

For the full write-up and discussion, sign up for the “Python Expert” newsletter!

bit.ly/expert-python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment