SlideShare a Scribd company logo
Programming with
Python
                    Week 3
Dept. of Electrical Engineering and Computer Science
Academic Year 2010-2011
Week 2 - Highlights


• Dictionaries:
  {key:value,...}
• Lists:
  [12,4,56,...]
• Tuples:
  (firstname,lastname)=(ā€œProgrammingā€,ā€Pythonā€)
Programming with Python - Week 3
4.1 The power of
Introspection
• Introspection is code looking at other modules and
  functions in memory as objects, getting information
  about them, and manipulating them.
• Along the way:
  i. you'll define functions with no name,
  ii. you’ll call functions with arguments out of order,
  iii. you’ll reference functions whose names you don't
  even know ahead of time.
Introspection at work

def info(object, spacing=10, collapse=1):
  """Print methods and doc strings.

  Takes module, class, list, dictionary, or string."""
  methodList = [method for method in dir(object) if callable(getattr(object, method))]
  processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
  print "n".join(["%s %s" %
               (method.ljust(spacing),
                processFunc(str(getattr(object, method).__doc__)))
              for method in methodList])
(setup)


• >>> import apihelper
• >>> apihelper.info.__doc__
  'Print methods and doc strings.n      n Takes module,
  class, list, dictionary, or string.'
4.2 Using Optional and
Named Arguments

• Python allows function arguments to have default values.
• If the function is called without the argument, the
  argument gets its default value.
• Arguments can be specified
  - in any order
  - by using named arguments.
spacing and collapse are
optional arguments.


def info(object, spacing=10, collapse=1):
This looks totally whacked
until you realize that
arguments are simply a
dictionary.
• info(spacing=15, object=odbchelper)
4.3 Some built-in functions


• type
• str
• dir
• callable
type function


• The type function returns the datatype of any arbitrary
  object.
• The possible types are listed in the types module. This is
  useful for helper functions that can handle several types
  of data.
Examples

• >>> type(apihelper)
  <type 'module'>
• >>> type(info)
  <type 'function'>
• >>> type("hello")
  <type 'str'>
• >>> type(1)
  <type 'int'>
types module


• >>> import types
• >>> types.ModuleType == type(apihelper)
  True
str function
• The str coerces data into a string. Every datatype can be
  coerced into a string.
• >>> str(1)
  '1'
• >>> str(apihelper)
  "<module 'apihelper' from '.../Week 3/Code/
  apihelper.py'>"
• >>> str([ā€œmortalā€, ā€œkombatā€, ā€œgo and fightā€])
  ask in class..
dir function


• dir returns a list of the attributes and methods
  of any object: modules, functions, strings, lists,
  dictionaries...

  pretty much anything.
Examples


• >>> dir([])
• >>> dir({})
• >>> dir(apihelper)
callable function

• The callable function takes any object and returns
  True if the object can be called,
  or False otherwise.
                                      example class
• Callable objects include
  functions,
  class methods,
  even classes themselves.
callable is beautiful:

• By using the callable function on each of an object's
  attributes, you can determine which attributes you care
  about (methods, functions, classes) and which you want
  to ignore (constants and so on)
  without knowing anything about the object
  ahead of time.

  HINT: Introspection
Examples

• >>> import string
• >>> string.punctuation
   '!"#$%&'()*+,-./:;<=>?@[]^_`{|}~'
• >>> string.join
   <function join at 0x6efaf0>
• >>> callable(string.punctuation)
   False
• >>> ask in class for string.join test..
4.4 Getting object
references with getattr

• You already know that Python functions are
  objects.
• What you don't know is that you can get a reference to
  a function without knowing its name until run-time, by
  using the getattr function.
Examples

• >>> li = [ā€œLarryā€, ā€œBracketyā€]
• >>> li.pop
• >>> getattr(li, ā€œpopā€)
• >>> getattr(li, ā€œappendā€)(ā€œJuniorā€)
• >>> li
Ask in class..



• 1. First import the ask_in_class module
  and then;
  2. call the mockfunction using getattr function.
4.4.2 Introspection,
Dispatching



• what is the typical use of getattr-like functionality?
Dispatching..
Dispatcher
Model, View, Controller (MVC)
Model, View, Controller (MVC)

So, what the hell is MVC?
Dispatcher


             Dispatcher
             sitting here
Model, View, Controller (MVC)
Front Controller
4.4.2 Introspection,
Dispatching

• A common usage pattern of getattr is as a dispatcher.
• For example, if you had a program that could output
  data in a variety of different formats, you could define
  separate functions for each output format and use a
  single dispatch function to call the right one.
Example

• For example, let's imagine a program that prints site
  statistics in HTML, XML, and plain text formats.
• The choice of output format could be specified on the
  command line, or stored in a configuration file.
• A statsout module defines three functions,
  output_html, output_xml, and output_text. Then the
  main program defines a single output function, like this:
Example

  import statsout

  def output(data, format="text"):
    output_function = getattr(statsout, "output_%s" % format)
    return output_function(data)
Default value
in case, the method or
attribute is not found.
 import statsout

 def output(data, format="text"):
   output_function = getattr(statsout, "output_%s" % format, statsout.output_text)
   return output_function(data)
Programming with Python - Week 3
4.5 Filtering Lists


• Python has powerful capabilities for mapping lists into
  other lists, via list comprehensions.
• This can be combined with a filtering mechanism, where
  some elements in the list are mapped while others are
  skipped entirely.
Filtering syntax:
[mapping-expression for element in source-list if filter-expression]


         Any element for which the filter expression
         evaluates true will be included in the mapping.

         All other elements are ignored, so they are never
         put through the mapping expression and
         are not included in the output list.
Example



• >>> li = [ā€œaaaā€, ā€œaaā€, ā€œaā€, ā€œbā€]
• >>> [elem for elem in li if len(elem) == 1]
Ask in class..


methodList = [method for method in dir(object) if callable(getattr(object, method))]




         interpretation
            please?!?
4.6 The Peculiar Nature
    of and and or


• In Python, and and or perform boolean logic as you
  would expect, but they do not return boolean values;
  instead, they return one of the actual values
  they are comparing.
and

• If all values are true, the last value is returned.
• If not all values are true, then it returns the first false
  value.
• >>> ā€œaā€ and ā€œbā€
  'b'
• >>> ā€œā€ and ā€œbā€
  ''
or



• if any value is true, that value is returned immediately.
• if all values are false, then the last value is returned.
4.7 Using lambda functions

• Python supports an interesting syntax that lets you
  define one-line mini-functions on the fly.
• Borrowed from Lisp, these so-called lambda functions
  can be used anywhere a function is required.
• The entire function can only be one expression.
• A lambda is just an in-line function.
Example

• >>> def f(x):
           return x*2
• >>> f(3)
• >>> g = lambda x: x*2
• >>> g(3)
• >>> (lambda x: x*2)(3)
Remember:

• To generalize, a lambda function is a function that takes
  any number of arguments (including optional arguments)
  and returns the value of a single expression.
• Don't try to squeeze too much into a lambda function; if
  you need something more complex, define a normal
  function instead and make it as long as you want.
• Use them in places where you want to encapsulate
  specific, non-reusable code without littering your code
  with a lot of little one-line functions.
apihelper.py
Happy holidays

More Related Content

What's hot (18)

Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
Praveen M Jigajinni
Ā 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
Ā 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith Kumar
Ā 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
Ā 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
Ā 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Emertxe Information Technologies Pvt Ltd
Ā 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
Ā 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!
Ā 
Python language data types
Python language data typesPython language data types
Python language data types
Hoang Nguyen
Ā 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
Ā 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
Mohammed Sikander
Ā 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
Ā 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
Megha V
Ā 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
Matt Harrison
Ā 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
SivaSankar Gorantla
Ā 
1. python
1. python1. python
1. python
PRASHANT OJHA
Ā 
Python list
Python listPython list
Python list
Prof. Dr. K. Adisesha
Ā 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Python
primeteacher32
Ā 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
Ā 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith Kumar
Ā 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
Ā 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
Ā 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!
Ā 
Python language data types
Python language data typesPython language data types
Python language data types
Hoang Nguyen
Ā 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
Ā 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
Ā 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
Megha V
Ā 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
Matt Harrison
Ā 
Intro to Functions Python
Intro to Functions PythonIntro to Functions Python
Intro to Functions Python
primeteacher32
Ā 

Viewers also liked (8)

Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
Ahmet Bulut
Ā 
Tristans Shooting
Tristans ShootingTristans Shooting
Tristans Shooting
Popular Struggle Coordination Committee
Ā 
Centro1807 marpegan tecnologia
Centro1807 marpegan tecnologiaCentro1807 marpegan tecnologia
Centro1807 marpegan tecnologia
Guillermo Barrionuevo
Ā 
What is open source?
What is open source?What is open source?
What is open source?
Ahmet Bulut
Ā 
Virtualization @ Sehir
Virtualization @ SehirVirtualization @ Sehir
Virtualization @ Sehir
Ahmet Bulut
Ā 
Kaihl 2010
Kaihl 2010Kaihl 2010
Kaihl 2010
Ahmet Bulut
Ā 
Upstreamed
UpstreamedUpstreamed
Upstreamed
jfetch01
Ā 
Startup Execution Models
Startup Execution ModelsStartup Execution Models
Startup Execution Models
Ahmet Bulut
Ā 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
Ahmet Bulut
Ā 
Centro1807 marpegan tecnologia
Centro1807 marpegan tecnologiaCentro1807 marpegan tecnologia
Centro1807 marpegan tecnologia
Guillermo Barrionuevo
Ā 
What is open source?
What is open source?What is open source?
What is open source?
Ahmet Bulut
Ā 
Virtualization @ Sehir
Virtualization @ SehirVirtualization @ Sehir
Virtualization @ Sehir
Ahmet Bulut
Ā 
Kaihl 2010
Kaihl 2010Kaihl 2010
Kaihl 2010
Ahmet Bulut
Ā 
Upstreamed
UpstreamedUpstreamed
Upstreamed
jfetch01
Ā 
Startup Execution Models
Startup Execution ModelsStartup Execution Models
Startup Execution Models
Ahmet Bulut
Ā 
Ad

Similar to Programming with Python - Week 3 (20)

Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
Ā 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
Ā 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
Ā 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
PranavSB
Ā 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
Haitham El-Ghareeb
Ā 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
Ā 
function_xii-BY APARNA DENDRE (1).pdf.pptx
function_xii-BY APARNA DENDRE (1).pdf.pptxfunction_xii-BY APARNA DENDRE (1).pdf.pptx
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
Ā 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
Karthik Prakash
Ā 
Python for Data Science function third module ppt.pptx
Python for Data Science  function third module ppt.pptxPython for Data Science  function third module ppt.pptx
Python for Data Science function third module ppt.pptx
bmit1
Ā 
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdfsingh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
horiamommand
Ā 
Functions
FunctionsFunctions
Functions
Gaurav Subham
Ā 
ExamRevision_FinalSession_C++ notes.pptx
ExamRevision_FinalSession_C++ notes.pptxExamRevision_FinalSession_C++ notes.pptx
ExamRevision_FinalSession_C++ notes.pptx
nglory326
Ā 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
arvdexamsection
Ā 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
Ā 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
Ā 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
Aditya Shankar
Ā 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
H2Kinfosys
Ā 
In Python, aĀ listĀ is a built-in dynamic sized array. We can store all types o...
In Python, aĀ listĀ is a built-in dynamic sized array. We can store all types o...In Python, aĀ listĀ is a built-in dynamic sized array. We can store all types o...
In Python, aĀ listĀ is a built-in dynamic sized array. We can store all types o...
Karthik Rohan
Ā 
Polymorphism
PolymorphismPolymorphism
Polymorphism
prabhat kumar
Ā 
Python programming Concepts (Functions, classes and Oops concept
Python programming Concepts (Functions, classes and Oops conceptPython programming Concepts (Functions, classes and Oops concept
Python programming Concepts (Functions, classes and Oops concept
Lipika Sharma
Ā 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
Ā 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
Ā 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
PranavSB
Ā 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
Ā 
function_xii-BY APARNA DENDRE (1).pdf.pptx
function_xii-BY APARNA DENDRE (1).pdf.pptxfunction_xii-BY APARNA DENDRE (1).pdf.pptx
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
Ā 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
Karthik Prakash
Ā 
Python for Data Science function third module ppt.pptx
Python for Data Science  function third module ppt.pptxPython for Data Science  function third module ppt.pptx
Python for Data Science function third module ppt.pptx
bmit1
Ā 
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdfsingh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
horiamommand
Ā 
ExamRevision_FinalSession_C++ notes.pptx
ExamRevision_FinalSession_C++ notes.pptxExamRevision_FinalSession_C++ notes.pptx
ExamRevision_FinalSession_C++ notes.pptx
nglory326
Ā 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
Ā 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
Ā 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
Aditya Shankar
Ā 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
H2Kinfosys
Ā 
In Python, aĀ listĀ is a built-in dynamic sized array. We can store all types o...
In Python, aĀ listĀ is a built-in dynamic sized array. We can store all types o...In Python, aĀ listĀ is a built-in dynamic sized array. We can store all types o...
In Python, aĀ listĀ is a built-in dynamic sized array. We can store all types o...
Karthik Rohan
Ā 
Python programming Concepts (Functions, classes and Oops concept
Python programming Concepts (Functions, classes and Oops conceptPython programming Concepts (Functions, classes and Oops concept
Python programming Concepts (Functions, classes and Oops concept
Lipika Sharma
Ā 
Ad

More from Ahmet Bulut (12)

Nose Dive into Apache Spark ML
Nose Dive into Apache Spark MLNose Dive into Apache Spark ML
Nose Dive into Apache Spark ML
Ahmet Bulut
Ā 
Data Economy: Lessons learned and the Road ahead!
Data Economy: Lessons learned and the Road ahead!Data Economy: Lessons learned and the Road ahead!
Data Economy: Lessons learned and the Road ahead!
Ahmet Bulut
Ā 
Apache Spark Tutorial
Apache Spark TutorialApache Spark Tutorial
Apache Spark Tutorial
Ahmet Bulut
Ā 
A Few Tips for the CS Freshmen
A Few Tips for the CS FreshmenA Few Tips for the CS Freshmen
A Few Tips for the CS Freshmen
Ahmet Bulut
Ā 
Agile Data Science
Agile Data ScienceAgile Data Science
Agile Data Science
Ahmet Bulut
Ā 
Data Science
Data ScienceData Science
Data Science
Ahmet Bulut
Ā 
Agile Software Development
Agile Software DevelopmentAgile Software Development
Agile Software Development
Ahmet Bulut
Ā 
Liselerde tanıtım sunumu
Liselerde tanıtım sunumuLiselerde tanıtım sunumu
Liselerde tanıtım sunumu
Ahmet Bulut
Ā 
Ecosystem for Scholarly Work
Ecosystem for Scholarly WorkEcosystem for Scholarly Work
Ecosystem for Scholarly Work
Ahmet Bulut
Ā 
I feel dealsy
I feel dealsyI feel dealsy
I feel dealsy
Ahmet Bulut
Ā 
Bilisim 2010 @ bura
Bilisim 2010 @ buraBilisim 2010 @ bura
Bilisim 2010 @ bura
Ahmet Bulut
Ā 
ESX Server from VMware
ESX Server from VMwareESX Server from VMware
ESX Server from VMware
Ahmet Bulut
Ā 
Nose Dive into Apache Spark ML
Nose Dive into Apache Spark MLNose Dive into Apache Spark ML
Nose Dive into Apache Spark ML
Ahmet Bulut
Ā 
Data Economy: Lessons learned and the Road ahead!
Data Economy: Lessons learned and the Road ahead!Data Economy: Lessons learned and the Road ahead!
Data Economy: Lessons learned and the Road ahead!
Ahmet Bulut
Ā 
Apache Spark Tutorial
Apache Spark TutorialApache Spark Tutorial
Apache Spark Tutorial
Ahmet Bulut
Ā 
A Few Tips for the CS Freshmen
A Few Tips for the CS FreshmenA Few Tips for the CS Freshmen
A Few Tips for the CS Freshmen
Ahmet Bulut
Ā 
Agile Data Science
Agile Data ScienceAgile Data Science
Agile Data Science
Ahmet Bulut
Ā 
Data Science
Data ScienceData Science
Data Science
Ahmet Bulut
Ā 
Agile Software Development
Agile Software DevelopmentAgile Software Development
Agile Software Development
Ahmet Bulut
Ā 
Liselerde tanıtım sunumu
Liselerde tanıtım sunumuLiselerde tanıtım sunumu
Liselerde tanıtım sunumu
Ahmet Bulut
Ā 
Ecosystem for Scholarly Work
Ecosystem for Scholarly WorkEcosystem for Scholarly Work
Ecosystem for Scholarly Work
Ahmet Bulut
Ā 
I feel dealsy
I feel dealsyI feel dealsy
I feel dealsy
Ahmet Bulut
Ā 
Bilisim 2010 @ bura
Bilisim 2010 @ buraBilisim 2010 @ bura
Bilisim 2010 @ bura
Ahmet Bulut
Ā 
ESX Server from VMware
ESX Server from VMwareESX Server from VMware
ESX Server from VMware
Ahmet Bulut
Ā 

Recently uploaded (20)

Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
Ā 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
Ā 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
Ā 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
Ā 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
Ā 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
Ā 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
Ā 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
Ā 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
Ā 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
Ā 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
Ā 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
Ā 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
Ā 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
Ā 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
Ā 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
Ā 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
Ā 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
Ā 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
Ā 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
Ā 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
Ā 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
Ā 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
Ā 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
Ā 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
Ā 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
Ā 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
Ā 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
Ā 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
Ā 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
Ā 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
Ā 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
Ā 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
Ā 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
Ā 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
Ā 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
Ā 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
Ā 

Programming with Python - Week 3

  • 1. Programming with Python Week 3 Dept. of Electrical Engineering and Computer Science Academic Year 2010-2011
  • 2. Week 2 - Highlights • Dictionaries: {key:value,...} • Lists: [12,4,56,...] • Tuples: (firstname,lastname)=(ā€œProgrammingā€,ā€Pythonā€)
  • 4. 4.1 The power of Introspection • Introspection is code looking at other modules and functions in memory as objects, getting information about them, and manipulating them. • Along the way: i. you'll define functions with no name, ii. you’ll call functions with arguments out of order, iii. you’ll reference functions whose names you don't even know ahead of time.
  • 5. Introspection at work def info(object, spacing=10, collapse=1): """Print methods and doc strings. Takes module, class, list, dictionary, or string.""" methodList = [method for method in dir(object) if callable(getattr(object, method))] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print "n".join(["%s %s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList])
  • 6. (setup) • >>> import apihelper • >>> apihelper.info.__doc__ 'Print methods and doc strings.n n Takes module, class, list, dictionary, or string.'
  • 7. 4.2 Using Optional and Named Arguments • Python allows function arguments to have default values. • If the function is called without the argument, the argument gets its default value. • Arguments can be specified - in any order - by using named arguments.
  • 8. spacing and collapse are optional arguments. def info(object, spacing=10, collapse=1):
  • 9. This looks totally whacked until you realize that arguments are simply a dictionary. • info(spacing=15, object=odbchelper)
  • 10. 4.3 Some built-in functions • type • str • dir • callable
  • 11. type function • The type function returns the datatype of any arbitrary object. • The possible types are listed in the types module. This is useful for helper functions that can handle several types of data.
  • 12. Examples • >>> type(apihelper) <type 'module'> • >>> type(info) <type 'function'> • >>> type("hello") <type 'str'> • >>> type(1) <type 'int'>
  • 13. types module • >>> import types • >>> types.ModuleType == type(apihelper) True
  • 14. str function • The str coerces data into a string. Every datatype can be coerced into a string. • >>> str(1) '1' • >>> str(apihelper) "<module 'apihelper' from '.../Week 3/Code/ apihelper.py'>" • >>> str([ā€œmortalā€, ā€œkombatā€, ā€œgo and fightā€]) ask in class..
  • 15. dir function • dir returns a list of the attributes and methods of any object: modules, functions, strings, lists, dictionaries... pretty much anything.
  • 16. Examples • >>> dir([]) • >>> dir({}) • >>> dir(apihelper)
  • 17. callable function • The callable function takes any object and returns True if the object can be called, or False otherwise. example class • Callable objects include functions, class methods, even classes themselves.
  • 18. callable is beautiful: • By using the callable function on each of an object's attributes, you can determine which attributes you care about (methods, functions, classes) and which you want to ignore (constants and so on) without knowing anything about the object ahead of time. HINT: Introspection
  • 19. Examples • >>> import string • >>> string.punctuation '!"#$%&'()*+,-./:;<=>?@[]^_`{|}~' • >>> string.join <function join at 0x6efaf0> • >>> callable(string.punctuation) False • >>> ask in class for string.join test..
  • 20. 4.4 Getting object references with getattr • You already know that Python functions are objects. • What you don't know is that you can get a reference to a function without knowing its name until run-time, by using the getattr function.
  • 21. Examples • >>> li = [ā€œLarryā€, ā€œBracketyā€] • >>> li.pop • >>> getattr(li, ā€œpopā€) • >>> getattr(li, ā€œappendā€)(ā€œJuniorā€) • >>> li
  • 22. Ask in class.. • 1. First import the ask_in_class module and then; 2. call the mockfunction using getattr function.
  • 23. 4.4.2 Introspection, Dispatching • what is the typical use of getattr-like functionality?
  • 27. Model, View, Controller (MVC) So, what the hell is MVC?
  • 28. Dispatcher Dispatcher sitting here
  • 31. 4.4.2 Introspection, Dispatching • A common usage pattern of getattr is as a dispatcher. • For example, if you had a program that could output data in a variety of different formats, you could define separate functions for each output format and use a single dispatch function to call the right one.
  • 32. Example • For example, let's imagine a program that prints site statistics in HTML, XML, and plain text formats. • The choice of output format could be specified on the command line, or stored in a configuration file. • A statsout module defines three functions, output_html, output_xml, and output_text. Then the main program defines a single output function, like this:
  • 33. Example import statsout def output(data, format="text"): output_function = getattr(statsout, "output_%s" % format) return output_function(data)
  • 34. Default value in case, the method or attribute is not found. import statsout def output(data, format="text"): output_function = getattr(statsout, "output_%s" % format, statsout.output_text) return output_function(data)
  • 36. 4.5 Filtering Lists • Python has powerful capabilities for mapping lists into other lists, via list comprehensions. • This can be combined with a filtering mechanism, where some elements in the list are mapped while others are skipped entirely.
  • 37. Filtering syntax: [mapping-expression for element in source-list if filter-expression] Any element for which the filter expression evaluates true will be included in the mapping. All other elements are ignored, so they are never put through the mapping expression and are not included in the output list.
  • 38. Example • >>> li = [ā€œaaaā€, ā€œaaā€, ā€œaā€, ā€œbā€] • >>> [elem for elem in li if len(elem) == 1]
  • 39. Ask in class.. methodList = [method for method in dir(object) if callable(getattr(object, method))] interpretation please?!?
  • 40. 4.6 The Peculiar Nature of and and or • In Python, and and or perform boolean logic as you would expect, but they do not return boolean values; instead, they return one of the actual values they are comparing.
  • 41. and • If all values are true, the last value is returned. • If not all values are true, then it returns the first false value. • >>> ā€œaā€ and ā€œbā€ 'b' • >>> ā€œā€ and ā€œbā€ ''
  • 42. or • if any value is true, that value is returned immediately. • if all values are false, then the last value is returned.
  • 43. 4.7 Using lambda functions • Python supports an interesting syntax that lets you define one-line mini-functions on the fly. • Borrowed from Lisp, these so-called lambda functions can be used anywhere a function is required. • The entire function can only be one expression. • A lambda is just an in-line function.
  • 44. Example • >>> def f(x): return x*2 • >>> f(3) • >>> g = lambda x: x*2 • >>> g(3) • >>> (lambda x: x*2)(3)
  • 45. Remember: • To generalize, a lambda function is a function that takes any number of arguments (including optional arguments) and returns the value of a single expression. • Don't try to squeeze too much into a lambda function; if you need something more complex, define a normal function instead and make it as long as you want. • Use them in places where you want to encapsulate specific, non-reusable code without littering your code with a lot of little one-line functions.

Editor's Notes