Domanda

While working with many if/elif/else I sometime loose a track if a variable has been already declared. I would like to know a simple way to check if the variable foo has been already declared. What would be the simplest syntax to accomplish that?

P.s. It was interesting to see how globals() and locals() could be used to accomplish this.

EDIT:

I've ended up using:

if not 'myVariableName' in globals().keys(): myVariableName='someValue'

It's hard to track when and where/if app = QtGui.QApplication(sys.argv) had been already declared especially in situation when one gui module calls another and vise versa.

if 'app' in globals() (seems) helps to avoid an accidental variable re-declaration.

È stato utile?

Soluzione 2

Rather than worrying about if a variable is declared, declare all variables from the start. You can give variables some value to indicate that it is still in a initial state, such as

foo = None 

or, if you want to use None for some other purpose, you can create a unique value to indicate the initial state, such as

INITIAL = object()
foo = INITIAL

Later, if you need to check if the variable has been set, you could just use if:

if foo == INITIAL:

I think the main advantages to doing it this way are

  1. You'll never accidentally raise a NameError.
  2. There will be one place in your code where all the variables are introduced, so readers of your code do not have to wonder what variables are in play.

By the way, it is similarly a good idea to define all instance attributes in __init__, so there is no question about what attributes an instance may have.

Altri suggerimenti

try:
   foo
except NameError:
   # does not exist
else:
   # does exist
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top