UberCurious
UberCurious

Reputation: 3

Python's namespace equivalent for dict.get()

Right now I have the following code in my project:

if keyword in sample_namespace:
    return sample_namespace[keyword]
else:
    return None

Namespace is build dynamically from plugins content.

If it were an dictionary, and not a namespace, I could simply do sample_dict.get(keyword), to get the same functionality. Is there any way how to do this with namespaces while achieving the same neatness?

Upvotes: 0

Views: 131

Answers (1)

mgilson
mgilson

Reputation: 309969

I think you're looking for getattr:

return getattr(sample_namespace,keyword,None)

Alternatively, if you're using the term namespace, vars(namespace) will return a dictionary which is a representation of the namespace.

Upvotes: 2

Related Questions