Catching errors in attribute names at assigment

T

Thomas Philips

If one makes a typographical error when assigning a value to an
attribute (i.e if one types ClassName.xyc = 10 instead of
ClassName.xyz=10), a new attribute xyc will be created, and the error
can later prove difficult to debug.

Is there a way to check assignments when they are made and to allow
only those that modify a restricted set of allowable attributes?
Looking through ClassName.__dict__.keys() is perhaps one way to
achieve this: Is there a simpler (i.e. more Pythonic) way to do it as
well?

Thomas Philips
 
P

Pawel Kraszewski

Thomas said:
If one makes a typographical error when assigning a value to an
attribute (i.e if one types ClassName.xyc = 10 instead of
ClassName.xyz=10), a new attribute xyc will be created, and the error
can later prove difficult to debug.
Is there a way to check assignments when they are made and to allow
only those that modify a restricted set of allowable attributes?
Looking through ClassName.__dict__.keys() is perhaps one way to
achieve this: Is there a simpler (i.e. more Pythonic) way to do it as
well?

Yes, there are at least two ways

The "new" way is to use "new classes" - ones being children of "object"
class - where you have a special attribute __all__ .

If you say __all__=["a","b","c"], those 3 attributes are the only ones valid
for field/method accessing. So class.a=5 is ok, but class.d=5 raises
exception.

The "old" way is to override __getattr__ and __setattr__ and check for a
valid name before accessing.
 
H

Heather Coppersmith

If you say __all__=["a","b","c"], those 3 attributes are the
only ones valid for field/method accessing. So class.a=5 is ok,
but class.d=5 raises exception.

ITYM __slots__ instead of __all__.

Regards,
Heather
 
D

Duncan Booth

(e-mail address removed) (Thomas Philips) wrote in
Is there a way to check assignments when they are made and to allow
only those that modify a restricted set of allowable attributes?
Looking through ClassName.__dict__.keys() is perhaps one way to
achieve this: Is there a simpler (i.e. more Pythonic) way to do it as
well?

Two more Pythonic ways to do this:

Write lots of unit tests. That way you not only catch this specific problem
but lots of others as well.

Use PyChecker. That way you not only catch this specific problem but lots
of others as well.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,053
Members
47,656
Latest member
rickwatson

Latest Threads

Top