Skip to content

Instantly share code, notes, and snippets.

@bonfy
Created June 14, 2017 00:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bonfy/961774239276fe57951459d1608e1ed6 to your computer and use it in GitHub Desktop.
Save bonfy/961774239276fe57951459d1608e1ed6 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
@fahdjamy
Copy link

Hello, thanks for the great book.
I have read the book but I am constantly confused with lines 35-36.

It looks like the argument that is an instance of abc.Mapping is not considered and instead, we return an instance of FrozenJSON.
Like how is the JSON object even converted to a Python JSON like object using new?
The build @classmethod was clear but this is a little baffling.

@ngokchaoho
Copy link

@fahdjamy I believe super().new(cls) # <2> calls object.new(FrozenJson) and since It is the same class of where the new is declared, it then proceed to use FrozenJson's init. Remember the object construction behaviour

# pseudocode for object construction
def make(the_class, some_arg):
    new_object = the_class.__new__(some_arg)
    if isinstance(new_object, the_class):
        the_class.__init__(new_object, some_arg)
    return new_object

# the following statements are roughly equivalent
x = Foo('bar')
x = make(Foo, 'bar')

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