g185030
07-01-2009, 11:18 AM
Phillip Watts article "Intro to Python Introspection and Dynamic Programming" contains errors and bad advice. First off, the example with the __dict__ built-in does not use the best method:
def clearVals(self):
dict = self.getVals()
for k in dict.keys():
dict[k] = None
The problem is that the keys() method returns a list and requires O(n) storage for n keys. Better is:
def clearVals(self):
dict = self.getVals()
for k in dict.iterkeys():
dict[k] = None
since the iterkeys() method returns an iterator and uses only O(1) storage. Best is:
def clearVals(self):
dict = self.getVals()
for k in dict:
dict[k] = None
Since the default dictionary iterator is over the keys.
==============
Second, his example for type simply doesn't work. Here's his example run on my machine:
>>> var1 = 12
>>> typ = str(type(var1))
>>> if typ == "":
... var1 / 4
... else: print 'Not an Int'
...
Not an Int
His example doesn't work because:
>>> print typ
<type 'int'>
>>>
To truly do what is required, you need to use the isinstance() built-in function:
>>> if isinstance(var1, int):
... var1/4
... else: print "not an int"
...
3
>>> var1 = 'abc'
>>> if isinstance(var1, int):
... var1/4
... else: print "not an int"
...
not an int
def clearVals(self):
dict = self.getVals()
for k in dict.keys():
dict[k] = None
The problem is that the keys() method returns a list and requires O(n) storage for n keys. Better is:
def clearVals(self):
dict = self.getVals()
for k in dict.iterkeys():
dict[k] = None
since the iterkeys() method returns an iterator and uses only O(1) storage. Best is:
def clearVals(self):
dict = self.getVals()
for k in dict:
dict[k] = None
Since the default dictionary iterator is over the keys.
==============
Second, his example for type simply doesn't work. Here's his example run on my machine:
>>> var1 = 12
>>> typ = str(type(var1))
>>> if typ == "":
... var1 / 4
... else: print 'Not an Int'
...
Not an Int
His example doesn't work because:
>>> print typ
<type 'int'>
>>>
To truly do what is required, you need to use the isinstance() built-in function:
>>> if isinstance(var1, int):
... var1/4
... else: print "not an int"
...
3
>>> var1 = 'abc'
>>> if isinstance(var1, int):
... var1/4
... else: print "not an int"
...
not an int