[Tutor] Why do I not get an error when I mistakenly type "humdrum.sigh_strenght" instead of the correct "humdrum.sigh_strength"?

Steven D'Aprano steve at pearwood.info
Thu Jan 21 05:57:09 EST 2016


On Wed, Jan 20, 2016 at 09:54:32PM -0800, Danny Yoo wrote:

> Just to be explicit: you are pointing out that:
> 
>      humdrum.sigh_strenght = 'high'
> 
> was a typo, and it would have been nice if it could be caught as an error.
> 
> If that's the case, then yes, I agree.  Unfortunately, this isn't a
> runtime error because Python allows us to add arbitrary attributes to
> objects: it's a deliberate design feature.

Danny is correct. And it is a useful feature too. For instance, we can 
add attributes to functions:

def spam(x, y):
    ...

spam.extra_info = "whatever"

Other advantages of this way of doing things include that you aren't 
forced to put all your initialisation code in a single, special place, 
you can factor parts of it out into alternative methods:

class X:
   def __init__(self, x):
       self.setup(x)
   def setup(self, x):
       process(x)
       self.attribute = x


It also means that Python doesn't require a magic "undefined" value, 
like Javascript has, or require declarations ahead of time, like static 
languages such as Pascal and C require.

However, this power does have a cost, as Danny points out:

> (As a personal note: I'm not entirely convinced of the merit of this
> particular freedom.  Misspelling is a really easy mistake to make, and
> I want the language to catch my simple mistakes, if it's not too
> onerous to do so.)

True, but I think that on average, the freedom and power of not needing 
declarations far outweighs the cost of dealing with typos. But if you 
type with your elbows and nose, you may disagree with me *wink*


[...]
> Furthermore, there actually *is* a way to turn it into a runtime
> error, though this is probably not beginner material.  If you're
> interested, see material on "__slots__".
> https://docs.python.org/3/reference/datamodel.html#slots.  I don't
> think it's intended to be used to catch typos though: its main purpose
> is to reduce memory usage, and it's use to catch misspellings is
> incidental.

Agreed. __slots__ is certainly not intended as a way of catching 
misspellings, or prohibiting the addition of new attributes. But if you 
don't mind the scorn of your fellow coders, you can use it for that 
purpose.



-- 
Steve


More information about the Tutor mailing list