Skip to content

Instantly share code, notes, and snippets.

@wwj718
Forked from bonfy/FrozenJSON.py
Created August 6, 2019 04:20
Show Gist options
  • Save wwj718/62d0d3f8046c6f90711e1bc34107b3d0 to your computer and use it in GitHub Desktop.
Save wwj718/62d0d3f8046c6f90711e1bc34107b3d0 to your computer and use it in GitHub Desktop.
FrozenJSON in Fluent Python
"""
explore2.py: Script to explore the OSCON schedule feed
>>> from osconfeed import load
>>> raw_feed = load()
>>> feed = FrozenJSON(raw_feed)
>>> len(feed.Schedule.speakers)
357
>>> sorted(feed.Schedule.keys())
['conferences', 'events', 'speakers', 'venues']
>>> feed.Schedule.speakers[-1].name
'Carina C. Zona'
>>> talk = feed.Schedule.events[40]
>>> talk.name
'There *Will* Be Bugs'
>>> talk.speakers
[3471, 5199]
>>> talk.flavor
Traceback (most recent call last):
...
KeyError: 'flavor'
"""
# BEGIN EXPLORE2
from collections import abc
class FrozenJSON:
"""A read-only façade for navigating a JSON-like object
using attribute notation
"""
def __new__(cls, arg): # <1>
if isinstance(arg, abc.Mapping):
return super().__new__(cls) # <2>
elif isinstance(arg, abc.MutableSequence): # <3>
return [cls(item) for item in arg]
else:
return arg
def __init__(self, mapping):
self.__data = {}
for key, value in mapping.items():
if iskeyword(key):
key += '_'
self.__data[key] = value
def __getattr__(self, name):
if hasattr(self.__data, name):
return getattr(self.__data, name)
else:
return FrozenJSON(self.__data[name]) # <4>
# END EXPLORE2
@wwj718
Copy link
Author

wwj718 commented Aug 6, 2019

用于处理深层消息

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment