Source code for namespace
#
##
## SPDX-FileCopyrightText: © 2007-2024 Benedict Verhegghe <bverheg@gmail.com>
## SPDX-License-Identifier: GPL-3.0-or-later
##
## This file is part of pyFormex 3.5 (Thu Feb 8 19:11:13 CET 2024)
## pyFormex is a tool for generating, manipulating and transforming 3D
## geometrical models by sequences of mathematical operations.
## Home page: https://pyformex.org
## Project page: https://savannah.nongnu.org/projects/pyformex/
## Development: https://gitlab.com/bverheg/pyformex
## Distributed under the GNU General Public License version 3 or later.
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see http://www.gnu.org/licenses/.
##
"""A Namespace class with both attribute and dict style lookup.
"""
import types
#######################################################
## Namespace ##
#################
[docs]class Namespace(types.SimpleNamespace):
"""A SimpleNamespace subclass that also has dict access methods.
The Namespace class adds three dunder methods to the
:class:`types.SimpleNamespace` class:
__getitem__, __setitem__ and__delitem__.
This allows the attributes also to be accessed with dict methods.
Furthermore, it defines an _attrs method to get a list of the
defined attributes.
Examples
--------
>>> S = Namespace(a=0, b=1)
>>> print(S)
Namespace(a=0, b=1)
>>> S['c'] = 2
>>> S.a = 3
>>> print(S)
Namespace(a=3, b=1, c=2)
>>> print(S.a, S['a'])
3 3
>>> del S.a
>>> T = Namespace(**{'b':1, 'c':2})
>>> print(S, T)
Namespace(b=1, c=2) Namespace(b=1, c=2)
>>> print(S == T)
True
>>> del S['c']
>>> print(S == T)
False
>>> print(T._attrs())
['b', 'c']
"""
def __getitem__(self, k):
return self.__getattribute__(k)
def __setitem__(self, k, v):
self.__setattr__(k, v)
def __delitem__(self, k):
self.__delattr__(k)
def _attrs(self):
return list(self.__dict__)
# End