I have found a similar question . It's related to immutable variable. But when I test mutable variable, I don't know how Python interpreter decides the scope of the variable.    Here's my sample code:    def test_immutable():     a = 1     b = 2      def _test():         print(a)         print(b)          a += 1         print(a)      _test()  def test_mutable():     _dict = {}      def _test():         print(_test.__dict__)          _dict['name'] = 'flyer'           print('in _test: {0}'.format(_dict['name']))      _test()      print(_dict['name'])   if __name__ == '__main__':     # test_immutable()    # throw exception     test_mutable()    # it's ok
1022
The following code works as expected in both Python 2.5 and 3.0:  a, b, c = (1, 2, 3)  print(a, b, c)  def test():     print(a)     print(b)     print(c)    # (A)     #c+=1       # (B) test()   However, when I uncomment line (B), I get an UnboundLocalError: 'c' not assigned at line (A). The values of a and b are printed correctly. This has me completely baffled for two reasons:   Why is there a runtime error thrown at line (A) because of a later statement on line (B)? Why are variables a and b printed as expected, while c raises an error?   The only explanation I can come up with is that a local variable c is created by the assignment c+=1, which takes precedent over the "global" variable c even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.  Could someone please explain this behavior?
4570
I'd like to call a function in python using a dictionary.  Here is some code:  d = dict(param='test')  def f(param):     print(param)  f(d)   This prints {'param': 'test'} but I'd like it to just print test.  I'd like it to work similarly for more parameters:  d = dict(p1=1, p2=2) def f2(p1, p2):     print(p1, p2) f2(d)   Is this possible?
24968
If a variable is declared as static in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called?  void foo()  {      static string plonk = "When will I die?"; }
71027
The following code fails to compile stating  "A local variable named 'st' cannot be declared in this scope because it would give a different meaning to 'st', which is already used in a 'child' scope to denote something else":           var l = new List&lt;string&gt;();         l.Find(st =&gt; st.EndsWith("12"));         string st = "why this fails?";   I understand why this won't work:          string preParent = "";         {             string preParent = "Should fail cause we change the meaning";         }   When we do the following we get "CS0103: The name 'postParent' does not exist in the current context":          {             string postParent=string.Empty;         }         postParent = "Should this work?";   What I don't get is why is the compiler smart enough to see that postParent is not within scope, but won't let me define a new variable that has the same name as a variable used within a child scope (which is obviously out of scope at this point).   Is the compiler simple enforcing scope by refusing to let me use the variable? If so this makes sense.  ===========  Edited:   I guess what I also find interesting is how you can have the same variable within two child scopes in a single method, so this is valid:          {             string thisWorks= string.Empty;         }         {             string thisWorks= "Should this work?";         }   I'm just a little curious that you can have two variables with the same name as long as they are at the same level (if you look at scope as a tree). This makes sense because you can have local variables in two methods of the same class with the same name.   I'm just surprised that the compiler is able to differentiate and allow this, while it wouldn't allow the postParent variable. And is this a technical limitation or was this a design decision? That's what I'm really trying to get at;-)
69666
How can I easily detect when a variable changes value? I would like the execution of the program to break on the debugger whenever a specified variable changes value. Right now I'm using Eclipse's debugger.
115925
Is there any difference between:  if foo is None: pass   and  if foo == None: pass   The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter.  None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right?  Are there any circumstances in which it might?
51358
How do you decide between passing arguments to a method versus simply declaring them as object instance variables that are visible to all of the object's methods? I prefer keeping instance variables in a list at the end of the Class, but this list gets longer as my program grows. I figure if a variable is passed often enough it should just be visible to all methods that need it, but then I wonder, &quot;if everything is public there will be no need for passing anything at all!&quot;
13911
Possible Duplicate:          Here is a test case:   void foo(int i, int j) {    printf("%d %d", i, j); } ... test = 0; foo(test++, test);   I would expect to get a "0 1" output, but I get "0 0"  What gives??
53456
What is the difference between:  some_list1 = [] some_list1.append("something")   and  some_list2 = [] some_list2 += ["something"]
119239
I have a variable, x, and I want to know whether it is pointing to a function or not.  I had hoped I could do something like:  &gt;&gt;&gt; isinstance(x, function)   But that gives me:  Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined   The reason I picked that is because  &gt;&gt;&gt; type(x) &lt;type 'function'&gt;
4318
I was wanting to initialize some strings at the top of my script with variables that have no yet been set, such as:  str1='I went to ${PLACE} and saw ${EVENT}' str2='If you do ${ACTION} you will ${RESULT}'   and then later on PLACE, EVENT, ACTION, and RESULT will be set. I want to then be able to print my strings out with the variables expanded. Is my only option eval? This seems to work:  eval "echo ${str1}"   is this standard? is there a better way to do this? It would be nice to not run eval considering the variables could be anything.
86767
Why is it that in a C# switch statement, for a variable used in multiple cases, you only declare it in the first case?  For example, the following throws the error "A local variable named 'variable' is already defined in this scope".  switch (Type) {     case Type.A:             string variable = "x";                 break;     case Type.B:             string variable = "y";                 break; }   However, per the logic, the initial declaration should not be hit if the type is Type.B. Do all variables within a switch statement exist in a single scope, and are they created/allocated before any logic is processed?
72908
I am trying to figure out this:  c = 1 def f(n):     print c + n  def g(n):     c = c + n  f(1) # =&gt; 2 g(1) # =&gt; UnboundLocalError: local variable 'c' referenced before assignment   Thanks!
3567
Given the following code, what does the if __name__ == "__main__": do?  # Threading example import time, thread  def myfunction(string, sleeptime, lock, *args):     while True:         lock.acquire()         time.sleep(sleeptime)         lock.release()         time.sleep(sleeptime)  if __name__ == "__main__":     lock = thread.allocate_lock()     thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))     thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
18277
Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?  I.e., I want to do this:  my_dict = {}  if (my_dict[key] != None):   my_dict[key] = 1 else:   my_dict[key] += 1   I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.
36537
Are stateful member variable of Batch Apex class maintain state after finish method when accessed in a test method. e.g.   global  class SampleBatch implements      Database.Batchable&lt;SObject&gt;,Database.Stateful {      global integer count;     global SampleBatch (){count =0;}      //START     global Database.QueryLocator start(Database.BatchableContext BC) {                  return Database.getQueryLocator(queryString);                      }          //EXECUTE      global void execute (Database.BatchableContext BC,List&lt;sObject&gt; scope){      count++;     }     //FINISH     global void finish(Database.BatchableContext BC){     }   }   When I try to access count variable in Apex Test Class it gives me value as 0, is it expected behavior?
119860
A weird bug was occurring in production which I was asked to look into. The issue was tracked down to a couple of variables being declared within a For loop and not being initialized on each iteration. An assumption had been made that due to the scope of their declaration they would be &quot;reset&quot; on each iteration. Could someone explain why they would not be)? (My first question, really looking forward to the responses.) The example below is obviously not the code in question but reflects the scenario:  Please excuse the code example, it looks fine in the editor preview?? for (int i =0; i&lt; 10; i++) {     decimal? testDecimal;     string testString;      switch( i % 2  )     {         case 0:         testDecimal = i / ( decimal ).32;         testString = i.ToString();             break;         default:             testDecimal = null;             testString = null;             break;     }      Console.WriteLine( &quot;Loop {0}: testDecimal={1} - testString={2}&quot;, i, testDecimal , testString ); }   EDIT: Sorry, had to rush out for child care issue. The issue was that the prod code had was that the switch statement was huge and in some &quot;case&quot;'s a check on a class' property was being made, like if (myObject.Prop != null) then testString = myObject.Stringval... At the end of the switch, (outside) a check on testString == null was being made but it was holding the value from the last iteration,hence not being null as the coder assumed with the variable being declared within the loop. Sorry if my question and example was a bit off, I got the phone call about the day care as I was banging it together. I should have mentioned I compared IL from both variables in and out the loop. So, is the common opinion that &quot;obviously the variables would not be reinitialized on each loop&quot;? A little more info, the variables WHERE being initialized on each iteration until someone got over enthusiastic with ReSharper pointing out &quot;the value is never used&quot; and removed them.  EDIT: Folks, I thank you all. As my first post I see how much clearer I should be in the future. The cause of our unexpected variable assignment can me placed on an inexperienced developer doing everything ReSharper told him and not running any unit tests after he ran a &quot;Code Cleanup&quot; on an entire solution. Looking at the history of this module in VSS I see variables Where declared outside of the loop and where initialized on each iteration. The person in question wanted his ReSharper to show &quot;all green&quot; so &quot;moved his variables closer to assignment&quot; then &quot;Removed redundant assignment&quot;! I don't think he will be doing it again...now to spend the weekend running all the unit tests he missed! How to do mark a question as answered?