Making class attributes non-case-sensitive?

Fuzzyman fuzzyman at gmail.com
Mon Oct 13 14:25:43 CEST 2008


On Oct 13, 10:11 am, Rafe <rafesa... at gmail.com> wrote:
> Hi,
>
> I'm working within an application (making a lot of wrappers), but the
> application is not case sensitive. For example, Typing obj.name,
> obj.Name, or even object.naMe is all fine (as far as the app is
> concerned). The problem is, If someone makes a typo, they may get an
> unexpected error due accidentally calling the original attribute
> instead of the wrapped version. Does anyone have a simple solution for
> this?
>
> I can protect against some cases just by making an 'alias':
> class AClass(object):
>     def name(self):
>         print "hello"
>
>     Name = name
>
> ...but this doesn't protect against typos, it gets more complicated
> with multi-word attribute names, and it makes my epydocs confusing to
> read since all spelling versions are shown (I AM concerned about my
> docs being clear, but not as much as stopping typo related errors).
>
> I thought about using my wrapper's __getattr__ and __setattr__, but I
> I am concerned about the overhead of every delegated attribute call
> running a search and compare (<paramName>.lower() based compare?).
>
> Any ideas or precedence?

If you define '__getattr__' then it will only be called for attribute
names that don't exist. So only explicitly define the names you want
in the lowercase variant and then have something like the following:

def __getattr__(self, name):
    return object.__getattr__(self, name.lower())

That way each name only appears once and you only get the extra
'__getattr__' in your epydoc docs.

Michael


>
> Cheers,
>
> - Rafe

--
http://www.ironpythoninaction.com/



More information about the Python-list mailing list