Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any trick to "overload the dot operator"?

Tags:

I know the question is a little weirdly stated, but I can't think of any other way of saying it. I have an application that deals with large json objects, and I want to be able to just say:

object1.value.size.whatever.attributexyz 

instead of

object1.get('value').get('size').get('whatever').get('attributexyz') 

Is there some clever way to catch the AttributeError that would be raised and check inside the data structure if that attribute corresponds to any of its values?

like image 598
alexgolec Avatar asked Apr 01 '11 18:04

alexgolec


People also ask

Can you overload the dot operator?

No, Dot (.) operator can't be overloaded. Doing so will cause an error.

Why we Cannot overload dot operator?

These operators cannot be overloaded because if we overload them it will make serious programming issues. For an example the sizeof operator returns the size of the object or datatype as an operand. This is evaluated by the compiler.

Which method is used to overload operators?

In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .

Is operator overloading slow?

If performance is extremely critical, some operator overloads are slightly slower than an optimized solution due to the way they are implemented. Because the vec3 + operator returns a new vec3 object, it requires some memory allocation, which is a bit slow.


1 Answers

In object1's class definition,

def __getattr__(self, key):     return self.get(key) 

Any attempt to resolve a property, method, or field name that doesn't actually exist on the object itself will be passed to __getattr__.

If you don't have access to the class definition, i.e. it's something like a dictionary, wrap it in a class. For a dictionary, you could do something like:

class DictWrapper(object):     def __init__(self, d):         self.d = d     def __getattr__(self, key):         return self.d[key] 

Note that a KeyError will be raised if the key is invalid; the convention, however, is to raise an AttributeError (thanks, S. Lott!). You can re-raise the KeyError as an AttributeError like so, if necessary:

try:     return self.get(key) except KeyError as e:     raise AttributeError(e) 

Also remember that if the objects you are returning from __getattr__ are also, for example, dictionaries, you'll need to wrap them too.

like image 194
Lucas Jones Avatar answered Sep 23 '22 15:09

Lucas Jones