jeudi 16 août 2018

Does python have a shorthand to check if a variable is unassigned?

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.

Aucun commentaire:

Enregistrer un commentaire