import sys ## Boxed arithmetic - overflow handling def fn(): i = 0 while i < 10000000: i = i+1 ## Introspection and reflection def fill_list(name): # get the frame object of the caller frame = sys._getframe().f_back # get the variable "name" in the caller's context lst = frame.f_locals[name] lst.append(42) def foo(): mylist = [] fill_list("mylist") print mylist # prints [42] ## Dynamic lookup of methods and attributes # an empty class class MyClass: pass # arguments passed to foo can be of any type def foo(target, flag): # the attribute x is set only if flag is True if flag: target.x = 42 def fn(): obj = MyClass() # if we pass False, obj would not have any attribute x foo(obj, True) print obj.x print getattr(obj, "x") # use a string for the attribute name ## From Python bytecode to native code import dis def add(a, b): return a+b #dis.dis(add)