Extending classes __init__behavior for newbies

James Mills prologic at shortcircuit.net.au
Tue Feb 15 00:46:24 CET 2011


On Tue, Feb 15, 2011 at 9:32 AM, rantingrick <rantingrick at gmail.com> wrote:
> In any event, normally i would expect people to use a bit of common
> sense when wielding an interface ESPECIALLY when they wrote it! Like
> for instance... If i gave someone a loaded gun i would not bother
> telling that person "Hey, don't aim the gun at your foot and then pull
> the trigger because you could blow your pinky toe off"... no, i would
> expect them to have enough sense not to do such a stupid thing.
> However, if they *did* happen to blow their pinky toe off i really
> would not get too upset about it. After all, i've always believed that
> stupidity should be painful.

This reminds me of "good engineering practise" where you
let the error occur where it lay.

Example:

>>> def f(a):
...     return a + 1
...
>>> f(1)
2
>>> def g(*args):
...     if len(args) == 1:
...             return args[0] + 1
...     else:
...             raise Exception("Invalid arguments")
...
>>> g(1)
2
>>> g()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in g
Exception: Invalid arguments
>>> g(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in g
Exception: Invalid arguments
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes exactly 1 argument (0 given)
>>> f(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes exactly 1 argument (2 given)
>>>

In that sense, you "trust" that the programmer using
your API(s) has read "documentation" and/or "source code"
and "understands" how to "correctly" use the API(s).

If the programmer doesn't use the API(s) "correctly"
f(...) will blow up in his/her face. g(...) will blow up as well
but tries to guard against the expected TypeError you
would expect if you called f(...) incorrectly.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"



More information about the Python-list mailing list