Main Content

Some gems from Intermediate Python

Archive - Originally posted on "The Horse's Mouth" - 2016-10-30 07:59:25 - Graham Ellis

Last week, I ran a private Python Intermediate course - using Python 2.7 at customer request - and here are some of the code snippets I wrote in front of the class - little things I may not have blogged about in the past. Complete examples being emailed to the delegates!

 # with keyword to perform open and closure on object
 # -------------------------------------------------
 
 with table.rectangularTable("Bob","3",2000,100) as ourparty:
         print ourparty
         print ourparty.getSeats()
 print ourparty
 
 # defining your own "with"
 # -----------------------
 
         def __enter__(this,*t,**tt):
                 print "We have a nice table by the window"
                 print t,tt
                 return this
         def __exit__(this,*t,**tt):
                 print "Can we have a cleaner over here please?"
                 print t,tt
 
 # map, filter and reduce examples
 # -------------------------------
 
 teams = map(lambda x: x/11,sizes)
 fewspares = filter(lambda x: x%11 < 1,sizes)
 ballgames = filter(lambda x:x.find("ball")>-1,games)
 print reduce(lambda x,y: x+y, sizes)
 
 # Python 2 - sorting
 # ------------------
 
 found.sort(lambda x,y:cmp(len(x),len(y)) or cmp(x,y))
 
 # Python 2 v Python 3 sorting
 # ---------------------------
 
 if sys.version_info < (3,0):
         found.sort(lambda x,y:cmp(len(x),len(y)))
 else:
         found.sort(key = lambda x:len(x))
 
 # Python 2 and 3 compatible printing
 # ----------------------------------
 
 print("Here are the remote IP visitors to your images")
 for k in range(len(found)):
         sep = ((k+1)%4 and k+1 != len(found)) and " " or "\n"
         sys.stdout.write("%16s%s"%(found[k],sep))