注册 | 登录

(十二) Nepxion-Thunder分布式RPC集成框架 - 配置调优

nepxion 分享于 2015-12-01


up vote 216 down vote favorite 44

Possible Duplicate:
Easy way to check that variable is defined in python?
How do I check if a variable exists in Python?

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?
python variables defined share | improve this question edited Mar 3 '12 at 22:55 asked Oct 20 '09 at 5:03 user102008 17.5k 8 61 81

marked as duplicate by DNA, Mark, ЯegDwight, Peter Brown, joran Sep 19 '12 at 2:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

9   Duplicates:…,…, –  carl Oct 20 '09 at 6:50 44   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. –  S.Lott Oct 20 '09 at 10:35 1   +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. –  e-satis Mar 31 '10 at 13:48 6   @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. –  0xC0000022L Mar 21 '12 at 0:51 11   @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. –  S.Lott Mar 22 '12 at 11:29  |  show 1 more comment

7 Answers 7

active oldest votes up vote 371 down vote accepted
except NameError:
  print "well, it WASN'T defined after all!"
  print "sure, it was defined."
share | improve this answer edited Feb 17 '15 at 16:36 Ryan Li 3,536 4 24 45 answered Oct 20 '09 at 5:07 Alex Martelli 506k 92 905 1181 63   @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. –  Denis Otkidach Oct 20 '09 at 7:58 120   @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 . –  Alex Martelli Oct 20 '09 at 14:51 10   @S.Lott People use it to maintain backwards compatibility. Search for NameError in Python 3.1 source code. There are many instances where "try: var_name except NameError: something_else" is used. Here are a couple of place where it is used: CSV ( library and in the ElementTree library (…). –  sc45 Oct 20 '09 at 14:54 15   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. –  e-satis Mar 31 '10 at 13:46 7   @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). –  Alex Martelli Apr 17 '15 at 10:10  |  show 14 more comments up vote 178 down vote

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

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

share | improve this answer edited Mar 10 at 13:40 aflat 3,330 12 22 answered Oct 20 '09 at 5:08 John La Rooy 163k 23 207 350 13   This should be the answer I believe. see… –  0atman Nov 4 '10 at 13:41      This is a very idiomatic answer. There is a strong use case here for maps; for example, if "prop2" in {"prop0": None, "prop1": None}: –  robert Feb 19 '16 at 18:46 add a comment  |  up vote 74 down vote

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

a = None
if condition:
    a = 42
share | improve this answer answered Oct 20 '09 at 5:15 divegeek 2,375 1 10 14 6   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 –  John La Rooy Oct 20 '09 at 7:03 7   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. –  Devin Jeanpierre Feb 3 '10 at 5:27 3   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). –  FizxMike Feb 14 '14 at 17:13      @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. –  Taywee Jun 24 '16 at 5:36      @Taywee sure. "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." If a non-None value can come up, then None is not acceptable, and this whole pattern is error-prone. –  Devin Jeanpierre Jun 28 '16 at 17:38 add a comment  |  up vote 6 down vote
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope
share | improve this answer edited Oct 20 '09 at 6:47 Jerub 26.8k 10 56 87 answered Oct 20 '09 at 5:06 sc45 973 2 10 24 2   Exceptions should only be used in exceptional cases. See this discussion –  einpoklum Apr 10 '15 at 22:17 9   @einpoklum This is true for most languages, but in Python exceptions are used more often, see e.g. –  sdcvvc Apr 27 '15 at 20:32 1   Hmm, strange but true, apparently. I still think that's not a Good Idea (TM) but, well, can't argue with community customs. –  einpoklum Apr 28 '15 at 19:43 add a comment  |  up vote 4 down vote

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.

share | improve this answer answered Oct 20 '09 at 6:30 Denis Otkidach 18.3k 5 48 77 add a comment  |  up vote 4 down vote

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.

share | improve this answer answered Dec 28 '11 at 14:20 xsreality 41 4 add a comment  |  up vote -1 down vote

If one wants to catch attempts to access a not-defined variable inside an object, there is a very easy way of doing that:

class Whatever(object):
  def __getattr__(self, key):
    return None

Here, python first tries to find an attribute within the object or the object tree, and only if that fails the __getattr__(self, key) function is called. This means, if __getattr__ is called we can simply return None.

share | improve this answer edited Jun 14 '12 at 22:14 Dhara 3,215 1 17 38 answered Jun 14 '12 at 15:45 user1456683 17      -1 __getattr__ is called before looking up the dictionary. –  quantum Oct 20 '12 at 1:16      @quantum no it's not, but __getattribute__ is called before looking up the dictionary. –  Neil G Apr 24 '16 at 2:17 add a comment  | 

Not the answer you're looking for? Browse other questions tagged python variables defined or ask your own question.

up vote 216 down vote favorite 44 Possible Duplicate: Easy way to check that variable is defined in python How do I check if a variable exists in Python How do you know whether a












您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱