January 2018

S M T W T F S
  123456
78910111213
14151617181920
21222324252627
28293031   

Style Credit

Expand Cut Tags

No cut tags
Tuesday, August 21st, 2007 12:59 pm (UTC)
Pychecker and associated tools do a limited form of type checking, but they only take it so far, because the python type system, when you come down to it, is Turing-complete.

Consider the following interactive session:

>>> class scary(object):
... 	def __getattr__(self, name):
... 		try:
... 			return getattr(self, name)
... 		except:
... 			setattr(self, name, self._genmethod(name))
... 			return getattr(self, name)
... 	def _genmethod(self, name):
... 		def _amethod(*args, **kw):
... 			sargs = [repr(arg) for arg in args]
... 			sargs += ["%s=%s" % (key, repr(val)) for (key, val) in kw.items()]
... 			print "called %s(%s)" % (name, ", ".join(sargs))
... 		return _amethod
...
>>> sc = scary()
>>> [method for method in dir(sc) if not method.startswith('_')]
[]
>>> sc.foo('a', 'b')
called foo('a', 'b')
>>> sc.foo('a', 'b', 'c')
called foo('a', 'b', 'c')
>>> [method for method in dir(sc) if not method.startswith('_')]
['foo']
>>> sc.bar('d')
called bar('d')
>>> [method for method in dir(sc) if not method.startswith('_')]
['bar', 'foo']
>>> sc.baz(harry="potter", ron="weasley", hermione="granger")
called baz(hermione='granger', ron='weasley', harry='potter')
>>> [method for method in dir(sc) if not method.startswith('_')]
['bar', 'baz', 'foo']
>>> 


The method for method bit removes all the attributes on the class that are built-in (start with __) or internal (start with _) by convention. Also, never use a straight except: in real code.

How do you type check that without actually running it?

You can't. So why bother?

The whole point is to ignore the type of the object. Your test are supposed to catch the common errors, and likely as not, the uncommon cases are being done by developers getting thing wrong or testing your code anyway. And they should test their code to catch these common errors.

Given that it's impossible to prove a python program's type correctness, we prefer to not bother, and get on with stuff that actually matters. Yes, having type warnings from pychecker et al can sometimes help, but normally they are more of a hindrance, and the sort of type errors that actually worry you won't be picked up by such tools.

Reply

This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting