4 ms·
SimpleNamespace[0] is pretty handy too. It essentially lets you wrap a dictionary and access its keys as member properties. Also, it's kind of weird that the a
by rcfox 7y ago
SimpleNamespace[0] is pretty handy too. It essentially lets you wrap a dictionary and access its keys as member properties.
Also, it's kind of weird that the article would mention type annotations and then not mention mypy[1].
[0] https://docs.python.org/3/library/types.html?highlight=types#types.SimpleNamespace https://docs.python.org/3/library/types.html?highlight=types...
[1] http://mypy-lang.org/ http://mypy-lang.org/
- DonaldPShimoda 7y agoWhoa, I've never seen the `types` module before! This will actually be very handy for me for what I've been working on lately. Thanks for pointing it out!
- rcfox 7y agoIt's definitely worthwhile going over the standard library[0] every now and then. I always find something interesting to read up on. I recently learned about cmd[1] (which has been around for a long time) and have been using it to write a text adventure game. [0] https://docs.python.org/3/library/index.html https://docs.python.org/3/library/index.html [1] https://docs.python.org/3/library/cmd.html https://docs.python.org/3/library/cmd.html
- rattray 7y agoCurious to see a small code sample illustrating typical usage of SimpleNamespace if you care to share? Docs didn't include one.
- rcfox 7y agoHere's one case I've used it for: foo = json.dumps({'a': 1, 'b': {'c': 2}}) # Pretend you've downloaded some JSON... bar = json.loads(foo, object_hook=lambda x: types.SimpleNamespace(**x)) print(bar.a) print(bar.b.c) print(bar.b.d) # Error bar.b.d = 3 print(bar.b.d) # Works now I mean, you could pretty much do the same sort of thing with namedtuple, except this is mutable and doesn't require a pre-declaration of the keys. It's easier to write off the cuff.