Skip to content

Instantly share code, notes, and snippets.

@dutc
Created August 31, 2021 14:44
Show Gist options
  • Save dutc/bc76a67c65d3a006ecc0dbfb845cbb12 to your computer and use it in GitHub Desktop.
Save dutc/bc76a67c65d3a006ecc0dbfb845cbb12 to your computer and use it in GitHub Desktop.
“Python Expert” Newsletter (Sep 1, 2021): Learning Corner
from pandas import DataFrame
class Base:
def __len__(self):
return 1
class Derived(Base):
def __len__(self):
return super().__len__() + 1
class T:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
if __name__ == '__main__':
df = DataFrame({
'a': range(10)
})
print(
df['a'], # __getitem__
df.a, # __getattr__
)
@dutc
Copy link
Author

dutc commented Aug 31, 2021

As you can see:

  • almost every syntax or built-in function has an associated implementation point—a __-method, a bytecode instruction, a tp_ method—and these constitute a “protocol.”
  • in Python, implementation of a protocol almost always involves dispatching to a constituent object or a base type.
  • one of the more important and more interesting protocols is __getattr__

@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