Reputation: 5931
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
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