ChatGPT解决这个技术问题 Extra ChatGPT

Determine if variable is defined in Python [duplicate]

This question already has answers here: Easy way to check that a variable is defined in python? [duplicate] (5 answers) Closed 2 years ago.

How do you know whether a variable has been set at a particular place in the code at runtime? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. I'm looking for something like defined() in Perl or isset() in PHP or defined? in Ruby.

if condition:
    a = 42

# is "a" defined here?

if other_condition:
    del a

# is "a" defined here?
Please, please, please, do not "conditionally" set a variable. That's just dreadful, horrible design. Always, always, always provide for all logic paths. Please do not continue doing this.
+1 to S.Lott anwser. The fact that there is a way to do it doesn't mean you should use it in a fresh project.
@S.Lott: I have to disagree. When I use import to "source" a "config file" (i.e. a file that only has assignments in it), it may very well be that some variable has not been defined there. And import is sure cheaper/simpler than ConfigParser, so for me pragmatism wins over beauty here.
@STATUS_ACCESS_DENIED: That's what defaults are appropriate. First set the defaults. Then import your configuration. Now all variables are defined, either as defaults or overrides in the configuration file. You can easily avoid conditionally setting a variable.

p
phoenix
try:
    thevariable
except NameError:
    print("well, it WASN'T defined after all!")
else:
    print("sure, it was defined.")

@Aaron: There are many cases when you don't know whether variable is defined. You can refactor code to avoid this in many, but not all cases. Alex's solution is correct and it the best when refactoing is not possible for some reasons. There is not much information in the question, so I believe only person asked it can select the best way to handle his case.
@Aaron, "should" is a 4-letter word -- e.g. no driver "should" ever exceed the speed limit, but that doesn't mean you don't take all proper and needed precautions against those who nevertheless do. Maintaining fragile, undertested legacy code with somewhat-broken design that you inherited from somebody else is a fact of life, and those who can only think of big-bang rewriting from scratch rather than cautiously and incrementally need to re-read Joel's 9-years-old essay joelonsoftware.com/articles/fog0000000069.html .
This debate is much more interesting that the answer itself, which by the way is 100% correct and let you handle poor legacy code elegantly.
Exceptions should be reserved for exceptional cases, not for use as the bastard brother of 'if' :-(
@einpoklum, Python uses exception StopIteration within just about every for statement -- that's how an iterator lets it known that it's all done. And of course, it is far from "an exceptional case" for iteration to be done -- indeed, one expects most iterations to terminate. Thus, obviously, your opinions on how exceptions "should" be used are not correctly applicable to Python (other languages have different pragmatics and the question cannot be properly treated as "language agnostic" as in the Q you point to).
J
John La Rooy

'a' in vars() or 'a' in globals()

if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)


This should be the answer I believe. see stackoverflow.com/questions/843277/…
This is a very idiomatic answer. There is a strong use case here for maps; for example, if "prop2" in {"prop0": None, "prop1": None}:
As of today — June 2018: I don't think vars(__builtin__) still works (either for Python 2 or 3). I believe vars(__builtins__) (mind the plural ;-)) should be used for both versions now (tested on: Python 2.7.10 and Python 3.6.1).
Why not locals() too, why not dir()?
@AndresVia globals() is a superset of locals().
d
divegeek

I think it's better to avoid the situation. It's cleaner and clearer to write:

a = None
if condition:
    a = 42

If you like to do it that way you should make the initial value unique so you can distinguish from something setting a to None ie. UNDEFINED=object();a=UNDEFINED then you can test with a is not UNDEFINED
This is a common use of None. It's literally the semantic meaning of None-- it's nothing, nada, zip. It exists, but has "no value". Using a non-None value is useful if None can come up in an assignment and so on, but this is not so common that avoiding None should be standard practice. For example, in the question, a would only ever be 42 or undefined. Changing undefined to having a value of None results in no loss of information.
This is THE way, not sure why people think using a LONG and DIRTY try/except construct to get this done. ALSO this is very useful when using keyword args in class member functions where you don't want to hard-code the default values into the parameter list (you just define the default value as a class member).
@DevinJeanpierre That's not necessarily true. If you want to create some client library for a JSON API that treats a null value as different from an unspecified value (eg. None sets the actual JSON value to null, whereas an unspecified leaves it out of the JSON message entirely, which makes the API use a default or calculate from other attributes), you need to either differentiate None from Undefined, or None from JSON null. It's incredibly short-sighted to think that None can't or shouldn't ever be used as distinct from a value that is explicitly unspecified or undefined.
Providing a default value (which is what this answer is doing) is far different than testing the existence of a variable. There may be much overlap in the use cases, but if you want to see if something has been defined, you'll never know with this method.
J
Jerub
try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope

Exceptions should only be used in exceptional cases. See this discussion
@einpoklum This is true for most languages, but in Python exceptions are used more often, see e.g. stackoverflow.com/questions/3086806
Hmm, strange but true, apparently. I still think that's not a Good Idea (TM) but, well, can't argue with community customs.
Better use the if 'a' in vars() or 'a' in globals() solution mentioned above, which does not require an exception
try/except is what you do in python. what is a code smell in one language is a feature in another.
D
Denis Otkidach

For this particular case it's better to do a = None instead of del a. This will decrement reference count to object a was (if any) assigned to and won't fail when a is not defined. Note, that del statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.


x
xsreality

One possible situation where this might be needed:

If you are using finally block to close connections but in the try block, the program exits with sys.exit() before the connection is defined. In this case, the finally block will be called and the connection closing statement will fail since no connection was created.


Then perhaps the connection close should not be done in the finally?