HANDLE ERROR,
GENERATOR AND
DECORATOR
John
Saturday, December 21, 2013
HANDLE ANY
UNEXPECTED
ERROR
Brief introduction
• Python provide 2 ways to handle unexpected
error: exception and assert.
• Exception handling: is an event, which occurs
during the execution of a program, that disrupts
the normal flow of the program's instructions.
• The exceptions are defined in the built-in class
exceptions
• For example: If divided by 0, we want to raise an
exception
Built-in exceptions
Warnings
• It is defined on the warnings module
Raising Exceptions
• The raise statement allows the programmer
to force a specified exception to occur
raise NameError('HiThere')
• Raise statement is to raise an exceptions, tryexception-finally clause is to catch an
exceptions and decide how to do.
Try …except…finally structure

•
•
•
•

First, the try clause(print 100/0) is executed
If no exception occurs, the except clause is skipped
Otherwise, the rest of the try clause is skipped. Go to the line its type
matches the exception name(ZeroDivisionError).
Clean-up info in the finally sentence. It executed under all conditions
Write User-defined Exceptions
>>> class MyError(Exception):
... def __init__(self, value):
...
self.value = value
... def __str__(self):
...
return repr(self.value)

• Define user-defined exception MyError.
• Raise an exception when x == 0. Also write the try-except-finally
clause
• When call f(0,100), the exception is raised and catched.
Brief introduction of assert
• The assert clause is used on situation or
condition that should never happen. For
example: assert 1>0
• “assert” statement is removed when the
compilation is optimized (-O and -OO option,
it is because __debug__ change to False
when -O or -OO option are added).
• So It is a convenient way to insert debugging
assertion into a program
Quick example

• We can see assert is ignored when add -O
option
GENERATOR
Brief introduction
• Generator s are a simple and powerful tool for
create iterators.
• Use yield statement instead of return to return
data
• the __iter__() and next() methods are created
automatically. The local and execution state are
saved automatically.
• When generator terminate, it raise StopIteration
Quick example
• When you call the generator function, the co
de does not run. It just return the generator
object.
The difference between generator
and sequence type
>>> mylist = [x*x for x in range(3)]
>>> mygenerator = (x*x for x in range(3))
•Both mylist and mygenerator are iterable
•But you can only read
generator once.
•Generator do not store all
the values in memory, they
generate the values on the
fly.
DECORATOR
Brief introduction
• Functions are objects in python.
• We can define other function inside function
definition.
• We can pass a function as argument of other
function.
Quick example
•

benchmark function accept
func as input argument.
• We can see @benchmark
equal to
apply benchmark function
on f
f = benchmark(f)
•

This is the typical usage of
decorator: Use func as input
argument. define wrapper
function inside function
definition
Official document
• PEP - 318 Decorators for Functions and
Methods
DESCRIPTOR
Brief introduction
• A descriptor is an object attribute with
“binding behavior”.
• If any of __get__(), __set__() and
__delete__() are defined for an object, it is
said to be a descriptor.
Descriptor protocol
• If an object defines both __get__() and __set__(), it is considered
a data descriptor.
• Descriptors that only define __get__() are called non-data
descriptors

• descriptors are invoked by the __getattribute__() method
• overriding __getattribute__() prevents automatic descriptor
calls
Descriptor example
• Define __set__ and __get__ method.
Implement the property() method
• Calling property() is a succinct way of building
a data descriptor
Let us write the similar property()
descriptor
Function are non-data descriptor
• All functions include __get__() method for
binding methods.
Non-data descriptor staticmethod
• The pure python verson of static method
should be like:

Use static method
Non-data descriptor classmethod
• Pure python version of classmethod looks
like:

Python advanced 1.handle error, generator, decorator and decriptor

  • 1.
  • 2.
  • 3.
    Brief introduction • Pythonprovide 2 ways to handle unexpected error: exception and assert. • Exception handling: is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. • The exceptions are defined in the built-in class exceptions • For example: If divided by 0, we want to raise an exception
  • 4.
  • 5.
    Warnings • It isdefined on the warnings module
  • 6.
    Raising Exceptions • Theraise statement allows the programmer to force a specified exception to occur raise NameError('HiThere') • Raise statement is to raise an exceptions, tryexception-finally clause is to catch an exceptions and decide how to do.
  • 7.
    Try …except…finally structure • • • • First,the try clause(print 100/0) is executed If no exception occurs, the except clause is skipped Otherwise, the rest of the try clause is skipped. Go to the line its type matches the exception name(ZeroDivisionError). Clean-up info in the finally sentence. It executed under all conditions
  • 8.
    Write User-defined Exceptions >>>class MyError(Exception): ... def __init__(self, value): ... self.value = value ... def __str__(self): ... return repr(self.value) • Define user-defined exception MyError. • Raise an exception when x == 0. Also write the try-except-finally clause • When call f(0,100), the exception is raised and catched.
  • 9.
    Brief introduction ofassert • The assert clause is used on situation or condition that should never happen. For example: assert 1>0 • “assert” statement is removed when the compilation is optimized (-O and -OO option, it is because __debug__ change to False when -O or -OO option are added). • So It is a convenient way to insert debugging assertion into a program
  • 10.
    Quick example • Wecan see assert is ignored when add -O option
  • 11.
  • 12.
    Brief introduction • Generators are a simple and powerful tool for create iterators. • Use yield statement instead of return to return data • the __iter__() and next() methods are created automatically. The local and execution state are saved automatically. • When generator terminate, it raise StopIteration
  • 13.
    Quick example • Whenyou call the generator function, the co de does not run. It just return the generator object.
  • 14.
    The difference betweengenerator and sequence type >>> mylist = [x*x for x in range(3)] >>> mygenerator = (x*x for x in range(3)) •Both mylist and mygenerator are iterable •But you can only read generator once. •Generator do not store all the values in memory, they generate the values on the fly.
  • 15.
  • 16.
    Brief introduction • Functionsare objects in python. • We can define other function inside function definition. • We can pass a function as argument of other function.
  • 17.
    Quick example • benchmark functionaccept func as input argument. • We can see @benchmark equal to apply benchmark function on f f = benchmark(f) • This is the typical usage of decorator: Use func as input argument. define wrapper function inside function definition
  • 18.
    Official document • PEP- 318 Decorators for Functions and Methods
  • 19.
  • 20.
    Brief introduction • Adescriptor is an object attribute with “binding behavior”. • If any of __get__(), __set__() and __delete__() are defined for an object, it is said to be a descriptor.
  • 21.
    Descriptor protocol • Ifan object defines both __get__() and __set__(), it is considered a data descriptor. • Descriptors that only define __get__() are called non-data descriptors • descriptors are invoked by the __getattribute__() method • overriding __getattribute__() prevents automatic descriptor calls
  • 22.
    Descriptor example • Define__set__ and __get__ method.
  • 23.
    Implement the property()method • Calling property() is a succinct way of building a data descriptor
  • 24.
    Let us writethe similar property() descriptor
  • 25.
    Function are non-datadescriptor • All functions include __get__() method for binding methods.
  • 26.
    Non-data descriptor staticmethod •The pure python verson of static method should be like: Use static method
  • 27.
    Non-data descriptor classmethod •Pure python version of classmethod looks like: