Correct type for a simple "bag of attributes" namespace object

Terry Reedy tjreedy at udel.edu
Sat Aug 2 22:43:53 EDT 2014


On 8/2/2014 8:59 PM, Ian Kelly wrote:
> On Sat, Aug 2, 2014 at 2:46 PM, Mark Summerfield <list at qtrac.plus.com> wrote:
>> On Saturday, 2 August 2014 20:58:59 UTC+1, Ben Finney  wrote:
>>> Steven D'Aprano writes:
>>>
>>>> If you need instances which carry state, then object is the wrong
>>>> class.
>>
>> Fair enough.
>>
>>> Right. The 'types' module provides a SimpleNamespace class for the
>>> common "bag of attributes" use case::
>>>
>>>      >>> import types
>>>      >>> foo = types.SimpleNamespace()
>>>      >>> foo.x = 3
>>>      >>> foo
>>>      namespace(x=3)
>>
>> This is too much for children (& beginners).
>>
>> But perhaps what I should be asking for is for a new built-in that does what types.SimpleNamespace() does, so that without any import you can write, say,
>>
>> foo = namespace(a=1, b=2)
>> # or
>> bar = namespace()
>> bar.a = 1
>>
>> where under the hood namespace has the same behavior as types.SimpleNamespace().
>>
>> Naturally, I understand that adding a new name is a big deal and may be too much to ask for beginners.
>
> from types import SimpleNamespace as namespace
>
> Just have them put that at the top of each file, and tell them not to
> worry about what it does.

In fact, for the original usecase, put it in a 'template file' that also 
includes a turtle import.  For one of my projects, I have @template with 
several lines of boilerplate that I use for new files.


-- 
Terry Jan Reedy




More information about the Python-list mailing list