|
|
Subscribe / Log in / New account

Improving Python's SimpleNamespace

Improving Python's SimpleNamespace

Posted May 1, 2020 1:18 UTC (Fri) by moxfyre (guest, #13847)
In reply to: Improving Python's SimpleNamespace by amarao
Parent article: Improving Python's SimpleNamespace

I agree. It's a matter of convenient access, whether you're populating contents “on the fly” (more a use case for dict) or with a relatively small set of fixed names (more a use case for a custom class or attrs).

In my vpn-slice and wtf utilities, I have long used an even simpler version of SimpleNameSpace, dubbed slurpy:

# Quacks like a dict and an object
class slurpy(dict):
    def __getattr__(self, k):
        try:
            return self[k]
        except KeyError as e:
            raise AttributeError(*e.args)
    def __setattr__(self, k, v):
        self[k]=v
This allows you to create an object like d = slurpy(foo="bar", baz=1) and then refer to any of its members/contents either by member access (.foo) or by item access (["foo"]).

It's very simple and performs well for a pure-Python implementation, and it even throws KeyError or AttributeError appropriately so that callers/REPLs don't get confused by the “wrong” kind of exception.

(See https://github.com/dlenski/vpn-slice/blob/HEAD/vpn_slice/util.py#L13-L22 and https://github.com/dlenski/wtf/blob/HEAD/wtf.py#L10-L18 for some context as to how this is useful.)


to post comments


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds