Created
July 25, 2024 08:27
-
-
Save louisswarren/171227c224ad9e986ba2d329eb0b9aee to your computer and use it in GitHub Desktop.
Nicer interface for JSON-like data in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Selector: | |
def __init__(self, *j): | |
self.__contents = j | |
def __getattr__(self, attr): | |
return Selector(*(v[attr] for v in self.__contents)) | |
def __getitem__(self, idx): | |
if idx is Ellipsis: | |
return Selector(*(x for v in self.__contents for x in v)) | |
if idx is None: | |
assert(all(len(v) == 1 for v in self.__contents)) | |
idx = 0 | |
return Selector(*(v[idx] for v in self.__contents)) | |
def __eq__(self, other): | |
return self.__contents == other.__contents | |
def __str__(self): | |
assert(len(self.__contents) == 1) | |
return str(self.__contents[0]) | |
def __int__(self): | |
assert(len(self.__contents) == 1) | |
return int(self.__contents[0]) | |
def __iter__(self): | |
for c in self.__contents: | |
for x in c: | |
yield Selector(x) | |
def __repr__(self): | |
return f'Selector(*{repr(self.__contents)})' | |
def __invert__(self): | |
return self.__contents |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment