Typing arguments in python

Andrew Bennetts andrew-pythonlist at puzzling.org
Wed Apr 16 10:12:44 EDT 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."
>     .
>     .
>     fileobj.write('...')
>     .
>     .
> 
> 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
succiently:

def f(fileobj):
    write = fileobj.write
    ...
    # Slow code goes here
    ...
    write('...')

> 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
> call.

1) Spaghetti code should be avoided
2) For geniunely complex code, you can resort to a debugger if the tracebacks
aren't sufficient.

I suggest learning to love and trust Python's dynamic typing, rather than
fighting it.

-Andrew.






More information about the Python-list mailing list