I try to understand memorization, particularly regarding nonlocal mem with the code below: def mem_last(f):     mem = 0     def helper(x):         print(&quot;mem = &quot;, mem)         mem = f(x + mem)         return mem     return helper  def mem_last1(f):     mem = {&quot;0&quot;: 0}     def helper(x):         print(&quot;mem = &quot;, mem)         mem[&quot;0&quot;] = f(x + mem[&quot;0&quot;])         return mem[&quot;0&quot;]     return helper      def f(x):     print(&quot;x = &quot;, x)     return x  f = mem_last(f)  #f = mem_last1(f)  print(f(0))  When I use f = mem_last(f), where mem is a scalar, there is an error: py mem.py  Traceback (most recent call last):   File &quot;mem.py&quot;, line 15, in &lt;module&gt;     print(f(0))   File &quot;mem.py&quot;, line 4, in helper     print(&quot;mem = &quot;, mem) UnboundLocalError: local variable 'mem' referenced before assignment  If I use f = mem_last1(f), where mem is a dict, there is no error and it works well. Please explain why there is a difference between a dict and a scalar var. Thank you very much. PS: I am using 3.7.7 64 bit on Windows 10. I have read the thread you provide and I fix it by add a line &quot;nonlocal mem&quot; before 'print(&quot;mem = &quot;, mem)'. However, my question is why I do not need to add line &quot;nonlocal mem&quot; when mem is a dict or a list, and no error occur. So why python treats scalar different from dict or list?
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?
78277
For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines.   One quick way is to do this:  lines = len(list(open(fname)))   However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to keep the current line in memory).  This doesn't work:  lines = len(line for line in open(fname))   as generators don't have a length.  Is there any way to do this short of defining a count function?  def count(i):     c = 0     for el in i: c += 1     return c   To clarify, I understand that the whole file will have to be read! I just don't want it in memory all at once
85902
I found the following behavior at least weird:  def errors():     try:         ErrorErrorError     finally:         return 10  print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined   The exception disappears when you use return inside a finally clause. Is that a bug? Is that documented anywhere?  But the real question (and the answer I will mark as correct) is: What is the python developers' reason to allow that odd behavior?
52593
Yesterday, I found myself writing code like this:  SomeStruct getSomeStruct() {     SomeStruct input;      cin &gt;&gt; input.x;     cin &gt;&gt; input.y; }   Of course forgetting to actually return the struct I just created.  Oddly enough, the values in the struct that was returned by this function got initialized to zero (when compiled using g++ that is).  Is this just a coincidence or did another SomeStruct get created and initialized somewhere implicitly?
84641
I hesitated to post on StackOverflow but I think the problem has little to do with programming and more to do with mathematics. So, here it is:  I wanted to compute the function $ f(n) = 0 \oplus 1 \oplus 2 \oplus \dotsb \oplus n$ in O(1) instead of O(n) so I computed $f(1), f(2),...$ to see the global look of the function and it appears that it has an easily identifiable pattern, which can be used to transform $f$ like so:  $$  f(n) = \left\{  \begin{array}{ll}   n  &amp; \mbox{if } n \equiv 0 \pmod 4 \\                 1  &amp; \mbox{if } n \equiv 1 \pmod 4 \\                 n+1  &amp; \mbox{if } n \equiv 2 \pmod 4 \\                 0 &amp; \mbox{if } n \equiv 3 \pmod 4 \\  \end{array} \right. $$   Does anyone know why the function has such pattern ?
53471
Now that it's clear , there is an associated concept that I use all the time without knowing what it really means.   I suppose everybody made once a mistake with parenthesis, resulting  in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for.  Could you give me some explanations, including examples with the magic method ?
31644
I'm looking for a clear, concise and accurate answer.    Ideally as the actual answer, although links to good explanations welcome.  This also applies to VB.Net, but the keywords are different - ByRef and ByVal.
34869
How can I iterate, loop, process, or otherwise do something, with each element from a comma separated list of things?  This question       , and the are already lots of very good answers everywhere. However I think it would also be valuable to have a single reference point where all such alternative techniques are explained in detail, with their advantages and disadvantages discussed.  All of plain-TeX, LaTeX, LaTeX3, LuaTeX, Context, etoolbox, pgffor, etc. answers are invited. Please consider explaining, for example:   How does the command/method deal with whitespace around items? How does the command/method deal with empty/missing items? (e.g. a,b,,c) How does the command/method deal with a trailing comma? Can the command/method work of a list stored on a macro? Is each iteration evaluated globally or on a local group? (i.e., if a command is defined during an iteration, does the command survive the loop?) Do items get expanded or somehow mangled before being processed? What about lists where items are key=value or some other kind of pairs? Does the method work for lists separated with something other than a comma? Any other thing I should know before deciding to use this method?
72634
I have this legacy code that I am working with and there is code like this all over the place:       #If PRE611 = True Then         'Do Something     #Else         'Something Else     #End If   I am pretty sure the PRE611 has something to do with versioning, but I would like to know what specifically the # sign does.
111183
What is the purpose of the colon before a block in Python?  Example:  if n == 0:     print "The end"
78279
I'm sure there's a simpler way of doing this that's just not occurring to me.  I'm calling a bunch of methods that return a list.  The list may be empty.  If the list is non-empty, I want to return the first item; otherwise, I want to return None.  This code works:  my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None   It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it.  Is there?  Edit:  The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:  x = get_first_list() if x:     # do something with x[0]     # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y:     # do something with y[0]     # inevitably forget the [0] part AGAIN, and have another bug to fix   What I'd like to be doing can certainly be accomplished with a function (and probably will be):  def first_item(list_or_none):     if list_or_none: return list_or_none[0]  x = first_item(get_first_list()) if x:     # do something with x y = first_item(get_second_list()) if y:     # do something with y   I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick.  But seeing these answers, it seems like a function is the simple solution.
38527
I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the .  However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can anyone tell me why this is happening and how I can implement this functionality otherwise? (Apart from putting the implementation into the __new__ which feels quite hacky.)  Here's an example:  class A(object):     _dict = dict()      def __new__(cls):         if 'key' in A._dict:             print "EXISTS"             return A._dict['key']         else:             print "NEW"             return super(A, cls).__new__(cls)      def __init__(self):         print "INIT"         A._dict['key'] = self         print ""  a1 = A() a2 = A() a3 = A()   Outputs:  NEW INIT  EXISTS INIT  EXISTS INIT   Why?
21209
Not many are aware of this feature, but Python's functions (and methods) can have . Behold:  &gt;&gt;&gt; def foo(x): ...     pass ...      &gt;&gt;&gt; foo.score = 10 &gt;&gt;&gt; dir(foo) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name', 'score'] &gt;&gt;&gt; foo.score 10 &gt;&gt;&gt; foo.score += 1 &gt;&gt;&gt; foo.score 11   What are the possible uses and abuses of this feature in Python ? One good use I'm aware of is 's usage of the docstring to associate a syntax rule with a method. But what about custom attributes ? Are there good reasons to use them ?
13401
I am trying to transition to using the etoolbox package, but seem to have run into some difficulties and they appear related to the hyperref and bm packages which to me seem totally unrelated.  The MWE example compiles since \RemoveEToolbox is defined and shows that there is no apparent problem before etoolbox was used.    Commenting out the \def\RemoveEToolbox{} line produces two problems:   With both the \renewcommand, and the usepackage{hyperref} commented, this results in "Runaway argument? Paragraph ended before \bm@test@token was complete". Including the usepackage{hyperref} (with \renewcommand commented) results in "Undefined control  sequence. \Call@AtVeryEndDocument ...cumentHook \@undefined"   But if uncomment the \renewcommand{\bm}{#1} line (effectively doing without any \bm), then this seems to compile.  I have been using this for a while now and things appeared to have been working fine, but now that I attempt to use etoolbox I seem to run into problems.  \documentclass{standalone} \def\RemoveEToolbox{}% Shows that this works fine without {etoolbox}  \usepackage{amsmath} \usepackage{xcolor} \usepackage{bm}  \ifdefined\RemoveEToolbox     \newcommand*{\iftoggle}[3]{#2}% Default to true value of "if" \else     \usepackage{etoolbox}     \newtoggle{paper}     \toggletrue{paper}      %\renewcommand{\bm}[1]{#1}% Why can't I have a normal \bm with {etoolbox}? \fi  % \usepackage{hyperref}  \begin{document}  This document is intended for  \iftoggle{paper}{paper}{electronic} distribution.  \bm{\textcolor{blue}{Solve $x^2-1=0$}}  \begin{align*}     a &amp;= b\\     \iftoggle{paper}{         c &amp;= d\\     }{}     e &amp;= f\\ \end{align*} \end{document}
6086
Putting aside whether the use of , I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:  from __future__ import with_statement import pickle  # Simple class definition class myclass(object):     def __init__(self, data):         self.data = data  # Create an instance of the class x = myclass(100)  # Pickle the instance to a file with open("c:\\pickletest.dat", "wb") as f:     pickle.dump(x, f)  # Replace class with exact same definition class myclass(object):     def __init__(self, data):         self.data = data  # Read an object from the pickled file with open("c:\\pickletest.dat", "rb") as f:     x2 = pickle.load(f)  # The class names appear to match print x.__class__ print x2.__class__  # Uh oh, this fails...(why?) assert isinstance(x2, x.__class__)   Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance works fine.
48764
Does anyone know how the built in dictionary type for python is implemented?  My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.
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;