Sharing attributes on arbitrary objects at runtime

Say we have an arbitrary object of an unknown type, and we want to access the equally arbitrary attribute associated with this object, requested as a string name. I am looking for the best approach to get this value.

In pseudo-code / Python, the current strategy I'm considering is this:

def access_attribute(obj, attr): if type(obj) == types.FunctionType: return access_attribute(obj(), attr) elif type(obj) == types.DictType: return obj.get(attr) # ... etc. 

A couple of issues to consider:

  • What happens if the attribute does not exist on the object? I raised an exception in order.
  • An attribute can be deeply nested.

I believe this is a problem that should be solved by DSL programming languages ​​and interpreters, but I do not know the standard / generally accepted best practices.

The idea of ​​passing custom DSL / code stored to eval at runtime with the object was raised, but I want to avoid this particular solution and prefer Python.

+5
source share
1 answer

getattr(object, name[, default]) seems to answer at least the first half of your question and this question:

What happens if the attribute does not exist on the object? I am raising an exception in order.

I would say that this is best practice as it is part of the standard library.

Regarding your second point:

An attribute can be deeply nested.

The solution would be to use dir(object) (which will list all the attributes of the object) and loop over those, but I'm less sure about the "best practice" of this solution.

-1
source

Source: https://habr.com/ru/post/1262584/


All Articles