query on nested python objects

505 Views Asked by At

I have some objects structure created with YAML. Inside YAML many tags are used. So the document contains not only builtin types but also some objects created from registered constructors. I need to check them by some patterns.

So far I've tried jsonpath, objectpath, jmespath and dpath. All those libraries are great and I like query languages (especially in first two), but they are strictly expecting JSON as the input. Is there some analogs for raw objects?

2

There are 2 best solutions below

0
On

From what I remember writing ObjectPath there are technical nuances which makes querying Python objects hard to impossible. There are built in Objects and classes written in C that do not expose object properties, there are private properties hidden for other classes etc.

ObjectPath should work well with classes that inherit from Dict, but the code is experimental. It may work out of the box for you and if not, the code that does that is in newest ObjectPath @ https://github.com/adriank/ObjectPath/blob/master/objectpath/core/interpreter.py#L47.

0
On

glom handle this:

>>> from glom import glom
>>> from types import SimpleNamespace
>>> sn1 = SimpleNamespace()
>>> sn1.foo = SimpleNamespace()
>>> sn1.foo.bar = "baz"
>>> glom(sn1, "foo.bar")
'baz'