EquipDev
EquipDev

Reputation: 5931

How to get all user defined attributes in types.SimpleNamespace type?

When doing:

import types
ns = types.SimpleNamespace(alfa = 1, bravo = 2, charlie = 3)
print(dir(ns))

The resulting list contains all the class methods also, thus:

['__class__', '__delattr__', ..., 'alfa', 'bravo', 'charlie']

How to get a list of only the user defined attributes, thus ['alfa', 'bravo', 'charlie'], preferable without doing ridiculous text matching on the attribute names ?

Upvotes: 10

Views: 7208

Answers (1)

user2555451
user2555451

Reputation:

Update:

Actually, I just remembered you can do:

>>> import types
>>> ns = types.SimpleNamespace(alfa = 1, bravo = 2, charlie = 3)
>>> list(ns.__dict__)
['charlie', 'bravo', 'alfa']
>>> sorted(ns.__dict__)
['alfa', 'bravo', 'charlie']
>>>

which is a lot simpler.


Just use a list comprehension to filter the results:

>>> import types
>>> ns = types.SimpleNamespace(alfa = 1, bravo = 2, charlie = 3)
>>> [x for x in dir(ns) if not x.startswith('__')]
['alfa', 'bravo', 'charlie']
>>>

Thankfully, all special methods/attributes begin and end with __, so they are easy to filter out.

If you want to allow names that only start with __, then you can make the if clause a little more robust:

[x for x in dir(ns) if not (x.startswith('__') and x.endswith('__'))]

Upvotes: 18

Related Questions