Background is I'm getting data from a JSON API where lots of fields are optional and I want most of the fields in a database. When a specific field isn't available I want an empty string ("") written into the database.
Currently I've been doing:
if jsonobject.what_i_look_for:
dbstring = jsonobject.what_i_look_for
else:
dbstring = ""
And then inserted dbstring into the database. However I'm getting a lot more of these fields now and I want a much cleaner code rather than a function which consists about 80% of if-statements.
I've found if-shorthands and this shorthand to check if a variable is empty, but both don't seem to work directly as a string. I've tested this using print() in an interactive python 3.5.2 shell:
>>> print(testvar or "")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'testvar' is not defined
>>> print(testvar if testvar else "")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'testvar' is not defined
This: echo (isset($testvar) ? $testvar : ""); is the PHP equivalent of what I seek.
Edit: Since it seems relevant: The object I am trying to process is coming from Telegram's JSON API. I'm using python-telegram-bot as library and this is an example object.
jsonobject.what_i_look_foris an attribute, not a variable. Is your question about variables or about attributes? Also,if jsonobject.what_i_look_for:checks whether thewhat_i_look_for_attributeis set to a truthy value; it does not check if that attribute exists. So, again, what is your question really?hasattris possibly what you want although it may be better to ask forgiveness not permissionhasattr(obj, name)to see if it exists, or getattr(obj, name, default)` to get the attribute if it exists or return the default if it doesn’t. But if you find yourself doinghasattrorgetattrfor most of your attributes, that’s often a sign that you didn’t want an object full of attributes in the first place, but a dictionary. (Notice that the stdlib json module uses dictionaries.)