Reputation: 2485
If I have some code like this:
x.y.z = 12
I can infer that the z
member is being indexed from the call to __setattr__
. However if I have something like this:
foo = x.y.z # situation 1
bar = x.y.z.bar # situation 2
How can I determine which of the above situations I am in, if I care to do something special for z
based on whether or not it is last in the chain of indexing? Is this kind of inference even possible in Python?
For more clarity let's assume I can change the implementation of all the objects being indexed, so using descriptors is wholly possible.
I worry that the answer to this question is "you can't do that" since it is impossible to override =
like you can in C++.
Upvotes: 3
Views: 83
Reputation: 2485
There is no way to do this with python overrides. The only way is to have a known member that means "the end." For example, if you wanted to know which member was being set in a long chain of indexes you'd need some kind of setter:
x.y.z.set(some_value)
Upvotes: 0
Reputation: 4232
I'm not sure how you define 'being last at chain of indexing'. You can still call more attributes on an object at any time.
But you can know when your object is being accessed as an attribute. As mentioned before, you can overload __getattr__
and __getattribute__
, but a more robust way would be with descriptors.
This can get you started: http://nbviewer.jupyter.org/urls/gist.github.com/ChrisBeaumont/5758381/raw/descriptor_writeup.ipynb
Alternatively, there's a more formal guide: https://docs.python.org/3/howto/descriptor.html
Upvotes: 1