SlideShare ist ein Scribd-Unternehmen logo
1 von 23
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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 StructureHadziq Fabroyir
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Gostrikr .
 
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/InvokeDmitri Nesteruk
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen 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
 

Was ist angesagt? (20)

Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
 
#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
 
C++ via C#
C++ via C#C++ via C#
C++ via C#
 
C++ references
C++ referencesC++ references
C++ references
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Go
 
Python The basics
Python   The basicsPython   The basics
Python The basics
 
C++ Chapter I
C++ Chapter IC++ Chapter I
C++ Chapter I
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++
 
Python programming
Python  programmingPython  programming
Python programming
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 
Idiomatic C++
Idiomatic C++Idiomatic C++
Idiomatic C++
 
C++ Chapter IV
C++ Chapter IVC++ Chapter IV
C++ Chapter IV
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
 

Andere mochten auch

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 flaskJason Myers
 
Hands on django part 1
Hands on django part 1Hands on django part 1
Hands on django part 1MicroPyramid .
 
Fuga dalla Comfort Zone
Fuga dalla Comfort ZoneFuga dalla Comfort Zone
Fuga dalla Comfort ZoneNicola 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 FarJason Myers
 
Python Static Analysis Tools
Python Static Analysis ToolsPython Static Analysis Tools
Python Static Analysis ToolsJason Myers
 
Introduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsIntroduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsJason Myers
 
Coderfaire Data Networking for Developers
Coderfaire Data Networking for DevelopersCoderfaire Data Networking for Developers
Coderfaire Data Networking for DevelopersJason 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 nicNicola Iarocci
 
Flask - Python microframework
Flask - Python microframeworkFlask - Python microframework
Flask - Python microframeworkAndré Mayer
 
Introduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORMIntroduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORMJason 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 WorkersNicola Iarocci
 
REST Web API with MongoDB
REST Web API with MongoDBREST Web API with MongoDB
REST Web API with MongoDBMongoDB
 
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 ScalabilitySanchit Gera
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flaskJim Yeh
 
Selenium testing
Selenium testingSelenium testing
Selenium testingJason Myers
 
Django channels
Django channelsDjango channels
Django channelsAndy Dai
 

Andere mochten auch (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)
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
 
Hands on django part 1
Hands on django part 1Hands on django part 1
Hands on django part 1
 
Fuga dalla Comfort Zone
Fuga dalla Comfort ZoneFuga dalla Comfort Zone
Fuga dalla Comfort Zone
 
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
 
CoderDojo Romagna
CoderDojo RomagnaCoderDojo Romagna
CoderDojo Romagna
 
Python Static Analysis Tools
Python Static Analysis ToolsPython Static Analysis Tools
Python Static Analysis Tools
 
Introduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsIntroduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic Migrations
 
Online / Offline
Online / OfflineOnline / Offline
Online / Offline
 
Coderfaire Data Networking for Developers
Coderfaire Data Networking for DevelopersCoderfaire Data Networking for Developers
Coderfaire Data Networking for Developers
 
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
 
Flask - Python microframework
Flask - Python microframeworkFlask - Python microframework
Flask - Python microframework
 
Introduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORMIntroduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORM
 
Eve - REST API for Humans™
Eve - REST API for Humans™Eve - REST API for Humans™
Eve - REST API for Humans™
 
We Are All Remote Workers
We Are All Remote WorkersWe Are All Remote Workers
We Are All Remote Workers
 
REST Web API with MongoDB
REST Web API with MongoDBREST Web API with MongoDB
REST Web API with 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
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
 
Selenium testing
Selenium testingSelenium testing
Selenium testing
 
Django channels
Django channelsDjango channels
Django channels
 

Ähnlich wie Intro python-object-protocol

Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Yung-Yu Chen
 
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 CSteffen Wenz
 
Pysmbc Python C Modules are Easy
Pysmbc Python C Modules are EasyPysmbc Python C Modules are Easy
Pysmbc Python C Modules are EasyRoberto Polli
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationGlobalLogic Ukraine
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonYi-Lung Tsai
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Scott Wlaschin
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts Pavan Babu .G
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Juan Pablo
 
#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And References#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And ReferencesHadziq Fabroyir
 
#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting StartedHadziq Fabroyir
 
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 doctrineFrankie Dintino
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerSrikanth Shreenivas
 
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologiesit-people
 
Improving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con BerlinImproving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con BerlinIain Hull
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++Khushal Mehta
 

Ähnlich wie Intro python-object-protocol (20)

Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020
 
Day 1
Day 1Day 1
Day 1
 
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
 
Pysmbc Python C Modules are Easy
Pysmbc Python C Modules are EasyPysmbc Python C Modules are Easy
Pysmbc Python C Modules are Easy
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python Integration
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded Python
 
C pythontalk
C pythontalkC pythontalk
C pythontalk
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And References#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And References
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started
 
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
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
 
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
 
Improving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con BerlinImproving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con Berlin
 
stacks and queues class 12 in c++
stacks and  queues class 12 in c++stacks and  queues class 12 in c++
stacks and queues class 12 in c++
 

Kürzlich hochgeladen

Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 

Kürzlich hochgeladen (20)

Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 

Intro python-object-protocol

  • 1. a smalltalk on Object and Protocol in CPython shiyao.ma <i@introo.me> 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] == ??