SlideShare a Scribd company logo
a smalltalk on
Object and Protocol in CPython
shiyao.ma <i@introo.me>
May. 4th
Why this
‣ Python is great for carrying out research experiment.
this should lay the foundation why I discuss Python.
‣ Life is short. You need Python.
this should lay the foundation why people like Python.
2
life is neither a short nor a long, just a (signed) int, 31bits at most, I say.
Takeaway
‣ Understand the inter-relation among {.py, .pyc .c} file.
‣ Understand that everything in Python is an object.
‣ Understand how functions on TypeObject affect
InstanceObject.
3
CPython Overview
‣ First implemented in Dec.1989 by GvR, the BDFL
‣ Serving as the reference implementation.
‣ IronPython (clr)
‣ Jython (jvm)
‣ Brython (v8, spider) [no kidding]
‣ Written in ANSI C.
‣ flexible language binding
‣ embedding (libpython), e.g., openwrt, etc.
4
CPython Overview
‣ Code maintained by Mercurial.
‣ source: https://hg.python.org/cpython/
‣ Build toolchain is autoconf (on *nix)
./configure --with-pydebug && make -j2
5
CPython Overview
‣ Structure
6
cpython
configure.ac
Doc
Grammar
Include
Lib
Mac
Modules
Objects
Parser
Programs
Python
CPython Overview
‣ execution lifetime
7
PY
Parser
PY[CO]
VM
LOAD 1
LOAD 2
ADD
LOAD X
STORE X
x = 1 + 2
1 1
2
3
3
x
STACK
takeaway: py/pyc/c inter-relatoin
8
object and protocol:
the objects
Object
object: memory of C structure with common header
9
PyListObject
PyDictObject
PyTupleObject
PySyntaxErrorObject
PyImportErrorObject
…
takeaway: everything is object
ob_type
ob_refcnt
PyObject
ob_type
ob_size
ob_refcnt
PyVarObject
Object Structure
Will PyLongObject overflow?
10
The answer: chunk-chunk
digit[n]
…
digit[3]
digit[2]
ob_type
ob_size
digit ob_digit[1]
ob_refcnt
PyLongObject
typedef PY_UINT32_T digit;
result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
size*sizeof(digit));
n = 2 ** 64 # more bits than a word
assert type(n) is int and n > 0
Object Structure
Why my multi-dimensional array won’t work?
11
The answer: indirection, mutability
allocated
ob_type
ob_item
ob_refcnt
ob_size
PyListObject
PyObject*
PyObject*
…
PyObject*
PyObject*
allocated
ob_type
ob_item
ob_refcnt
ob_size
PyObject*
PyObject*
… 42
None
m, n = 4, 2
arr = [ [ None ] * n ] * m
arr[1][1] = 42
# [[None, 42], [None, 42], [None, 42], [None, 42]]
PyList_SetItem
Object Structure
what is the ob_type?
12
The answer: flexible type system
class Machine(type): pass
# Toy = Machine(foo, bar, hoge)
class Toy(metaclass=Machine): pass
toy = Toy()
# Toy, Machine, type, type
print(type(toy), type(Toy), type(Machine), type(type))
ob_type
ob_refcnt
…
toy
ob_type
ob_refcnt
…
ob_type
ob_refcnt
…
Toy
Machine
ob_type
ob_refcnt
…
Type
Object Structure
what is the ob_type?
13
# ob_type2
# 10fd69490 - 10fd69490 - 10fd69490
print("%x - %x - %x" % (id(42 .__class__), id(233 .__class__), id(int)))
assert dict().__class__ is dict
# dynamically create a class named "MagicKlass"
klass=“MagicKlass"
klass=type(klass, (object,), {"quack": lambda _: print("quack")});
duck = klass()
# quack
duck.quack()
assert duck.__class__ is klass
Object Structure
what is the ob_type?
14
ob_type
…
…
…
ob_refcnt
PyObject
…
*tp_as_mapping
*tp_as_sequence
*tp_as_number
…
ob_type
tp_getattr
…
tp_print
ob_refcnt
PyTypeObject
…
nb_subtract
…
nb_add
15
object and protocol:
the protocol
16
Protocol:
duck-typing in typing
AOL
‣ Abstract Object Layer
17
…
*tp_as_mapping
*tp_as_sequence
*tp_as_number
…
ob_type
tp_getattr
…
tp_print
ob_refcnt
PyTypeObject
…
nb_subtract
…
nb_add
When I see a bird that walks like a duck and swims like a duck and
quacks like a duck, I call that bird a duck.
Object Protocol
Number Protocol
Sequence Protocol
Iterator Protocol
Buffer Protocol
int PyObject_Print(PyObject *o, FILE *fp, int flags)
int PyObject_HasAttr(PyObject *o, PyObject *attr_name)
int PyObject_DelAttr(PyObject *o, PyObject *attr_name)
…
PyObject* PyNumber_Add(PyObject *o1, PyObject *o2)
PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2)
PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2)
…
PyObject* PySequence_Concat(PyObject *o1, PyObject *o2)
PyObject* PySequence_Repeat(PyObject *o, Py_ssize_t count)
PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i)
…
int PyIter_Check(PyObject *o)
PyObject* PyIter_Next(PyObject *o)
int PyObject_GetBuffer(PyObject *exporter, Py_buffer *view, int flags)
void PyBuffer_Release(Py_buffer *view)
int PyBuffer_IsContiguous(Py_buffer *view, char order)
…
Mapping Protocol
int PyMapping_HasKey(PyObject *o, PyObject *key)
PyObject* PyMapping_GetItemString(PyObject *o, const char *key)
int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *v)
…
Example
‣ Number Protocol (PyNumber_Add)
18
// v + w?
PyObject *
PyNumber_Add(PyObject *v, PyObject *w)
{
// this just an example!
// try on v
result = v->ob_type->tp_as_number.nb_add(v, w)
// if fail or if w->ob_type is a subclass of v->ob_type
result = w->ob_type->tp_as_number.nb_add(w, v)
// return result
}
…
*tp_as_mapping
*tp_as_sequence
*tp_as_number
…
ob_type
tp_getattr
…
tp_print
ob_refcnt
PyTypeObject
…
nb_subtract
…
nb_add
takeaway: typeobject stores meta information
More Example
Why can we multiply a list? Is it slow?
19
arr = [None] * 3
# [None, None, None]
Exercise:
arr = [None] + [None]
# [None, None]
Magic Methods
access slots of tp_as_number, and its friends
20
Note tp_as_mapping->mp_length and tp_as_sequence->sq_length map to the
same slot __len__

If your C based MyType implements both, what’s MyType.__len__ and
len(MyType()) ?

# access magic method of dict and list
dict.__getitem__ # tp_as_mapping->mp_subscript
dict.__len__ # tp_as_mapping->mp_length
list.__getitem__ # tp_as_sequence->sq_item
list.__len__ # tp_as_sequence->sq_length
Magic Methods
backfill as_number and its friends
21
class A():
def __len__(self):
return 42
class B(): pass
# 42
print(len(A()))
# TypeError: object of type 'B' has no len()
print(len(B()))
Py_ssize_t
PyObject_Size(PyObject *o)
{
PySequenceMethods *m;
if (o == NULL) {
null_error();
return -1;
}
m = o->ob_type->tp_as_sequence;
if (m && m->sq_length)
return m->sq_length(o);
return PyMapping_Size(o);
}Which field does A.__len__ fill?
Next: Heterogeneous
Have you ever felt insecure towards negative indexing of
PyListObject?
22
The answer: RTFSC
words = "the quick brown fox jumps over the old lazy dog".split()
assert words[-1] == "dog"
words.insert(-100, "hayabusa")
assert words[-100] == ??
Thanks
23

More Related Content

What's hot (20)

Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
Egor Bogatov
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure
Hadziq Fabroyir
 
C++ via C#
C++ via C#C++ via C#
C++ via C#
Egor Bogatov
 
C++ references
C++ referencesC++ references
C++ references
corehard_by
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Go
strikr .
 
Python The basics
Python   The basicsPython   The basics
Python The basics
Bobby Murugesan
 
C++ Chapter I
C++ Chapter IC++ Chapter I
C++ Chapter I
Sorn Chanratha
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++
Ilio Catallo
 
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
Frank Müller
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
Bartlomiej Filipek
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
Ritika Sharma
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
Ishin Vin
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
Dmitri Nesteruk
 
Idiomatic C++
Idiomatic C++Idiomatic C++
Idiomatic C++
Federico Ficarelli
 
C++ Chapter IV
C++ Chapter IVC++ Chapter IV
C++ Chapter IV
Sorn Chanratha
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
Open Gurukul
 
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++
PRINCE KUMAR
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
Carson Wilber
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
Dmitri Nesteruk
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
Egor Bogatov
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure
Hadziq Fabroyir
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Go
strikr .
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++
Ilio Catallo
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
Ritika Sharma
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
Ishin Vin
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
Dmitri Nesteruk
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
Open Gurukul
 
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++
PRINCE KUMAR
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
Dmitri Nesteruk
 

Viewers also liked (20)

Quattro passi tra le nuvole (e non scordate il paracadute)
Quattro passi tra le nuvole (e non scordate il paracadute)Quattro passi tra le nuvole (e non scordate il paracadute)
Quattro passi tra le nuvole (e non scordate il paracadute)
Nicola Iarocci
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
Jason Myers
 
Hands on django part 1
Hands on django part 1Hands on django part 1
Hands on django part 1
MicroPyramid .
 
Fuga dalla Comfort Zone
Fuga dalla Comfort ZoneFuga dalla Comfort Zone
Fuga dalla Comfort Zone
Nicola Iarocci
 
Diabetes and Me: My Journey So Far
Diabetes and Me: My Journey So FarDiabetes and Me: My Journey So Far
Diabetes and Me: My Journey So Far
Jason Myers
 
CoderDojo Romagna
CoderDojo RomagnaCoderDojo Romagna
CoderDojo Romagna
Nicola Iarocci
 
Python Static Analysis Tools
Python Static Analysis ToolsPython Static Analysis Tools
Python Static Analysis Tools
Jason Myers
 
Introduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsIntroduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic Migrations
Jason Myers
 
Online / Offline
Online / OfflineOnline / Offline
Online / Offline
Nicola Iarocci
 
Coderfaire Data Networking for Developers
Coderfaire Data Networking for DevelopersCoderfaire Data Networking for Developers
Coderfaire Data Networking for Developers
Jason Myers
 
RESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nicRESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nic
Nicola Iarocci
 
Flask - Python microframework
Flask - Python microframeworkFlask - Python microframework
Flask - Python microframework
André Mayer
 
Introduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORMIntroduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORM
Jason Myers
 
Eve - REST API for Humans™
Eve - REST API for Humans™Eve - REST API for Humans™
Eve - REST API for Humans™
Nicola Iarocci
 
We Are All Remote Workers
We Are All Remote WorkersWe Are All Remote Workers
We Are All Remote Workers
Nicola Iarocci
 
REST Web API with MongoDB
REST Web API with MongoDBREST Web API with MongoDB
REST Web API with MongoDB
MongoDB
 
Impact of Restful Web Architecture on Performance and Scalability
Impact of Restful Web Architecture on Performance and ScalabilityImpact of Restful Web Architecture on Performance and Scalability
Impact of Restful Web Architecture on Performance and Scalability
Sanchit Gera
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
Jim Yeh
 
Selenium testing
Selenium testingSelenium testing
Selenium testing
Jason Myers
 
Django channels
Django channelsDjango channels
Django channels
Andy Dai
 
Quattro passi tra le nuvole (e non scordate il paracadute)
Quattro passi tra le nuvole (e non scordate il paracadute)Quattro passi tra le nuvole (e non scordate il paracadute)
Quattro passi tra le nuvole (e non scordate il paracadute)
Nicola Iarocci
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
Jason Myers
 
Hands on django part 1
Hands on django part 1Hands on django part 1
Hands on django part 1
MicroPyramid .
 
Fuga dalla Comfort Zone
Fuga dalla Comfort ZoneFuga dalla Comfort Zone
Fuga dalla Comfort Zone
Nicola Iarocci
 
Diabetes and Me: My Journey So Far
Diabetes and Me: My Journey So FarDiabetes and Me: My Journey So Far
Diabetes and Me: My Journey So Far
Jason Myers
 
Python Static Analysis Tools
Python Static Analysis ToolsPython Static Analysis Tools
Python Static Analysis Tools
Jason Myers
 
Introduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsIntroduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic Migrations
Jason Myers
 
Coderfaire Data Networking for Developers
Coderfaire Data Networking for DevelopersCoderfaire Data Networking for Developers
Coderfaire Data Networking for Developers
Jason Myers
 
RESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nicRESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nic
Nicola Iarocci
 
Flask - Python microframework
Flask - Python microframeworkFlask - Python microframework
Flask - Python microframework
André Mayer
 
Introduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORMIntroduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORM
Jason Myers
 
Eve - REST API for Humans™
Eve - REST API for Humans™Eve - REST API for Humans™
Eve - REST API for Humans™
Nicola Iarocci
 
We Are All Remote Workers
We Are All Remote WorkersWe Are All Remote Workers
We Are All Remote Workers
Nicola Iarocci
 
REST Web API with MongoDB
REST Web API with MongoDBREST Web API with MongoDB
REST Web API with MongoDB
MongoDB
 
Impact of Restful Web Architecture on Performance and Scalability
Impact of Restful Web Architecture on Performance and ScalabilityImpact of Restful Web Architecture on Performance and Scalability
Impact of Restful Web Architecture on Performance and Scalability
Sanchit Gera
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
Jim Yeh
 
Selenium testing
Selenium testingSelenium testing
Selenium testing
Jason Myers
 
Django channels
Django channelsDjango channels
Django channels
Andy Dai
 
Ad

Similar to Intro python-object-protocol (20)

PYTHON OBJECTS - Copy.pptx
 PYTHON OBJECTS - Copy.pptx PYTHON OBJECTS - Copy.pptx
PYTHON OBJECTS - Copy.pptx
sanchiganandhini
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
Chui-Wen Chiu
 
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
Frankie Dintino
 
C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending Python
Priyank Kapadia
 
Python Objects
Python ObjectsPython Objects
Python Objects
Quintagroup
 
Python_Buildin_Data_types_Lecture_8.pptx
Python_Buildin_Data_types_Lecture_8.pptxPython_Buildin_Data_types_Lecture_8.pptx
Python_Buildin_Data_types_Lecture_8.pptx
foxel54542
 
Cthhis_is_cybersecurty_and_cyber_sxec.pptx
Cthhis_is_cybersecurty_and_cyber_sxec.pptxCthhis_is_cybersecurty_and_cyber_sxec.pptx
Cthhis_is_cybersecurty_and_cyber_sxec.pptx
sonawaneabhishek69
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
petrov
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
Steffen Wenz
 
4. Data Handling computer shcience pdf s
4. Data Handling computer shcience pdf s4. Data Handling computer shcience pdf s
4. Data Handling computer shcience pdf s
TonyTech2
 
About Python
About PythonAbout Python
About Python
Shao-Chuan Wang
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
baabtra.com - No. 1 supplier of quality freshers
 
Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.
Carlos Miguel Ferreira
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Advance python
Advance pythonAdvance python
Advance python
pulkit agrawal
 
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
upendramaurya11
 
Slide - FPT University - PFP191 - Chapter 11 - Objects
Slide - FPT University - PFP191 - Chapter 11 - ObjectsSlide - FPT University - PFP191 - Chapter 11 - Objects
Slide - FPT University - PFP191 - Chapter 11 - Objects
cMai28
 
Presentation on python data type
Presentation on python data typePresentation on python data type
Presentation on python data type
swati kushwaha
 
Understanding Python
Understanding PythonUnderstanding Python
Understanding Python
Kaleem Ullah Mangrio
 
Master of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdfMaster of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdf
Krrai1
 
PYTHON OBJECTS - Copy.pptx
 PYTHON OBJECTS - Copy.pptx PYTHON OBJECTS - Copy.pptx
PYTHON OBJECTS - Copy.pptx
sanchiganandhini
 
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrine
Frankie Dintino
 
C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending Python
Priyank Kapadia
 
Python_Buildin_Data_types_Lecture_8.pptx
Python_Buildin_Data_types_Lecture_8.pptxPython_Buildin_Data_types_Lecture_8.pptx
Python_Buildin_Data_types_Lecture_8.pptx
foxel54542
 
Cthhis_is_cybersecurty_and_cyber_sxec.pptx
Cthhis_is_cybersecurty_and_cyber_sxec.pptxCthhis_is_cybersecurty_and_cyber_sxec.pptx
Cthhis_is_cybersecurty_and_cyber_sxec.pptx
sonawaneabhishek69
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
petrov
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
Steffen Wenz
 
4. Data Handling computer shcience pdf s
4. Data Handling computer shcience pdf s4. Data Handling computer shcience pdf s
4. Data Handling computer shcience pdf s
TonyTech2
 
Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.
Carlos Miguel Ferreira
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
upendramaurya11
 
Slide - FPT University - PFP191 - Chapter 11 - Objects
Slide - FPT University - PFP191 - Chapter 11 - ObjectsSlide - FPT University - PFP191 - Chapter 11 - Objects
Slide - FPT University - PFP191 - Chapter 11 - Objects
cMai28
 
Presentation on python data type
Presentation on python data typePresentation on python data type
Presentation on python data type
swati kushwaha
 
Master of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdfMaster of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdf
Krrai1
 
Ad

Recently uploaded (20)

Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 

Intro python-object-protocol

  • 1. a smalltalk on Object and Protocol in CPython shiyao.ma <[email protected]> May. 4th
  • 2. Why this ‣ Python is great for carrying out research experiment. this should lay the foundation why I discuss Python. ‣ Life is short. You need Python. this should lay the foundation why people like Python. 2 life is neither a short nor a long, just a (signed) int, 31bits at most, I say.
  • 3. Takeaway ‣ Understand the inter-relation among {.py, .pyc .c} file. ‣ Understand that everything in Python is an object. ‣ Understand how functions on TypeObject affect InstanceObject. 3
  • 4. CPython Overview ‣ First implemented in Dec.1989 by GvR, the BDFL ‣ Serving as the reference implementation. ‣ IronPython (clr) ‣ Jython (jvm) ‣ Brython (v8, spider) [no kidding] ‣ Written in ANSI C. ‣ flexible language binding ‣ embedding (libpython), e.g., openwrt, etc. 4
  • 5. CPython Overview ‣ Code maintained by Mercurial. ‣ source: https://hg.python.org/cpython/ ‣ Build toolchain is autoconf (on *nix) ./configure --with-pydebug && make -j2 5
  • 7. CPython Overview ‣ execution lifetime 7 PY Parser PY[CO] VM LOAD 1 LOAD 2 ADD LOAD X STORE X x = 1 + 2 1 1 2 3 3 x STACK takeaway: py/pyc/c inter-relatoin
  • 9. Object object: memory of C structure with common header 9 PyListObject PyDictObject PyTupleObject PySyntaxErrorObject PyImportErrorObject … takeaway: everything is object ob_type ob_refcnt PyObject ob_type ob_size ob_refcnt PyVarObject
  • 10. Object Structure Will PyLongObject overflow? 10 The answer: chunk-chunk digit[n] … digit[3] digit[2] ob_type ob_size digit ob_digit[1] ob_refcnt PyLongObject typedef PY_UINT32_T digit; result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) + size*sizeof(digit)); n = 2 ** 64 # more bits than a word assert type(n) is int and n > 0
  • 11. Object Structure Why my multi-dimensional array won’t work? 11 The answer: indirection, mutability allocated ob_type ob_item ob_refcnt ob_size PyListObject PyObject* PyObject* … PyObject* PyObject* allocated ob_type ob_item ob_refcnt ob_size PyObject* PyObject* … 42 None m, n = 4, 2 arr = [ [ None ] * n ] * m arr[1][1] = 42 # [[None, 42], [None, 42], [None, 42], [None, 42]] PyList_SetItem
  • 12. Object Structure what is the ob_type? 12 The answer: flexible type system class Machine(type): pass # Toy = Machine(foo, bar, hoge) class Toy(metaclass=Machine): pass toy = Toy() # Toy, Machine, type, type print(type(toy), type(Toy), type(Machine), type(type)) ob_type ob_refcnt … toy ob_type ob_refcnt … ob_type ob_refcnt … Toy Machine ob_type ob_refcnt … Type
  • 13. Object Structure what is the ob_type? 13 # ob_type2 # 10fd69490 - 10fd69490 - 10fd69490 print("%x - %x - %x" % (id(42 .__class__), id(233 .__class__), id(int))) assert dict().__class__ is dict # dynamically create a class named "MagicKlass" klass=“MagicKlass" klass=type(klass, (object,), {"quack": lambda _: print("quack")}); duck = klass() # quack duck.quack() assert duck.__class__ is klass
  • 14. Object Structure what is the ob_type? 14 ob_type … … … ob_refcnt PyObject … *tp_as_mapping *tp_as_sequence *tp_as_number … ob_type tp_getattr … tp_print ob_refcnt PyTypeObject … nb_subtract … nb_add
  • 17. AOL ‣ Abstract Object Layer 17 … *tp_as_mapping *tp_as_sequence *tp_as_number … ob_type tp_getattr … tp_print ob_refcnt PyTypeObject … nb_subtract … nb_add When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck. Object Protocol Number Protocol Sequence Protocol Iterator Protocol Buffer Protocol int PyObject_Print(PyObject *o, FILE *fp, int flags) int PyObject_HasAttr(PyObject *o, PyObject *attr_name) int PyObject_DelAttr(PyObject *o, PyObject *attr_name) … PyObject* PyNumber_Add(PyObject *o1, PyObject *o2) PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2) PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2) … PyObject* PySequence_Concat(PyObject *o1, PyObject *o2) PyObject* PySequence_Repeat(PyObject *o, Py_ssize_t count) PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i) … int PyIter_Check(PyObject *o) PyObject* PyIter_Next(PyObject *o) int PyObject_GetBuffer(PyObject *exporter, Py_buffer *view, int flags) void PyBuffer_Release(Py_buffer *view) int PyBuffer_IsContiguous(Py_buffer *view, char order) … Mapping Protocol int PyMapping_HasKey(PyObject *o, PyObject *key) PyObject* PyMapping_GetItemString(PyObject *o, const char *key) int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *v) …
  • 18. Example ‣ Number Protocol (PyNumber_Add) 18 // v + w? PyObject * PyNumber_Add(PyObject *v, PyObject *w) { // this just an example! // try on v result = v->ob_type->tp_as_number.nb_add(v, w) // if fail or if w->ob_type is a subclass of v->ob_type result = w->ob_type->tp_as_number.nb_add(w, v) // return result } … *tp_as_mapping *tp_as_sequence *tp_as_number … ob_type tp_getattr … tp_print ob_refcnt PyTypeObject … nb_subtract … nb_add takeaway: typeobject stores meta information
  • 19. More Example Why can we multiply a list? Is it slow? 19 arr = [None] * 3 # [None, None, None] Exercise: arr = [None] + [None] # [None, None]
  • 20. Magic Methods access slots of tp_as_number, and its friends 20 Note tp_as_mapping->mp_length and tp_as_sequence->sq_length map to the same slot __len__ If your C based MyType implements both, what’s MyType.__len__ and len(MyType()) ? # access magic method of dict and list dict.__getitem__ # tp_as_mapping->mp_subscript dict.__len__ # tp_as_mapping->mp_length list.__getitem__ # tp_as_sequence->sq_item list.__len__ # tp_as_sequence->sq_length
  • 21. Magic Methods backfill as_number and its friends 21 class A(): def __len__(self): return 42 class B(): pass # 42 print(len(A())) # TypeError: object of type 'B' has no len() print(len(B())) Py_ssize_t PyObject_Size(PyObject *o) { PySequenceMethods *m; if (o == NULL) { null_error(); return -1; } m = o->ob_type->tp_as_sequence; if (m && m->sq_length) return m->sq_length(o); return PyMapping_Size(o); }Which field does A.__len__ fill?
  • 22. Next: Heterogeneous Have you ever felt insecure towards negative indexing of PyListObject? 22 The answer: RTFSC words = "the quick brown fox jumps over the old lazy dog".split() assert words[-1] == "dog" words.insert(-100, "hayabusa") assert words[-100] == ??