Typing arguments in python
andrew-pythonlist at puzzling.org
Wed Apr 16 16:12:44 CEST 2003
On Wed, Apr 16, 2003 at 06:24:15AM -0700, Danra wrote:
> def f(fileobj):
> if not hasattr(fileobj,'write'):
> raise TypeError, "Given arg must have the 'write' attribute."
> The advantages of the second definition are obvious - The fact that
> the argument passed doesn't have the write method would be detected
> immediately, rather than when trying to call the it.
> Why is that so important? Well, for starters in many cases it isn't.
> In a simple script or application it really is sufficient to get the
> exception only when calling write.
> But - what if:
> 1) The stuff you do before calling write takes a lot of time, which
> could be saved if the error is detected when the function is called.
If this really is a concern, then this idiom takes care of it quite
write = fileobj.write
# Slow code goes here
> 2) The object gets passed around from function to function, and maybe
> changes its name on the way. In this case it would be more difficult
> to trace the problem from the errorneous call to the original function
1) Spaghetti code should be avoided
2) For geniunely complex code, you can resort to a debugger if the tracebacks
I suggest learning to love and trust Python's dynamic typing, rather than
More information about the Python-list