SlideShare a Scribd company logo
ADVANCED PYTHON
by Gyuri Horak
DIAMOND INHERITANCE PROBLEM
Cls.__mro__ - method resolution order
py> class A(object): pass
py> class B(A): pass
py> class C(A): pass
py> class D(B,C): pass
py> D.__mro__
(<class '__main__.D'>,
<class '__main__.B'>,
<class '__main__.C'>,
<class '__main__.A'>,
<type 'object'>)
MIXINS
You can add baseclasses runtime
class A(object): pass
class B(object): pass
class C(A): pass
py> C.__bases__ += (B,)
py> C.__mro__
(<class '__main__.C'>, <class '__main__.A'>,
<class '__main__.B'>, <type 'object'>)
VARIABLE SCOPE
● No declaration, just use any variable
whenever you want
● There's global but ...
● Namespaces are dicts
● module.submodule.variable = 42
● del keyword
● __builtins__, locals()
VARIABLE SCOPE
def scopetest(mut, imut):
global gvar
gvar = 11
lvar = 12
mut += [2]
imut += "apple"
print locals()
# {'mut': [1, 2], 'lvar': 12, 'imut': 'pineapple'}
gvar, lvar, amut, aimut = 1, 1, [1], "pine"
print locals()
# {'__builtins__': <..>, 'scopetest': <function ..>,
# '__file__': 'scope.py', 'amut': [1], 'gvar': 1,
# '__package__': None, 'lvar': 1, 'aimut': 'pine',
# '__name__': '__main__', '__doc__': None}
scopetest(amut, aimut)
print locals()
# {'__builtins__': <..>, 'scopetest': <function ..>,
# '__file__': 'scope.py', 'amut': [1, 2], 'gvar': 11,
# '__package__': None, 'lvar': 1, 'aimut': 'pine',
# '__name__': '__main__', '__doc__': None}
ITERATORS
● container.__iter__() -> iterator
● iterator.__iter__() -> iterator (self)
● iterator.next() -> next item, or StopIteration
exception
py> a = [1,2,3,4,5]
py> i = a.__iter__()
py> i.next()
1
py> i.next()
2
GENERATORS, YIELD
Generate the next item only when we need it
class Fib(object):
def __init__(self, limit):
self.limit = limit
def __iter__(self):
p0, p = 0, 1 # tuple pack/unpack
while p < self.limit:
yield p
p0, p = p, p+p0
raise StopIteration
py> f100 = Fib(100)
py> for x in f100:
... print x,
1 1 2 3 5 8 13 21 34 55 89
LIST COMPREHENSIONS
The functional way of list creation
py> [x+1 for x in f100]
[2, 2, 3, 4, 6, 9, 14, 22, 35, 56, 90]
In Python 3 dicts and sets can be created this
way as well
ITERTOOLS
Useful toolset for iterators
py> from itertools import izip
py> for x,y in izip(xrange(10), f100):
... print "(%s, %s)" % (x, y),
(0, 1) (1, 1) (2, 2) (3, 3) (4, 5) (5, 8) 
(6, 13) (7, 21) (8, 34) (9, 55)
COROUTINES (PEP-342)
def grep(pattern):
print "Looking for %s" % pattern
while True:
line = (yield)
if pattern in line:
print line
py> g = grep("python")
py> g.next()
py> g.send("No snakes here.")
py> g.send("Generators in python ROCK!")
Generators in python ROCK!
py> g.close()
OPERATOR OVERLOADING
class Fun(object):
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
return self.function(*args, **kwargs)
def __add__(self, funinst):
def inner(*args, **kwargs):
return funinst(self.function(*args, **kwargs))
return Fun(inner)
py> f1 = Fun(a)
py> f1(1,2) # 3
py> f2 = Fun(lambda x: x*x)
py> f2(2) # 4
py> f3 = f1+f2
py> f3(1,2) # 9
__gettattr__
class JSObj(dict):
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, attr, value):
self[attr] = value
py> o = JSObj({'a': 10, 'b': 20})
py> o.a # 10
py> o.c # None
py> o.c = 30
py> o['c'] # 30
py> o.c # 30
__dict__
class Borg(object):
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
py> a = Borg()
py> b = Borg()
py> a.x = 42
py> b.x
42
py> a == b
False
http://docs.python.org/reference/datamodel.html#special-method-names
NOTHING IS PRIVATE (AGAIN)
def hide(o):
class Proxy(object):
__slots__ = ()
def __getattr__(self, name):
return getattr(o, name)
return Proxy()
class A(object):
a = 42
py> a = hide(A())
py> a.a
42
py> a.a = 43
AttributeError: 'Proxy' object has no attribute 'a'
py> a.__getattr__.func_closure[0].cell_contents
<__main__.A object at 0x7faae6e16510>
DECORATORS
● syntactic sugar
● class decorators in Python 3
● functool.wraps helper - sets __name__, docstring, etc.
● @classmethod, @staticmethod
def funct(): pass
funct = decorator(funct)
@decorator
def funct(): pass
EXAMPLE DECORATOR
def logger(f):
def inner(*args, **kwargs):
print "%s called with arguments: %s; %s" % (f.__name__, args, kwargs)
retval = f(*args, **kwargs)
print "%s returned: %s" % (f.__name__, retval)
return retval
return inner
@logger
def mul(a,b):
return a*b
py> mul(1,2)
mul called with arguments: (1, 2); {}
mul returned: 2
DESCRIPTORS
● to "hide" getter/setter methods
○ __get__(self, instance, owner)
○ __set__(self, instance, value)
○ __delete__(self, instance)
● functions are descriptors (with __get__), late binding is possible
PROPERTIES
class PropEx(object):
__a = 1
__b = 2
@property
def c(self):
return self.__a + self.__b
def getA(self): return self.__a
def setA(self, value): self.__a = value
def delA(self): self.__a = 1
a = property(getA, setA, delA)
# @property, @m.setter, @m.deleter
py> x = PropEx()
py> x.a = 12
py> x.c
14
py> x.__class__.__dict__['a'].fset
<function setA at 0x7ff241c266e0>
FUNCTIONS / METHODS
def myclass(self):
return self.__class__
class A(object):
def method(self):
pass
py> a = A(); a.__class__.__dict__['method']
<function method at 0x7ff241c26cf8>
py> a.__class__.method
<unbound method A.method>
py> a.method
<bound method A.method of <__main__.A object at 0x7ff242d56bd0>>
py> a.myclass = myclass; a.myclass()
TypeError: myclass() takes exactly 1 argument (0 given) # ???
py> a.myclass
<function myclass at 0x7ff241c26b18> # :(
py> a.myclass = myclass.__get__(a, A); a.myclass()
<class '__main__.A'>
py> a.myclass
<bound method A.myclass of <__main__.A object at 0x7ff242d56bd0>> # :)
type()
● function: returns the type of the argument
● but it's a type too
● moreover it's the root of all classes
py> type(object)
<type 'type'>
py> type(type)
<type 'type'>
● AND it can create new classes runtime
METAPROGRAMMING
def constr(self):
print "new instance created"
self.foo = "foo"
def method(self):
print "foo: " + self.foo
py> MyClass = type("MyClass", # classname
(dict, object), # baseclasses
{'PI': 3.14, # __dict__
'method': method,
'__init__': constr})
py> myinstance = MyClass()
new instance created
py> myinstance.method()
foo: foo
__metaclass__
When defined, it is called instead of type at class generation
class mymeta(type):
def __new__(mcs, name, bases, dict):
dict['myprop'] = 'metaclass property'
return type.__new__(mcs, name, bases, dict)
class A(object):
__metaclass__ = mymeta
py> a = A()
py> a.myprop
'metaclass property'
You can do _anything_ here, like type checking based on docstrings (or py3 annotations), decorating all the methods, create
mixins ...

More Related Content

What's hot

Python decorators (中文)
Python decorators (中文)Python decorators (中文)
Python decorators (中文)
Yiwei Chen
 
Python decorators
Python decoratorsPython decorators
Python decoratorsAlex Su
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
Bryan Helmig
 
Don't do this
Don't do thisDon't do this
Don't do this
Richard Jones
 
The Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in PythonThe Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in Python
OSCON Byrum
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
ESUG
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Samuel Fortier-Galarneau
 
C++ L01-Variables
C++ L01-VariablesC++ L01-Variables
C++ L01-Variables
Mohammad Shaker
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
kwatch
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in PythonBen James
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
Bruno Scopelliti
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
Christian Baranowski
 
Python decorators
Python decoratorsPython decorators
Python decorators
Guillermo Blasco Jiménez
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the world
David Muñoz Díaz
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수
용 최
 
Why rust?
Why rust?Why rust?
Why rust?
Mats Kindahl
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
Mohammad Shaker
 
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Codemotion
 
Zope component architechture
Zope component architechtureZope component architechture
Zope component architechture
Anatoly Bubenkov
 

What's hot (20)

Python decorators (中文)
Python decorators (中文)Python decorators (中文)
Python decorators (中文)
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
Don't do this
Don't do thisDon't do this
Don't do this
 
The Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in PythonThe Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in Python
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
 
C++ L01-Variables
C++ L01-VariablesC++ L01-Variables
C++ L01-Variables
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the world
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수
 
Why rust?
Why rust?Why rust?
Why rust?
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
 
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
 
Zope component architechture
Zope component architechtureZope component architechture
Zope component architechture
 

Similar to Advanced python

Pybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonPybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in Python
Christoph Matthies
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examples
Robert Lujo
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
Fwdays
 
Why you should use super() though it sucks
Why you should use super() though it sucksWhy you should use super() though it sucks
Why you should use super() though it sucks
Eunchong Yu
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
Nandan Sawant
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
Python Ireland
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
Michael Pirnat
 
I regret nothing
I regret nothingI regret nothing
I regret nothing
Łukasz Langa
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
Zsolt Mészárovics
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonTendayi Mawushe
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions
Dr. Volkan OBAN
 
Python Cheat Sheet Presentation Learning
Python Cheat Sheet Presentation LearningPython Cheat Sheet Presentation Learning
Python Cheat Sheet Presentation Learning
Naseer-ul-Hassan Rehman
 
Introduction to julia
Introduction to juliaIntroduction to julia
Introduction to julia
岳華 杜
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
Simone Federici
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
decoupled
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
Aleksandar Veselinovic
 
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 AutumnGoptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
Masashi Shibata
 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia
岳華 杜
 
using python module: doctest
using python module: doctestusing python module: doctest
using python module: doctest
mitnk
 

Similar to Advanced python (20)

Pybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonPybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in Python
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examples
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Why you should use super() though it sucks
Why you should use super() though it sucksWhy you should use super() though it sucks
Why you should use super() though it sucks
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
I regret nothing
I regret nothingI regret nothing
I regret nothing
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions ggtimeseries-->ggplot2 extensions
ggtimeseries-->ggplot2 extensions
 
Python Cheat Sheet Presentation Learning
Python Cheat Sheet Presentation LearningPython Cheat Sheet Presentation Learning
Python Cheat Sheet Presentation Learning
 
Introduction to julia
Introduction to juliaIntroduction to julia
Introduction to julia
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 AutumnGoptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia
 
using python module: doctest
using python module: doctestusing python module: doctest
using python module: doctest
 

More from EU Edge

Synchronization with CouchDB and PouchDB
Synchronization with CouchDB and PouchDBSynchronization with CouchDB and PouchDB
Synchronization with CouchDB and PouchDB
EU Edge
 
How I learned to Stop Worrying and Love the inline-block
How I learned to Stop Worrying and Love the inline-blockHow I learned to Stop Worrying and Love the inline-block
How I learned to Stop Worrying and Love the inline-blockEU Edge
 
What is python
What is pythonWhat is python
What is pythonEU Edge
 
Python alapu mobil backend
Python alapu mobil backendPython alapu mobil backend
Python alapu mobil backendEU Edge
 
Res tful services
Res tful servicesRes tful services
Res tful servicesEU Edge
 
Google glass a developers perspective
Google glass   a developers perspectiveGoogle glass   a developers perspective
Google glass a developers perspectiveEU Edge
 
Google glass ict day presentation
Google glass   ict day presentationGoogle glass   ict day presentation
Google glass ict day presentationEU Edge
 
How does it work the keyboard
How does it work   the keyboardHow does it work   the keyboard
How does it work the keyboardEU Edge
 
Node webkit-meetup
Node webkit-meetupNode webkit-meetup
Node webkit-meetupEU Edge
 
Frontend meetup 2014.06.25
Frontend meetup 2014.06.25Frontend meetup 2014.06.25
Frontend meetup 2014.06.25EU Edge
 
Eu edge intro
Eu edge introEu edge intro
Eu edge introEU Edge
 
Halado css eu edge
Halado css   eu edgeHalado css   eu edge
Halado css eu edgeEU Edge
 
Miért jó oktatóanyagot készíteni?
Miért jó oktatóanyagot készíteni?Miért jó oktatóanyagot készíteni?
Miért jó oktatóanyagot készíteni?EU Edge
 

More from EU Edge (16)

Synchronization with CouchDB and PouchDB
Synchronization with CouchDB and PouchDBSynchronization with CouchDB and PouchDB
Synchronization with CouchDB and PouchDB
 
How I learned to Stop Worrying and Love the inline-block
How I learned to Stop Worrying and Love the inline-blockHow I learned to Stop Worrying and Love the inline-block
How I learned to Stop Worrying and Love the inline-block
 
Node.js
Node.jsNode.js
Node.js
 
What is python
What is pythonWhat is python
What is python
 
WebGL
WebGLWebGL
WebGL
 
Python alapu mobil backend
Python alapu mobil backendPython alapu mobil backend
Python alapu mobil backend
 
Res tful services
Res tful servicesRes tful services
Res tful services
 
Open gl
Open glOpen gl
Open gl
 
Google glass a developers perspective
Google glass   a developers perspectiveGoogle glass   a developers perspective
Google glass a developers perspective
 
Google glass ict day presentation
Google glass   ict day presentationGoogle glass   ict day presentation
Google glass ict day presentation
 
How does it work the keyboard
How does it work   the keyboardHow does it work   the keyboard
How does it work the keyboard
 
Node webkit-meetup
Node webkit-meetupNode webkit-meetup
Node webkit-meetup
 
Frontend meetup 2014.06.25
Frontend meetup 2014.06.25Frontend meetup 2014.06.25
Frontend meetup 2014.06.25
 
Eu edge intro
Eu edge introEu edge intro
Eu edge intro
 
Halado css eu edge
Halado css   eu edgeHalado css   eu edge
Halado css eu edge
 
Miért jó oktatóanyagot készíteni?
Miért jó oktatóanyagot készíteni?Miért jó oktatóanyagot készíteni?
Miért jó oktatóanyagot készíteni?
 

Recently uploaded

Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Nidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, TipsNidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, Tips
vrstrong314
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 

Recently uploaded (20)

Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Nidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, TipsNidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, Tips
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 

Advanced python

  • 2. DIAMOND INHERITANCE PROBLEM Cls.__mro__ - method resolution order py> class A(object): pass py> class B(A): pass py> class C(A): pass py> class D(B,C): pass py> D.__mro__ (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
  • 3. MIXINS You can add baseclasses runtime class A(object): pass class B(object): pass class C(A): pass py> C.__bases__ += (B,) py> C.__mro__ (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>)
  • 4. VARIABLE SCOPE ● No declaration, just use any variable whenever you want ● There's global but ... ● Namespaces are dicts ● module.submodule.variable = 42 ● del keyword ● __builtins__, locals()
  • 5. VARIABLE SCOPE def scopetest(mut, imut): global gvar gvar = 11 lvar = 12 mut += [2] imut += "apple" print locals() # {'mut': [1, 2], 'lvar': 12, 'imut': 'pineapple'} gvar, lvar, amut, aimut = 1, 1, [1], "pine" print locals() # {'__builtins__': <..>, 'scopetest': <function ..>, # '__file__': 'scope.py', 'amut': [1], 'gvar': 1, # '__package__': None, 'lvar': 1, 'aimut': 'pine', # '__name__': '__main__', '__doc__': None} scopetest(amut, aimut) print locals() # {'__builtins__': <..>, 'scopetest': <function ..>, # '__file__': 'scope.py', 'amut': [1, 2], 'gvar': 11, # '__package__': None, 'lvar': 1, 'aimut': 'pine', # '__name__': '__main__', '__doc__': None}
  • 6. ITERATORS ● container.__iter__() -> iterator ● iterator.__iter__() -> iterator (self) ● iterator.next() -> next item, or StopIteration exception py> a = [1,2,3,4,5] py> i = a.__iter__() py> i.next() 1 py> i.next() 2
  • 7. GENERATORS, YIELD Generate the next item only when we need it class Fib(object): def __init__(self, limit): self.limit = limit def __iter__(self): p0, p = 0, 1 # tuple pack/unpack while p < self.limit: yield p p0, p = p, p+p0 raise StopIteration py> f100 = Fib(100) py> for x in f100: ... print x, 1 1 2 3 5 8 13 21 34 55 89
  • 8. LIST COMPREHENSIONS The functional way of list creation py> [x+1 for x in f100] [2, 2, 3, 4, 6, 9, 14, 22, 35, 56, 90] In Python 3 dicts and sets can be created this way as well
  • 9. ITERTOOLS Useful toolset for iterators py> from itertools import izip py> for x,y in izip(xrange(10), f100): ... print "(%s, %s)" % (x, y), (0, 1) (1, 1) (2, 2) (3, 3) (4, 5) (5, 8) (6, 13) (7, 21) (8, 34) (9, 55)
  • 10. COROUTINES (PEP-342) def grep(pattern): print "Looking for %s" % pattern while True: line = (yield) if pattern in line: print line py> g = grep("python") py> g.next() py> g.send("No snakes here.") py> g.send("Generators in python ROCK!") Generators in python ROCK! py> g.close()
  • 11. OPERATOR OVERLOADING class Fun(object): def __init__(self, function): self.function = function def __call__(self, *args, **kwargs): return self.function(*args, **kwargs) def __add__(self, funinst): def inner(*args, **kwargs): return funinst(self.function(*args, **kwargs)) return Fun(inner) py> f1 = Fun(a) py> f1(1,2) # 3 py> f2 = Fun(lambda x: x*x) py> f2(2) # 4 py> f3 = f1+f2 py> f3(1,2) # 9
  • 12. __gettattr__ class JSObj(dict): def __getattr__(self, attr): return self.get(attr) def __setattr__(self, attr, value): self[attr] = value py> o = JSObj({'a': 10, 'b': 20}) py> o.a # 10 py> o.c # None py> o.c = 30 py> o['c'] # 30 py> o.c # 30
  • 13. __dict__ class Borg(object): __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state py> a = Borg() py> b = Borg() py> a.x = 42 py> b.x 42 py> a == b False http://docs.python.org/reference/datamodel.html#special-method-names
  • 14. NOTHING IS PRIVATE (AGAIN) def hide(o): class Proxy(object): __slots__ = () def __getattr__(self, name): return getattr(o, name) return Proxy() class A(object): a = 42 py> a = hide(A()) py> a.a 42 py> a.a = 43 AttributeError: 'Proxy' object has no attribute 'a' py> a.__getattr__.func_closure[0].cell_contents <__main__.A object at 0x7faae6e16510>
  • 15. DECORATORS ● syntactic sugar ● class decorators in Python 3 ● functool.wraps helper - sets __name__, docstring, etc. ● @classmethod, @staticmethod def funct(): pass funct = decorator(funct) @decorator def funct(): pass
  • 16. EXAMPLE DECORATOR def logger(f): def inner(*args, **kwargs): print "%s called with arguments: %s; %s" % (f.__name__, args, kwargs) retval = f(*args, **kwargs) print "%s returned: %s" % (f.__name__, retval) return retval return inner @logger def mul(a,b): return a*b py> mul(1,2) mul called with arguments: (1, 2); {} mul returned: 2
  • 17. DESCRIPTORS ● to "hide" getter/setter methods ○ __get__(self, instance, owner) ○ __set__(self, instance, value) ○ __delete__(self, instance) ● functions are descriptors (with __get__), late binding is possible
  • 18. PROPERTIES class PropEx(object): __a = 1 __b = 2 @property def c(self): return self.__a + self.__b def getA(self): return self.__a def setA(self, value): self.__a = value def delA(self): self.__a = 1 a = property(getA, setA, delA) # @property, @m.setter, @m.deleter py> x = PropEx() py> x.a = 12 py> x.c 14 py> x.__class__.__dict__['a'].fset <function setA at 0x7ff241c266e0>
  • 19. FUNCTIONS / METHODS def myclass(self): return self.__class__ class A(object): def method(self): pass py> a = A(); a.__class__.__dict__['method'] <function method at 0x7ff241c26cf8> py> a.__class__.method <unbound method A.method> py> a.method <bound method A.method of <__main__.A object at 0x7ff242d56bd0>> py> a.myclass = myclass; a.myclass() TypeError: myclass() takes exactly 1 argument (0 given) # ??? py> a.myclass <function myclass at 0x7ff241c26b18> # :( py> a.myclass = myclass.__get__(a, A); a.myclass() <class '__main__.A'> py> a.myclass <bound method A.myclass of <__main__.A object at 0x7ff242d56bd0>> # :)
  • 20. type() ● function: returns the type of the argument ● but it's a type too ● moreover it's the root of all classes py> type(object) <type 'type'> py> type(type) <type 'type'> ● AND it can create new classes runtime
  • 21. METAPROGRAMMING def constr(self): print "new instance created" self.foo = "foo" def method(self): print "foo: " + self.foo py> MyClass = type("MyClass", # classname (dict, object), # baseclasses {'PI': 3.14, # __dict__ 'method': method, '__init__': constr}) py> myinstance = MyClass() new instance created py> myinstance.method() foo: foo
  • 22. __metaclass__ When defined, it is called instead of type at class generation class mymeta(type): def __new__(mcs, name, bases, dict): dict['myprop'] = 'metaclass property' return type.__new__(mcs, name, bases, dict) class A(object): __metaclass__ = mymeta py> a = A() py> a.myprop 'metaclass property' You can do _anything_ here, like type checking based on docstrings (or py3 annotations), decorating all the methods, create mixins ...