[Python-ideas] a simple namespace type

Eric Snow ericsnowcurrently at gmail.com
Sat May 26 20:53:11 CEST 2012


On Thu, May 24, 2012 at 1:34 PM, Eric Snow <ericsnowcurrently at gmail.com> wrote:
> On Thu, May 24, 2012 at 12:14 PM, Guido van Rossum <guido at python.org> wrote:
>> On Thu, May 24, 2012 at 10:17 AM, Eric Snow <ericsnowcurrently at gmail.com> wrote:
>>>  Effectively this is just a simple but distinct facade around dict to
>>> give a namespace with attribute access.  I suppose part of the
>>> question is how much of the Mapping interface would belong instead to
>>> a hypothetical Namespace interface. (I'm definitely _not_ proposing
>>> such an unnecessary extra level of abstraction).
>>
>> Possibly there is a (weird?) parallel with namedtuple. The end result
>> is somewhat similar: you get to use attribute names instead of the
>> accessor syntax (x[y]) of the underlying type. But the "feel" of the
>> type is different, and inherits more of the underlying type
>> (namedtuple is immutable and has a fixed set of keys, whereas the type
>> proposed here is mutable and allows arbitrary keys as long as they
>> look like Python names).
>
> Yeah, the feel is definitely different.  I've been thinking about this
> because of the code for sys.implementation.  Using a structseq would
> probably been the simplest approach there, but a named tuple doesn't
> feel right.  In contrast, a SimpleNamespace would fit much better.
>
> As far as this goes generally, the pattern of a simple, dynamic
> attribute-based namespace has been implemented a zillion times (and
> it's easy to do).  This is because people find a simple dynamic
> namespace really handy and they want the attribute-access interface
> rather than a mapping.
>
> In contrast, a namedtuple is, as Nick said, "the standard library's
> answer for structured records".  It's an immutable (attribute-based)
> namespace implementing the Sequence interface.  It's a tuple and
> directly reflects the underlying concept of tuples in Python by giving
> the values names.
>
> SimpleNamespace (and the like) isn't a structured record.  It's only
> job is to be an attribute-based namespace with as simple an interface
> as possible.
>
> So why isn't a type like SimpleNamespace in the stdlib? Because it's
> trivial to implement.  There's a certain trivial-ness threshold a
> function/type must pass before it gets canonized, and rightly so.
>
> Anyway, while many would use something like SimpleNamespace out the
> the standard library, my impetus was having it as a builtin type so I
> could use it for sys.implementation.  :)
>
> FWIW, I have an implementation (pure Python + c extension) of
> SimpleNamespace on PyPI:
>
>  http://pypi.python.org/pypi/simple_namespace
>
> -eric

Any further thoughts on this?  Unless anyone is strongly opposed, I'd
like to push this forward.

-eric



More information about the Python-ideas mailing list