Functions in python

Ilian Iliev
Ilian IlievSoftware Engineer at Lifesum
Functions in Python

arguments, lambdas, decorators, generators
Defining simple functions:
>>> def my_func():
... print "Inside my function"
...
>>> my_func()
Inside my function
Function with arguments - basics
>>> def func_with_args(a, b):
... print 'a: ', a
... print 'b: ', b
...
>>> func_with_args(5, 'c')
a: 5
b: c
Two types of arguments
● positional - arguments order matters
     >>> func_with_args(5, 'c')
     a: 5
     b: c
● keyword - argument name matters
     func_with_args(b=5, a='c')
     a: c
     b: 5
Mixing position and keyword
arguments
>>> def func_with_args(a, b, c):
... print a, b, c
...

>>> func_with_args(1, c=3, b=2)
123

>>> func_with_args(a=1, 3, b=2)
 File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
Passing attributes - old style
>>> func_with_args(1, 2, 3) # standart call
123

>>> apply(func_with_args, [1, 2, 3]) # positional
123

>>> apply(func_with_args, [], {'a': 1, 'c': 3, 'b': 2}) # keywords
123

>>> apply(func_with_args, [1], {'c': 3, 'b': 2}) # mixed
123
Passing attributes - new style
>>> func_with_args(*[1, 2, 3]) # positional
123

>>> func_with_args(**{'b': 2, 'a': '1', 'c': 3}) # keywords
123

>>> func_with_args(*[1], **{'b': 2, 'c': 3}) # mixed
123

>>> func_with_args(*[1], **{'b': 2, 'a': '1', 'c': 3})
TypeError: func_with_args() got multiple values for keyword
argument 'a'
Function arguments revisited
>>> def f(*args, **kwargs):
... print args
... print kwargs

>>> f()
()
{}
>>> f(1,2,3)
(1, 2, 3)
{}
>>> f(a=1, c=3, b=2)
()
{'a': 1, 'c': 3, 'b': 2}
>>> f(1, b=2, c=3)
(1,)
{'c': 3, 'b': 2}
Default arguments
>>> def func(a=5):
... print a

>>> func()
5

>>> func(6)
6

>>> func()
5
Default arguments - part II
>>> def func(a=[]):
... print a

>>> func()
[]

>>> func(['a'])
['a']

>>> func()
[]
Default arguments - part III
>>> def func(a=[]):
... a = a * 5
... print a
>>> func()
[]
>>> func()
[]
>>> func([1])
[1, 1, 1, 1, 1]
>>> func()
[]
Default arguments - part IV - problem
>>> def func(a=[]):
... a.append(2)
... print a

>>> func()
[2]
>>> func()
[2, 2]
>>> func([1])
[1, 2]
>>> func()
[2, 2, 2]
Default arguments - part V - solution
>>> def func(a=None):
... a = a or []
... a.append(2)
... print a
...

>>> func()
[2]

>>> func()
[2]
Preloading arguments
>>> def func(a, b, c):
... print a, b, c

>>> import functools
>>> func_preloader = functools.partial(func, a=5, c=3)
>>> func_preloader()
TypeError: func() takes exactly 3 arguments (2 given)

>>> func_preloader(b=2)
523
Preloading arguments - mixing
>>> def func(a, b, c):
... print a, b, c

>>> import functools
>>> func_preloader = functools.partial(func, a=5, c=3)

>>> func_preloader(2)
TypeError: func() got multiple values for keyword argument 'a'
Python introspection


""" In computing, type introspection is the ability of a
program to examine the type or properties of an object
at runtime. """

                           Wikipedia - Type Introspection
Introspection basics
>>> def func(a, b, c):
... """ Just an example how introspection works """
... pass

>>> help(func)
Help on function func in module __main__:
func(a, b, c)
  Just an example how introspection works
Methods related to introspection
● type(var) # show the type of the object
● dir(var) # lists object's methods and attributes
● id(var) # return object specific identificator
● getattr(obj, <attribute name>, <default value>)
● hasattr(obj, <attribute name>)
● globals()
● locals()
● callable(obj) # returns True if the object is callable
Lambda functions
>>> f = lambda x,y: x+y
>>> f(1,2)
3

>>> f = lambda x,y=[]: x+y
>>> f([1])
[1]

>>> f([1], [2])
[1, 2]
Lambdas and print
# Python 2.7.3
>>> a = lambda x: print x # print is a statement
 File "<stdin>", line 1
  a = lambda x: print x

Lambdas can not contain statements

# Python 3.2.3
>>> f = lambda x: print(x) # print is a function
>>> f(5)
5
Lambdas usage
>>> map(lambda x: x**2, range(5))
[0, 1, 4, 9, 16]

>>> [x**2 for x in range(5)]
[0, 1, 4, 9, 16]

>>> reduce(lambda a, x: a+x, range(5))
10

Avoid using lambdas and check Guido van Rossum's vision
for lambdas http://www.artima.com/weblogs/viewpost.jsp?thread=98196
Generators
yield x # Generator function send protocol
>>> def a():
... yield 5
... yield 6
... yield 7

>>> a()
<generator object a at 0x158caa0>

>>> a()
<generator object a at 0x158caa0>
Generators - range vs xrange
>>> range(10**10)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
MemoryError

>>> xrange(10**10)
xrange(10000000000)

# range has been replaced by xrange in Python 3.x
Creating generators
>>> def fib():
... a, b = 0, 1
... while True:
...    yield a, b
...    a, b = b, a+b
...
>>> g = fib()
>>> g
<generator object fib at 0x19b4be0>
Creating generators
>>> g.next()
(0, 1)
>>> g.next()
(1, 1)
>>> g.next()
(1, 2)
>>> g.next()
(2, 3)
Exhausting generators
>>> def cubes(n):
... for i in range(n):
...      yield i**3
>>> c = cubes(3)
>>> c.next() # 0
>>> c.next() # 1
>>> c.next() # 8
>>> c.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
Generators and comprehension lists
>>> def cubes(n):
... for i in range(n):
...      yield i**3
...
>>> [a for a in cubes(3)]
[0, 1, 8]
Generators and the send method
>>> def waiting_for_input():
... i = 0
... while True:
...     i = yield i**3
...
>>> f = waiting_for_input()
>>> f.next() # 0
>>> f.send(8) # 512
>>> f.send(10) # 1000
>>> f.send(12) # 1728
Decorators
>>> def decorator(func):
... print 'Entering decorator'
... return func
...
>>> @decorator
... def f():
... print 'Executing F'
...
Entering decorator
>>> f()
Executing F
Decorators simplified
>>> def decorator(func):
... print 'Entering decorator'
... return func
...
>>> @decorator
... def f():
... print 'Executing F'

# Using the decorator above is the same as using:
>>> f = decorator(f)
Functions as Decorators
>>> def decorator(func):
... def wrap():
...       print 'Calling function %s' % func.__name__
...       func()
...       print 'Exiting decorator'
... return wrap
...
>>> @decorator
... def f():
... print 'Executing F'
...
>>> f()
Calling function f
Executing F
Exiting decorator
Functions as decorators - part II
>>> def decorator(func):
... def wrap(a, b, c):
...       print 'Function f called with %s, %s, %s' % (a, b, c)
...       return func(a, b, c)
... return wrap
...
>>> @decorator
... def f(a, b, c):
... return a + b + c
...
>>> f(1, 2, 3)
Function f called with 1, 2, 3
6
Classes as decorators
>>> class decorator(object):
... def __init__(self, func):
...       print 'Initializing decorator'
...       self.func = func
... def __call__(self, *args, **kwargs):
...       print 'Calling method'
...       return self.func(*args, **kwargs)
>>> @decorator
... def f(a, b, c):
... return a + b + c
...
Initializing decorator
>>> f(1, 2, 3)
Calling method
6
Decorators with arguments
>>> def decorator(debug=False):
... def wrap(func):
...    def f_wrap(a, b, c):
...       if debug:
...           print 'Function f called with %s, %s, %s' % (a,
b, c)
...       return func(a, b, c)
...    return f_wrap
... return wrap
Decorators with arguments
>>> @decorator(debug=True)
... def f(a, b, c):
... return a + b + c
...
>>> f(1, 2, 3)
Function f called with 1, 2, 3
6

>>> @decorator(debug=False)
... def f(a, b, c):
... return a + b + c
...
>>> f(1, 2, 3)
6
Q&A
Problems to solve
1) Create a function that accept both positional and
keyword arguments and returns their sum

2) Create a generator that implements a dice that "brokes"
after the 10th roll

3) Create a decorator that converts letters to number
according to their position in the alphabet and combine it
with the solution of problem #1. When converting letters to
numbers make them lowercase and count from 0 i.e. a==0,
b==1.
About Me
eng. Ilian Iliev

●   Web Developer for 9+ years
●   Python/Django fan for 3+ years
●   ilian@i-n-i.org
●   http://ilian.i-n-i.org
●   https://github.com/IlianIliev/
1 of 38

Recommended

Python Functions (PyAtl Beginners Night) by
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Rick Copeland
2.4K views97 slides
Functions by
FunctionsFunctions
FunctionsMarieswaran Ramasamy
2.3K views87 slides
Introduction to python by
Introduction to pythonIntroduction to python
Introduction to pythonMarian Marinov
427 views41 slides
Python programing by
Python programingPython programing
Python programinghamzagame
144 views90 slides
Python by
PythonPython
PythonSameeksha Verma
116 views57 slides

More Related Content

What's hot

Python course Day 1 by
Python course Day 1Python course Day 1
Python course Day 1Karin Lagesen
1.3K views38 slides
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE by
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEVenugopalavarma Raja
533 views95 slides
python Function by
python Function python Function
python Function Ronak Rathi
6.5K views20 slides
Python Programming: Data Structure by
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data StructureChan Shik Lim
337 views49 slides
The Ring programming language version 1.7 book - Part 35 of 196 by
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196Mahmoud Samir Fayed
18 views10 slides
Python легко и просто. Красиво решаем повседневные задачи by
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиMaxim Kulsha
1.3K views48 slides

What's hot(20)

python Function by Ronak Rathi
python Function python Function
python Function
Ronak Rathi6.5K views
Python Programming: Data Structure by Chan Shik Lim
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
Chan Shik Lim337 views
The Ring programming language version 1.7 book - Part 35 of 196 by Mahmoud Samir Fayed
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196
Python легко и просто. Красиво решаем повседневные задачи by Maxim Kulsha
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
Maxim Kulsha1.3K views
Matlab and Python: Basic Operations by Wai Nwe Tun
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic Operations
Wai Nwe Tun155 views
Basics of Python programming (part 2) by Pedro Rodrigues
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
Pedro Rodrigues494 views
GE8151 Problem Solving and Python Programming by Muthu Vinayagam
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam1.8K views
Python fundamentals - basic | WeiYuan by Wei-Yuan Chang
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang908 views
Python Puzzlers - 2016 Edition by Nandan Sawant
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
Nandan Sawant6.3K views
Learn 90% of Python in 90 Minutes by Matt Harrison
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
Matt Harrison319.7K views
Very basic functional design patterns by Tomasz Kowal
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
Tomasz Kowal820 views
Python programming: Anonymous functions, String operations by Megha V
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha V211 views

Similar to Functions in python

PythonOOP by
PythonOOPPythonOOP
PythonOOPVeera Pendyala
907 views157 slides
Functional Programming inside OOP? It’s possible with Python by
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonCarlos V.
130 views38 slides
Funkcija, objekt, python by
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, pythonRobert Lujo
1.3K views42 slides
Py3k by
Py3kPy3k
Py3kAndrew Svetlov
1.3K views20 slides
An overview of Python 2.7 by
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
248 views42 slides
A tour of Python by
A tour of PythonA tour of Python
A tour of PythonAleksandar Veselinovic
1.1K views42 slides

Similar to Functions in python(20)

Functional Programming inside OOP? It’s possible with Python by Carlos V.
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
Carlos V.130 views
Funkcija, objekt, python by Robert Lujo
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
Robert Lujo1.3K views
An overview of Python 2.7 by decoupled
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
decoupled248 views
Python 내장 함수 by 용 최
Python 내장 함수Python 내장 함수
Python 내장 함수
용 최2.4K views
Python Training v2 by ibaydan
Python Training v2Python Training v2
Python Training v2
ibaydan626 views
Python 표준 라이브러리 by 용 최
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
용 최6.9K views
Palestra sobre Collections com Python by pugpe
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
pugpe1.5K views
Chapter 02 functions -class xii by praveenjigajinni
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
praveenjigajinni21.5K views
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt. by Samuel Fortier-Galarneau
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.
Pres_python_talakhoury_26_09_2023.pdf by RamziFeghali
Pres_python_talakhoury_26_09_2023.pdfPres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdf
RamziFeghali10 views
Slide PF Pertemuan 2.pptx by LucidAxel
Slide PF Pertemuan 2.pptxSlide PF Pertemuan 2.pptx
Slide PF Pertemuan 2.pptx
LucidAxel3 views
Functional programming from its fundamentals by Mauro Palsgraaf
Functional programming from its fundamentalsFunctional programming from its fundamentals
Functional programming from its fundamentals
Mauro Palsgraaf387 views
Python lambda functions with filter, map & reduce function by ARVIND PANDE
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
ARVIND PANDE270 views
Functors, applicatives, monads by rkaippully
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
rkaippully356 views

Functions in python

  • 1. Functions in Python arguments, lambdas, decorators, generators
  • 2. Defining simple functions: >>> def my_func(): ... print "Inside my function" ... >>> my_func() Inside my function
  • 3. Function with arguments - basics >>> def func_with_args(a, b): ... print 'a: ', a ... print 'b: ', b ... >>> func_with_args(5, 'c') a: 5 b: c
  • 4. Two types of arguments ● positional - arguments order matters >>> func_with_args(5, 'c') a: 5 b: c ● keyword - argument name matters func_with_args(b=5, a='c') a: c b: 5
  • 5. Mixing position and keyword arguments >>> def func_with_args(a, b, c): ... print a, b, c ... >>> func_with_args(1, c=3, b=2) 123 >>> func_with_args(a=1, 3, b=2) File "<stdin>", line 1 SyntaxError: non-keyword arg after keyword arg
  • 6. Passing attributes - old style >>> func_with_args(1, 2, 3) # standart call 123 >>> apply(func_with_args, [1, 2, 3]) # positional 123 >>> apply(func_with_args, [], {'a': 1, 'c': 3, 'b': 2}) # keywords 123 >>> apply(func_with_args, [1], {'c': 3, 'b': 2}) # mixed 123
  • 7. Passing attributes - new style >>> func_with_args(*[1, 2, 3]) # positional 123 >>> func_with_args(**{'b': 2, 'a': '1', 'c': 3}) # keywords 123 >>> func_with_args(*[1], **{'b': 2, 'c': 3}) # mixed 123 >>> func_with_args(*[1], **{'b': 2, 'a': '1', 'c': 3}) TypeError: func_with_args() got multiple values for keyword argument 'a'
  • 8. Function arguments revisited >>> def f(*args, **kwargs): ... print args ... print kwargs >>> f() () {} >>> f(1,2,3) (1, 2, 3) {} >>> f(a=1, c=3, b=2) () {'a': 1, 'c': 3, 'b': 2} >>> f(1, b=2, c=3) (1,) {'c': 3, 'b': 2}
  • 9. Default arguments >>> def func(a=5): ... print a >>> func() 5 >>> func(6) 6 >>> func() 5
  • 10. Default arguments - part II >>> def func(a=[]): ... print a >>> func() [] >>> func(['a']) ['a'] >>> func() []
  • 11. Default arguments - part III >>> def func(a=[]): ... a = a * 5 ... print a >>> func() [] >>> func() [] >>> func([1]) [1, 1, 1, 1, 1] >>> func() []
  • 12. Default arguments - part IV - problem >>> def func(a=[]): ... a.append(2) ... print a >>> func() [2] >>> func() [2, 2] >>> func([1]) [1, 2] >>> func() [2, 2, 2]
  • 13. Default arguments - part V - solution >>> def func(a=None): ... a = a or [] ... a.append(2) ... print a ... >>> func() [2] >>> func() [2]
  • 14. Preloading arguments >>> def func(a, b, c): ... print a, b, c >>> import functools >>> func_preloader = functools.partial(func, a=5, c=3) >>> func_preloader() TypeError: func() takes exactly 3 arguments (2 given) >>> func_preloader(b=2) 523
  • 15. Preloading arguments - mixing >>> def func(a, b, c): ... print a, b, c >>> import functools >>> func_preloader = functools.partial(func, a=5, c=3) >>> func_preloader(2) TypeError: func() got multiple values for keyword argument 'a'
  • 16. Python introspection """ In computing, type introspection is the ability of a program to examine the type or properties of an object at runtime. """ Wikipedia - Type Introspection
  • 17. Introspection basics >>> def func(a, b, c): ... """ Just an example how introspection works """ ... pass >>> help(func) Help on function func in module __main__: func(a, b, c) Just an example how introspection works
  • 18. Methods related to introspection ● type(var) # show the type of the object ● dir(var) # lists object's methods and attributes ● id(var) # return object specific identificator ● getattr(obj, <attribute name>, <default value>) ● hasattr(obj, <attribute name>) ● globals() ● locals() ● callable(obj) # returns True if the object is callable
  • 19. Lambda functions >>> f = lambda x,y: x+y >>> f(1,2) 3 >>> f = lambda x,y=[]: x+y >>> f([1]) [1] >>> f([1], [2]) [1, 2]
  • 20. Lambdas and print # Python 2.7.3 >>> a = lambda x: print x # print is a statement File "<stdin>", line 1 a = lambda x: print x Lambdas can not contain statements # Python 3.2.3 >>> f = lambda x: print(x) # print is a function >>> f(5) 5
  • 21. Lambdas usage >>> map(lambda x: x**2, range(5)) [0, 1, 4, 9, 16] >>> [x**2 for x in range(5)] [0, 1, 4, 9, 16] >>> reduce(lambda a, x: a+x, range(5)) 10 Avoid using lambdas and check Guido van Rossum's vision for lambdas http://www.artima.com/weblogs/viewpost.jsp?thread=98196
  • 22. Generators yield x # Generator function send protocol >>> def a(): ... yield 5 ... yield 6 ... yield 7 >>> a() <generator object a at 0x158caa0> >>> a() <generator object a at 0x158caa0>
  • 23. Generators - range vs xrange >>> range(10**10) Traceback (most recent call last): File "<stdin>", line 1, in <module> MemoryError >>> xrange(10**10) xrange(10000000000) # range has been replaced by xrange in Python 3.x
  • 24. Creating generators >>> def fib(): ... a, b = 0, 1 ... while True: ... yield a, b ... a, b = b, a+b ... >>> g = fib() >>> g <generator object fib at 0x19b4be0>
  • 25. Creating generators >>> g.next() (0, 1) >>> g.next() (1, 1) >>> g.next() (1, 2) >>> g.next() (2, 3)
  • 26. Exhausting generators >>> def cubes(n): ... for i in range(n): ... yield i**3 >>> c = cubes(3) >>> c.next() # 0 >>> c.next() # 1 >>> c.next() # 8 >>> c.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
  • 27. Generators and comprehension lists >>> def cubes(n): ... for i in range(n): ... yield i**3 ... >>> [a for a in cubes(3)] [0, 1, 8]
  • 28. Generators and the send method >>> def waiting_for_input(): ... i = 0 ... while True: ... i = yield i**3 ... >>> f = waiting_for_input() >>> f.next() # 0 >>> f.send(8) # 512 >>> f.send(10) # 1000 >>> f.send(12) # 1728
  • 29. Decorators >>> def decorator(func): ... print 'Entering decorator' ... return func ... >>> @decorator ... def f(): ... print 'Executing F' ... Entering decorator >>> f() Executing F
  • 30. Decorators simplified >>> def decorator(func): ... print 'Entering decorator' ... return func ... >>> @decorator ... def f(): ... print 'Executing F' # Using the decorator above is the same as using: >>> f = decorator(f)
  • 31. Functions as Decorators >>> def decorator(func): ... def wrap(): ... print 'Calling function %s' % func.__name__ ... func() ... print 'Exiting decorator' ... return wrap ... >>> @decorator ... def f(): ... print 'Executing F' ... >>> f() Calling function f Executing F Exiting decorator
  • 32. Functions as decorators - part II >>> def decorator(func): ... def wrap(a, b, c): ... print 'Function f called with %s, %s, %s' % (a, b, c) ... return func(a, b, c) ... return wrap ... >>> @decorator ... def f(a, b, c): ... return a + b + c ... >>> f(1, 2, 3) Function f called with 1, 2, 3 6
  • 33. Classes as decorators >>> class decorator(object): ... def __init__(self, func): ... print 'Initializing decorator' ... self.func = func ... def __call__(self, *args, **kwargs): ... print 'Calling method' ... return self.func(*args, **kwargs) >>> @decorator ... def f(a, b, c): ... return a + b + c ... Initializing decorator >>> f(1, 2, 3) Calling method 6
  • 34. Decorators with arguments >>> def decorator(debug=False): ... def wrap(func): ... def f_wrap(a, b, c): ... if debug: ... print 'Function f called with %s, %s, %s' % (a, b, c) ... return func(a, b, c) ... return f_wrap ... return wrap
  • 35. Decorators with arguments >>> @decorator(debug=True) ... def f(a, b, c): ... return a + b + c ... >>> f(1, 2, 3) Function f called with 1, 2, 3 6 >>> @decorator(debug=False) ... def f(a, b, c): ... return a + b + c ... >>> f(1, 2, 3) 6
  • 36. Q&A
  • 37. Problems to solve 1) Create a function that accept both positional and keyword arguments and returns their sum 2) Create a generator that implements a dice that "brokes" after the 10th roll 3) Create a decorator that converts letters to number according to their position in the alphabet and combine it with the solution of problem #1. When converting letters to numbers make them lowercase and count from 0 i.e. a==0, b==1.
  • 38. About Me eng. Ilian Iliev ● Web Developer for 9+ years ● Python/Django fan for 3+ years ● ilian@i-n-i.org ● http://ilian.i-n-i.org ● https://github.com/IlianIliev/