Upload
chathuranga-bandara
View
98
Download
1
Embed Size (px)
Citation preview
Python Master ClassPart 2
By Chathuranga Bandarawww.chathuranga.com
AgendaSome advanced concepts in Python
Exceptions Handling in Python
ORM - SQLAlchemy
Unit testing in Python
GeneratorsGenerators are a simple and powerful tool for creating iterators.
ie:
What is wrong there?The code is quite simple and straightforward, but its builds the full list in memory. This is clearly not acceptable in our case,
because we cannot afford to keep all n "10 megabyte" integers in memory.
Generator pattern may be?
Still Have issues.● Lots of code / boilerplate
● Hard to read
Generators to the Rescue!
Some Dark Magic there! WTF is yield?
Yield is a keyword that is used like return, except the function will return a generator.
When a yield statement is executed, the state of the generator is frozen and the value of expression_list is returned to next()‘s caller. By “frozen” we mean that all
local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack: enough information is saved so that the next time next() is invoked, the function can proceed exactly as if the
yield statement were just another external call.
Iterators It's a stateful helper object that will produce the next value when you call next() on
it. Any object that has a __next__() method is therefore an iterator. How it produces a value is irrelevant.
ie: inbuilt iterators
Custom Iterators
Decorators Some sh*t which is very useful
What is a decorator?decorators dynamically alter the functionality of a function, method or class without
having to directly use subclasses.
Some ContextWe can assign names to functions right?
Also Closures. (yes. JS stole it from here)
Also Higher Order Functions
Return a function
Finally Decorators! (stitch all the sh*t together)
Python Decorator Syntax
Better way?
Passing Arguments to decorators
More Pythonic
Exceptions Handling in PythonTry and Catch that nigga!
Syntax
How to raise an Exception
Custom Exceptions
ORM for Flask
pip install Flask-SQLAlchemy
Relationships?
Do Something!
Small Applications/yourapplication /yourapplication.py /static /style.css /templates layout.html index.html login.html ...
Packages/yourapplication /runserver.py /yourapplication /__init__.py /views.py /static /style.css /templates layout.html index.html login.html ...
With Blueprintsyourapp/
__init__.py
static/
templates/
home/
control_panel/
admin/
views/
__init__.py
home.py
control_panel.py
admin.py
models.py
Unit Testing
Inbuilt?
Nose helps you manage unit tests
pip install unittest2
Questions?
That’s all for today Folks!