I'm finding myself using hasattr a lot and would like to write more concisely.
In JS, I use the开发者_开发问答 following pattern often:
var x = variable || DEFAULT_VARIABLE;
What's the equivalent in Python?
Something better than this...
if hasattr(my_obj, 'my_key'):
x = my_obj.my_key
else:
x = 3
EDIT: Fixed a bug mixing up objects and dicts.
x = my_dict.get('my_key', 3)
That seems clear: http://docs.python.org/library/stdtypes.html#dict.get
Assuming, of course, that my_dict
really is a dictionary. The whole hasattr
thing in the question is confusing.
Since you're talking about javascript and hasattr
, I'm guessing this is a situation where variable
is undefined. In Python, hasattr
doesn't test for the presence of dictionary keys, it only tests for the presence of object attributes. Furthermore, there is no simpler way than hasattr
to test whether an object has an attribute in Python, because unlike in javascript, variable names must be defined to be used. Therefore, to refer to a variable name that may or may not be defined, you must use a string.
That said, you could use the ternary operator + hasattr
to write the test in one line:
>>> class F(object):
... pass
...
>>> f = F()
>>> f.foo = 5
>>> f.bar if hasattr(f, 'bar') else 10
10
>>> f.foo if hasattr(f, 'foo') else 10
5
This works because f.foo
isn't even evaluated if hasattr
returns False
.
You could also define f.foo = None
and use or
as Wooble suggests in his comment.
To test whether a key is in a dictionary, say if k in d:
, and to get a default value if k
isn't in the dictionary, if that's what you want, see S.Lott's answer.
x=variable if variable else DEFAULT_VARIABLE
Don't remember if this works with all python versions...
精彩评论