Python & Perl: Lecture 11

1,065 views
999 views

Published on

Published in: Technology, Business
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,065
On SlideShare
0
From Embeds
0
Number of Embeds
400
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Python & Perl: Lecture 11

  1. 1. Python & Perl Lecture 11 Vladimir Kulyukin Department of Computer Science Utah State Universitywww.youtube.com/vkedco www.vkedco.blogspot.com
  2. 2. Outline ● Run-time Code Execution & Evaluation ● Functional Abstraction ● Getting Ready to Take Your PIL: Installing Python Image Library (PIL)www.youtube.com/vkedco www.vkedco.blogspot.com
  3. 3. Run-Time Code Execution & Evaluationwww.youtube.com/vkedco www.vkedco.blogspot.com
  4. 4. exec() ● exec() is used to execute strings, file objects, and code objects (code object is an object that contains Python expressions/statements that can be executed or evaluated >>> exec("def add2(x, y): return x + y") >>> add2(1, 2) 3 >>> exec("z = add2(1, 2); z *= 2; print z") 6 >>> z 6www.youtube.com/vkedco www.vkedco.blogspot.com
  5. 5. exec() & Code Objects ● One way to obtain code objects is to call the Python compiler on some expression or statement >>> cobj1 = compile(x = 1 + 3; print x + 5, errors.txt, exec) >>> cobj2 = compile(def add2(x, y): return x + y, errors.txt, exec) >>> exec cobj1 9 >>> exec cobj2 >>> add2www.youtube.com/vkedco www.vkedco.blogspot.com
  6. 6. exec() >>> code_str = """ ### beginning of multi-line code string def fact(n): ### def begins if n == 0: return 1 else: return n * fact(n-1) ### def ends x = fact(5) print x """ ### end of multi-line code string >>> exec code_str ### code string is executed 120www.youtube.com/vkedco www.vkedco.blogspot.com
  7. 7. Code Templates ● exec() can be used to run code templates ● Code templates can be useful when you want to test functions or code pieces without necessarily saving them into files ● Code templates can be saved in a dictionary or some other container and later disposed of or saved in a filewww.youtube.com/vkedco www.vkedco.blogspot.com
  8. 8. Example from string import Template code1 = def add2(x, y): return x + y sum = add2($x, $y) print sum code2 = def mult3(x, y, z): return x * y * z prod = mult3($x, $y, $z) print prod www.youtube.com/vkedco www.vkedco.blogspot.com
  9. 9. Example Continued code_tmpl1 = Template(code1) ## create code template 1 code_tmpl2 = Template(code2) ## create code template 2 tmpl_dict = {} ## create a dictionary tmpl_dict[tmpl1] = code_tmpl1 ## put code template 1 into dictionary under tmpl1 tmpl_dict[tmpl2] = code_tmpl2 ## put code template 2 into dictionary under tmpl2 ### use dictionary to execute templates with different values >>> exec tmpl_dict[tmpl1].substitute(x=5, y=5) 10 >>> exec tmpl_dict[tmpl2].substitute(x=5, y=10) 15 >>> exec tmpl_dict[tmpl2].substitute(x=5, y=5, z=10) 250www.youtube.com/vkedco www.vkedco.blogspot.com
  10. 10. Security Caveat ● exec() is very useful in automated code generation, code testing, intelligent data analysis and synthesis ● Caveat: This is a potential security hole, especially if used with untrusted third-party source code files ● Recommendation: Do not use exec() on code segments that you download from the web (unless you know exactly what that code does)www.youtube.com/vkedco www.vkedco.blogspot.com
  11. 11. exec() & Namespaces ● By default, exec() uses the global namespace, which may result in conflicts as shown below: >>> def f(x): return x + 1 >>> f(1) 2 >>> exec(def f(x): return x + 10) >>> f(1) ## f is redefined 11www.youtube.com/vkedco www.vkedco.blogspot.com
  12. 12. exec() & Namespaces ● You can avoid naming conflicts with exec() by creating your own namespaces ● You can create your own namespace (namespaces are dictionaries) as follows: ● exec <code_string> in <scope>, where <scope> is a dictionarywww.youtube.com/vkedco www.vkedco.blogspot.com
  13. 13. Example >>> my_scope = {} >>> exec "def add2(x, y): return x + y" in my_scope >>> add2(1, 2) ### error, because add2 is not defined in __main__ >>> my_scope[add2](1, 2) 3 >>> exec def mult3(x, y, z): return x * y * z in my_scope >>> mult3(2, 3, 4) ### error, because mult3 is not define in __main__ >>> my_scope[mult3](2, 3, 4) 24www.youtube.com/vkedco www.vkedco.blogspot.com
  14. 14. eval() ● eval() is a built-in function so parentheses are mandatory ● eval() is used with expressions, not statements ● Key difference: eval() returns the value of its argument expression >>> exec “1 + 2” ## does not return anything >>> eval(“1 + 2”) ## returns 3 >>> exec def add2(x, y): return x + y) ## this is OK >>> eval(def add2(x, y): return x + y) ## error >>> eval(print 1) ## error ● Same security concerns as with exec()www.youtube.com/vkedco www.vkedco.blogspot.com
  15. 15. Functional Abstractionwww.youtube.com/vkedco www.vkedco.blogspot.com
  16. 16. Defining Functions ● Function definition syntax def <name>(arg1, arg2, … , argN): <statements> ● Remember : after the arguments ● Indent body statements ● The body needs at least one statment ● Use pass as a place holder ● Use return to return valueswww.youtube.com/vkedco www.vkedco.blogspot.com
  17. 17. Notes on def ● def is an executable statement ● def statements can be placed inside of other control structures and executed at run time ● A function must be defined if it is to be callable by name ● Python has anonymous functions that can be defined without assigned names (lambda functions)www.youtube.com/vkedco www.vkedco.blogspot.com
  18. 18. Run-Time Function Definition def add_str(i): return def add + str(i) + (x): return x + + str(i) >>> add_str(0) def add0(x): return x + 0 >>> add_str(1) def add1(x): return x + 1 >>> add_str(2) def add2(x): return x + 2www.youtube.com/vkedco www.vkedco.blogspot.com
  19. 19. Run-Time Function Definition >>> my_funs = {} >>> for s in [add_str(i) for i in xrange(11)]: exec s in my_funs >>> my_funs[add5](10) 15 >>> my_funs[add10](10) 20www.youtube.com/vkedco www.vkedco.blogspot.com
  20. 20. Passing Function References ● It is possible and quite common to have lists of functions and call them on containers with arguments def add_str(i): return def add + str(i) + (x): return x + + str(i) for s in [add_str(i) for i in xrange(4)]: exec s >>> flist = [add0, add1, add2, add3] >>> vlist = [10, 20, 30, 40] >>> rlist = [flist[i](vlist[i]) for i in xrange(len(flist))] >>> print rlist [10, 21, 32, 43]www.youtube.com/vkedco www.vkedco.blogspot.com
  21. 21. Function Introspection ● Suppose that we define func as: def func(arg1, arg2, … , argN): <statements> ● Then: >>> func.__name__ ## double underscores on both sides >>> func >>> def add1(x): return x + 1 >>> add1.__name__ add1www.youtube.com/vkedco www.vkedco.blogspot.com
  22. 22. Function Introspection ● Functions can be documented with documentation strings ● Documentation strings (they can be multiline if necessary) must follow immediately after the def line ● Documentation strings are stored in the function objects __doc__ (double underscores on both ends) property ● To access the property: >>> function_name.__doc__www.youtube.com/vkedco www.vkedco.blogspot.com
  23. 23. Example def add1(x): “add1(x): returns x + 1” return x + 1 >>> add1.__doc__ add1(x): returns x + 1 >>> len.__doc__ ## built-in function len(object) -> integernnReturn the number of items of a sequence or mapping.www.youtube.com/vkedco www.vkedco.blogspot.com
  24. 24. Function Introspection with help() >>> help(add1) Help on function add1 in module __main__: add1(x) add1(x): returns x + 1 >>> help(len) Help on built-in function len in module __builtin__: len(...) len(object) -> integer Return the number of items of a sequence or mapping.www.youtube.com/vkedco www.vkedco.blogspot.com
  25. 25. Notes on return ● Functions with no return return None ● Functions that have return with no values return None ● If you want a function to return multiple objects, use a list, a tuple, a dictionary, or your own containerwww.youtube.com/vkedco www.vkedco.blogspot.com
  26. 26. Getting Ready to Take Your PILwww.youtube.com/vkedco www.vkedco.blogspot.com
  27. 27. Installation ● PIL is available at www.pythonware.org ● There are PIL versions for various Python releases 2.7, 2.6, etc. ● We will use PIL 1.1.7 for Python 2.7www.youtube.com/vkedco www.vkedco.blogspot.com
  28. 28. PIL on 64bit Win ● There may still be issues with 64bit versions of PIL on Windows ● Here is a forum that suggest links to 64bit versions of PIL as well as other possible workarounds on 64bit version of Python – http://stackoverflow.com/questions/2088304/installing- pil-python-imaging-library-in-win7-64-bits-python-2-6-4 ● The simplest way to handle 64bit issues is to: – Uninstall any previously installed PIL version – Install Python 32bit Version for Windows (Python 2.7) – Install PIL 32 bit Version (for Python 2.7)www.youtube.com/vkedco www.vkedco.blogspot.com
  29. 29. PIL on Mac ● In order to install PIL on a Mac it needs to be built from the source ● Source is at http://www.pythonware.com/products/pil/ ● Inside tar.gz there is README that describes which commands need to be ran to install PIL ● There are dependencies for the build as well ● These dependencies are also described in READMEwww.youtube.com/vkedco www.vkedco.blogspot.com
  30. 30. Checking PIL Availability ● Run this program interactively in the interpreter or or as a program: import Image im = Image.new(“RGB”, (32, 32)) print im ● If this works, PIL is installedwww.youtube.com/vkedco www.vkedco.blogspot.com
  31. 31. Reading & References ● www.python.org ● http://en.wikipedia.org/wiki/List_comprehension ● www.pythonware.org ● Ch 05 M. L. Hetland. Beginning Python From Novice to Pro- nd fessional, 2 Ed., APRESS ● Ch 06 M. L. Hetland. Beginning Python From Novice to Pro- fessional, 2nd Ed., APRESSwww.youtube.com/vkedco www.vkedco.blogspot.com
  32. 32. Feedback Bugs, comments to vladimir dot kulyukin at usu dot eduwww.youtube.com/vkedco www.vkedco.blogspot.com

×