Datasets:
Upload stackoverflow_q_and_a_sample.csv
Browse files
stackoverflow_q_and_a_sample.csv
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
link,question,accepted_answer
|
2 |
+
https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python,"<p>What functionality does the <a href=""https://docs.python.org/3/reference/simple_stmts.html#yield"" rel=""noreferrer""><code>yield</code></a> keyword in Python provide?</p> <p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p> <pre><code>def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance + max_dist >= self._median: yield self._rightchild </code></pre> <p>And this is the caller:</p> <pre><code>result, candidates = [], [self] while candidates: node = candidates.pop() distance = node._get_dist(obj) if distance <= max_dist and distance >= min_dist: result.extend(node._values) candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) return result </code></pre> <p>What happens when the method <code>_get_child_candidates</code> is called? Is a list returned? A single element? Is it called again? When will subsequent calls stop?</p> <hr /> <sub> 1. This piece of code was written by Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source: <a href=""https://well-adjusted.de/~jrspieker/mspace/"" rel=""noreferrer"">Module mspace</a>.</sub>","<p>To understand what <a href=""https://docs.python.org/3/reference/simple_stmts.html#yield"" rel=""noreferrer""><code>yield</code></a> does, you must understand what <em><a href=""https://docs.python.org/3/glossary.html#term-generator"" rel=""noreferrer"">generators</a></em> are. And before you can understand generators, you must understand <em><a href=""https://docs.python.org/3/glossary.html#term-iterable"" rel=""noreferrer"">iterables</a></em>.</p> <h2>Iterables</h2> <p>When you create a list, you can read its items one by one. Reading its items one by one is called iteration:</p> <pre><code>>>> mylist = [1, 2, 3] >>> for i in mylist: ... print(i) 1 2 3 </code></pre> <p><code>mylist</code> is an <em>iterable</em>. When you use a list comprehension, you create a list, and so an iterable:</p> <pre><code>>>> mylist = [x*x for x in range(3)] >>> for i in mylist: ... print(i) 0 1 4 </code></pre> <p>Everything you can use "<code>for... in...</code>" on is an iterable; <code>lists</code>, <code>strings</code>, files...</p> <p>These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.</p> <h2>Generators</h2> <p>Generators are <em><a href=""https://docs.python.org/3/glossary.html#term-iterator"" rel=""noreferrer"">iterators</a></em>, a kind of iterable <strong>you can only iterate over once</strong>. Generators do not store all the values in memory, <strong>they generate the values on the fly</strong>:</p> <pre><code>>>> mygenerator = (x*x for x in range(3)) >>> for i in mygenerator: ... print(i) 0 1 4 </code></pre> <p>It is just the same except you used <code>()</code> instead of <code>[]</code>. BUT, you <strong>cannot</strong> perform <code>for i in mygenerator</code> a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end after calculating 4, one by one.</p> <h2>Yield</h2> <p><code>yield</code> is a keyword that is used like <code>return</code>, except the function will return a generator.</p> <pre><code>>>> def create_generator(): ... mylist = range(3) ... for i in mylist: ... yield i*i ... >>> mygenerator = create_generator() # create a generator >>> print(mygenerator) # mygenerator is an object! <generator object create_generator at 0xb7555c34> >>> for i in mygenerator: ... print(i) 0 1 4 </code></pre> <p>Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.</p> <p>To master <code>yield</code>, you must understand that <strong>when you call the function, the code you have written in the function body does not run.</strong> The function only returns the generator object, this is a bit tricky.</p> <p>Then, your code will continue from where it left off each time <code>for</code> uses the generator.</p> <p>Now the hard part:</p> <p>The first time the <code>for</code> calls the generator object created from your function, it will run the code in your function from the beginning until it hits <code>yield</code>, then it'll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting <code>yield</code>. That can be because the loop has come to an end, or because you no longer satisfy an <code>"if/else"</code>.</p> <hr /> <h2>Your code explained</h2> <p><em>Generator:</em></p> <pre><code># Here you create the method of the node object that will return the generator def _get_child_candidates(self, distance, min_dist, max_dist): # Here is the code that will be called each time you use the generator object: # If there is still a child of the node object on its left # AND if the distance is ok, return the next child if self._leftchild and distance - max_dist < self._median: yield self._leftchild # If there is still a child of the node object on its right # AND if the distance is ok, return the next child if self._rightchild and distance + max_dist >= self._median: yield self._rightchild # If the function arrives here, the generator will be considered empty # There are no more than two values: the left and the right children </code></pre> <p><em>Caller:</em></p> <pre><code># Create an empty list and a list with the current object reference result, candidates = list(), [self] # Loop on candidates (they contain only one element at the beginning) while candidates: # Get the last candidate and remove it from the list node = candidates.pop() # Get the distance between obj and the candidate distance = node._get_dist(obj) # If the distance is ok, then you can fill in the result if distance <= max_dist and distance >= min_dist: result.extend(node._values) # Add the children of the candidate to the candidate's list # so the loop will keep running until it has looked # at all the children of the children of the children, etc. of the candidate candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) return result </code></pre> <p>This code contains several smart parts:</p> <ul> <li><p>The loop iterates on a list, but the list expands while the loop is being iterated. It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case, <code>candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))</code> exhausts all the values of the generator, but <code>while</code> keeps creating new generator objects which will produce different values from the previous ones since it's not applied on the same node.</p> </li> <li><p>The <code>extend()</code> method is a list object method that expects an iterable and adds its values to the list.</p> </li> </ul> <p>Usually, we pass a list to it:</p> <pre><code>>>> a = [1, 2] >>> b = [3, 4] >>> a.extend(b) >>> print(a) [1, 2, 3, 4] </code></pre> <p>But in your code, it gets a generator, which is good because:</p> <ol> <li>You don't need to read the values twice.</li> <li>You may have a lot of children and you don't want them all stored in memory.</li> </ol> <p>And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question...</p> <p>You can stop here, or read a little bit to see an advanced use of a generator:</p> <h2>Controlling a generator exhaustion</h2> <pre><code>>>> class Bank(): # Let's create a bank, building ATMs ... crisis = False ... def create_atm(self): ... while not self.crisis: ... yield "$100" >>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want >>> corner_street_atm = hsbc.create_atm() >>> print(corner_street_atm.next()) $100 >>> print(corner_street_atm.next()) $100 >>> print([corner_street_atm.next() for cash in range(5)]) ['$100', '$100', '$100', '$100', '$100'] >>> hsbc.crisis = True # Crisis is coming, no more money! >>> print(corner_street_atm.next()) <type 'exceptions.StopIteration'> >>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs >>> print(wall_street_atm.next()) <type 'exceptions.StopIteration'> >>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty >>> print(corner_street_atm.next()) <type 'exceptions.StopIteration'> >>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business >>> for cash in brand_new_atm: ... print cash $100 $100 $100 $100 $100 $100 $100 $100 $100 ... </code></pre> <p><strong>Note:</strong> For Python 3, use<code>print(corner_street_atm.__next__())</code> or <code>print(next(corner_street_atm))</code></p> <p>It can be useful for various things like controlling access to a resource.</p> <h2>Itertools, your best friend</h2> <p>The <code>itertools</code> module contains special functions to manipulate iterables. Ever wish to duplicate a generator? Chain two generators? Group values in a nested list with a one-liner? <code>Map / Zip</code> without creating another list?</p> <p>Then just <code>import itertools</code>.</p> <p>An example? Let's see the possible orders of arrival for a four-horse race:</p> <pre><code>>>> horses = [1, 2, 3, 4] >>> races = itertools.permutations(horses) >>> print(races) <itertools.permutations object at 0xb754f1dc> >>> print(list(itertools.permutations(horses))) [(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)] </code></pre> <h2>Understanding the inner mechanisms of iteration</h2> <p>Iteration is a process implying iterables (implementing the <code>__iter__()</code> method) and iterators (implementing the <code>__next__()</code> method). Iterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.</p> <p>There is more about it in this article about <a href=""https://web.archive.org/web/20201109034340/http://effbot.org/zone/python-for-statement.htm"" rel=""noreferrer"">how <code>for</code> loops work</a>.</p>"
|
3 |
+
https://stackoverflow.com/questions/419163/what-does-if-name-main-do,"<p>What does this do, and why should one include the <code>if</code> statement?</p> <pre class=""lang-py prettyprint-override""><code>if __name__ == "__main__": print("Hello, World!") </code></pre> <hr /> <p><sub>If you are trying to close a question where someone should be using this idiom and isn't, consider closing as a duplicate of <a href=""https://stackoverflow.com/questions/6523791"">Why is Python running my module when I import it, and how do I stop it?</a> instead. For questions where someone simply hasn't called any functions, or incorrectly expects a function named <code>main</code> to be used as an entry point automatically, use <a href=""https://stackoverflow.com/questions/17257631"">Why doesn't the main() function run when I start a Python script? Where does the script start running?</a>.</sub></p>","<h1>Short Answer</h1> <p>It's boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script:</p> <ul> <li><p>If you import the guardless script in another script (e.g. <code>import my_script_without_a_name_eq_main_guard</code>), then the latter script will trigger the former to run <em>at import time</em> and <em>using the second script's command line arguments</em>. This is almost always a mistake.</p> </li> <li><p>If you have a custom class in the guardless script and save it to a pickle file, then unpickling it in another script will trigger an import of the guardless script, with the same problems outlined in the previous bullet.</p> </li> </ul> <h1>Long Answer</h1> <p>To better understand why and how this matters, we need to take a step back to understand how Python initializes scripts and how this interacts with its module import mechanism.</p> <p>Whenever the Python interpreter reads a source file, it does two things:</p> <ul> <li><p>it sets a few special variables like <code>__name__</code>, and then</p> </li> <li><p>it executes all of the code found in the file.</p> </li> </ul> <p>Let's see how this works and how it relates to your question about the <code>__name__</code> checks we always see in Python scripts.</p> <h2>Code Sample</h2> <p>Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called <code>foo.py</code>.</p> <pre><code># Suppose this is foo.py. print("before import") import math print("before function_a") def function_a(): print("Function A") print("before function_b") def function_b(): print("Function B {}".format(math.sqrt(100))) print("before __name__ guard") if __name__ == '__main__': function_a() function_b() print("after __name__ guard") </code></pre> <h2>Special Variables</h2> <p>When the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the <code>__name__</code> variable.</p> <p><strong>When Your Module Is the Main Program</strong></p> <p>If you are running your module (the source file) as the main program, e.g.</p> <pre><code>python foo.py </code></pre> <p>the interpreter will assign the hard-coded string <code>"__main__"</code> to the <code>__name__</code> variable, i.e.</p> <pre><code># It's as if the interpreter inserts this at the top # of your module when run as the main program. __name__ = "__main__" </code></pre> <p><strong>When Your Module Is Imported By Another</strong></p> <p>On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:</p> <pre><code># Suppose this is in some other main program. import foo </code></pre> <p>The interpreter will search for your <code>foo.py</code> file (along with searching for a few other variants), and prior to executing that module, it will assign the name <code>"foo"</code> from the import statement to the <code>__name__</code> variable, i.e.</p> <pre><code># It's as if the interpreter inserts this at the top # of your module when it's imported from another module. __name__ = "foo" </code></pre> <h2>Executing the Module's Code</h2> <p>After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.</p> <p><strong>Always</strong></p> <ol> <li><p>It prints the string <code>"before import"</code> (without quotes).</p> </li> <li><p>It loads the <code>math</code> module and assigns it to a variable called <code>math</code>. This is equivalent to replacing <code>import math</code> with the following (note that <code>__import__</code> is a low-level function in Python that takes a string and triggers the actual import):</p> </li> </ol> <pre><code># Find and load a module given its string name, "math", # then assign it to a local variable called math. math = __import__("math") </code></pre> <ol start=""3""> <li><p>It prints the string <code>"before function_a"</code>.</p> </li> <li><p>It executes the <code>def</code> block, creating a function object, then assigning that function object to a variable called <code>function_a</code>.</p> </li> <li><p>It prints the string <code>"before function_b"</code>.</p> </li> <li><p>It executes the second <code>def</code> block, creating another function object, then assigning it to a variable called <code>function_b</code>.</p> </li> <li><p>It prints the string <code>"before __name__ guard"</code>.</p> </li> </ol> <p><strong>Only When Your Module Is the Main Program</strong></p> <ol start=""8""> <li>If your module is the main program, then it will see that <code>__name__</code> was indeed set to <code>"__main__"</code> and it calls the two functions, printing the strings <code>"Function A"</code> and <code>"Function B 10.0"</code>.</li> </ol> <p><strong>Only When Your Module Is Imported by Another</strong></p> <ol start=""8""> <li>(<strong>instead</strong>) If your module is not the main program but was imported by another one, then <code>__name__</code> will be <code>"foo"</code>, not <code>"__main__"</code>, and it'll skip the body of the <code>if</code> statement.</li> </ol> <p><strong>Always</strong></p> <ol start=""9""> <li>It will print the string <code>"after __name__ guard"</code> in both situations.</li> </ol> <p><em><strong>Summary</strong></em></p> <p>In summary, here's what'd be printed in the two cases:</p> <pre class=""lang-none prettyprint-override""><code># What gets printed if foo is the main program before import before function_a before function_b before __name__ guard Function A Function B 10.0 after __name__ guard </code></pre> <pre class=""lang-none prettyprint-override""><code># What gets printed if foo is imported as a regular module before import before function_a before function_b before __name__ guard after __name__ guard </code></pre> <h2>Why Does It Work This Way?</h2> <p>You might naturally wonder why anybody would want this. Well, sometimes you want to write a <code>.py</code> file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself. Examples:</p> <ul> <li><p>Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.</p> </li> <li><p>Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing <code>.py</code> files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.</p> </li> <li><p>Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.</p> </li> </ul> <p>Beyond those examples, it's elegant that running a script in Python is just setting up a few magic variables and importing the script. "Running" the script is a side effect of importing the script's module.</p> <h2>Food for Thought</h2> <ul> <li><p>Question: Can I have multiple <code>__name__</code> checking blocks? Answer: it's strange to do so, but the language won't stop you.</p> </li> <li><p>Suppose the following is in <code>foo2.py</code>. What happens if you say <code>python foo2.py</code> on the command-line? Why?</p> </li> </ul> <pre class=""lang-py prettyprint-override""><code># Suppose this is foo2.py. import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters def function_a(): print("a1") from foo2 import function_b print("a2") function_b() print("a3") def function_b(): print("b") print("t1") if __name__ == "__main__": print("m1") function_a() print("m2") print("t2") </code></pre> <ul> <li>Now, figure out what will happen in <code>foo3.py</code> (having removed the <code>__name__</code> check):</li> </ul> <pre class=""lang-py prettyprint-override""><code># Suppose this is foo3.py. import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters def function_a(): print("a1") from foo3 import function_b print("a2") function_b() print("a3") def function_b(): print("b") print("t1") print("m1") function_a() print("m2") print("t2") </code></pre> <ul> <li>What will this do when used as a script? When imported as a module?</li> </ul> <pre class=""lang-py prettyprint-override""><code># Suppose this is in foo4.py __name__ = "__main__" def bar(): print("bar") print("before __name__ guard") if __name__ == "__main__": bar() print("after __name__ guard") </code></pre>"
|
4 |
+
https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator,"<p>Is there a <a href=""https://en.wikipedia.org/wiki/%3F:#Python"" rel=""noreferrer"">ternary conditional operator</a> in Python?</p>","<p>Yes, it was <a href=""https://mail.python.org/pipermail/python-dev/2005-September/056846.html"" rel=""noreferrer"" title=""[Python-Dev] Conditional Expression Resolution"">added</a> in version 2.5. The expression syntax is:</p> <pre class=""lang-py prettyprint-override""><code>a if condition else b </code></pre> <p>First <code>condition</code> is evaluated, then exactly one of either <code>a</code> or <code>b</code> is evaluated and returned based on the <a href=""https://en.wikipedia.org/wiki/Boolean_data_type"" rel=""noreferrer"" title=""Boolean data type"">Boolean</a> value of <code>condition</code>. If <code>condition</code> evaluates to <code>True</code>, then <code>a</code> is evaluated and returned but <code>b</code> is ignored, or else when <code>b</code> is evaluated and returned but <code>a</code> is ignored.</p> <p>This allows short-circuiting because when <code>condition</code> is true only <code>a</code> is evaluated and <code>b</code> is not evaluated at all, but when <code>condition</code> is false only <code>b</code> is evaluated and <code>a</code> is not evaluated at all.</p> <p>For example:</p> <pre class=""lang-py prettyprint-override""><code>>>> 'true' if True else 'false' 'true' >>> 'true' if False else 'false' 'false' </code></pre> <p>Note that conditionals are an <em>expression</em>, not a <em>statement</em>. This means you can't use <strong>statements</strong> such as <code>pass</code>, or assignments with <code>=</code> (or "augmented" assignments like <code>+=</code>), within a conditional <strong>expression</strong>:</p> <pre class=""lang-py prettyprint-override""><code>>>> pass if False else pass File "<stdin>", line 1 pass if False else pass ^ SyntaxError: invalid syntax >>> # Python parses this as `x = (1 if False else y) = 2` >>> # The `(1 if False else x)` part is actually valid, but >>> # it can't be on the left-hand side of `=`. >>> x = 1 if False else y = 2 File "<stdin>", line 1 SyntaxError: cannot assign to conditional expression >>> # If we parenthesize it instead... >>> (x = 1) if False else (y = 2) File "<stdin>", line 1 (x = 1) if False else (y = 2) ^ SyntaxError: invalid syntax </code></pre> <p>(In 3.8 and above, the <code>:=</code> "walrus" operator allows simple assignment of values <em>as an expression</em>, which is then compatible with this syntax. But please don't write code like that; it will quickly become very difficult to understand.)</p> <p>Similarly, because it is an expression, the <code>else</code> part is <em>mandatory</em>:</p> <pre><code># Invalid syntax: we didn't specify what the value should be if the # condition isn't met. It doesn't matter if we can verify that # ahead of time. a if True </code></pre> <p>You can, however, use conditional expressions to assign a variable like so:</p> <pre class=""lang-py prettyprint-override""><code>x = a if True else b </code></pre> <p>Or for example to return a value:</p> <pre><code># Of course we should just use the standard library `max`; # this is just for demonstration purposes. def my_max(a, b): return a if a > b else b </code></pre> <p>Think of the conditional expression as switching between two values. We can use it when we are in a 'one value or another' situation, where we will <em>do the same thing</em> with the result, regardless of whether the condition is met. We use the expression to compute the value, and then do something with it. If you need to <em>do something different</em> depending on the condition, then use a normal <code>if</code> <strong>statement</strong> instead.</p> <hr /> <p>Keep in mind that it's frowned upon by some Pythonistas for several reasons:</p> <ul> <li>The order of the arguments is different from those of the classic <code>condition ? a : b</code> ternary operator from many other languages (such as <a href=""https://en.wikipedia.org/wiki/C_%28programming_language%29"" rel=""noreferrer"">C</a>, <a href=""https://en.wikipedia.org/wiki/C%2B%2B"" rel=""noreferrer"">C++</a>, <a href=""https://en.wikipedia.org/wiki/Go_%28programming_language%29"" rel=""noreferrer"">Go</a>, <a href=""https://en.wikipedia.org/wiki/Perl"" rel=""noreferrer"">Perl</a>, <a href=""https://en.wikipedia.org/wiki/Ruby_%28programming_language%29"" rel=""noreferrer"">Ruby</a>, <a href=""https://en.wikipedia.org/wiki/Java_%28programming_language%29"" rel=""noreferrer"">Java</a>, <a href=""https://en.wikipedia.org/wiki/JavaScript"" rel=""noreferrer"">JavaScript</a>, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the argument order).</li> <li>Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).</li> <li>Stylistic reasons. (Although the 'inline <code>if</code>' can be <em>really</em> useful, and make your script more concise, it really does complicate your code)</li> </ul> <p>If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example, <code>x = 4 if b > 8 else 9</code> is read aloud as <code>x will be 4 if b is greater than 8 otherwise 9</code>.</p> <p>Official documentation:</p> <ul> <li><a href=""https://docs.python.org/3/reference/expressions.html#conditional-expressions"" rel=""noreferrer"" title=""Conditional expressions"">Conditional expressions</a></li> <li><a href=""https://docs.python.org/3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator"" rel=""noreferrer"" title=""Is there an equivalent of C’s ”?:” ternary operator?"">Is there an equivalent of C’s ”?:” ternary operator?</a></li> </ul>"
|
5 |
+
https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python,"<p>What are <a href=""https://docs.python.org/3/reference/datamodel.html#metaclasses"" rel=""noreferrer"">metaclasses</a>? What are they used for?</p>","<p>A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.</p> <p>While in Python you can use arbitrary callables for metaclasses (like <a href=""https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/100037#100037"">Jerub</a> shows), the better approach is to make it an actual class itself. <code>type</code> is the usual metaclass in Python. <code>type</code> is itself a class, and it is its own type. You won't be able to recreate something like <code>type</code> purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass <code>type</code>.</p> <p>A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the normal <code>__init__</code> and <code>__new__</code> methods, metaclasses therefore allow you to do 'extra things' when creating a class, like registering the new class with some registry or replace the class with something else entirely.</p> <p>When the <code>class</code> statement is executed, Python first executes the body of the <code>class</code> statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the <code>__metaclass__</code> attribute of the class-to-be (if any) or the <code>__metaclass__</code> global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.</p> <p>However, metaclasses actually define the <em>type</em> of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass. These metaclass-methods are like classmethods in that they can be called on the class without an instance, but they are also not like classmethods in that they cannot be called on an instance of the class. <code>type.__subclasses__()</code> is an example of a method on the <code>type</code> metaclass. You can also define the normal 'magic' methods, like <code>__add__</code>, <code>__iter__</code> and <code>__getattr__</code>, to implement or change how the class behaves.</p> <p>Here's an aggregated example of the bits and pieces:</p> <pre><code>def make_hook(f): """"""Decorator to turn 'foo' method into '__foo__'"""""" f.is_hook = 1 return f class MyType(type): def __new__(mcls, name, bases, attrs): if name.startswith('None'): return None # Go over attributes and see if they should be renamed. newattrs = {} for attrname, attrvalue in attrs.iteritems(): if getattr(attrvalue, 'is_hook', 0): newattrs['__%s__' % attrname] = attrvalue else: newattrs[attrname] = attrvalue return super(MyType, mcls).__new__(mcls, name, bases, newattrs) def __init__(self, name, bases, attrs): super(MyType, self).__init__(name, bases, attrs) # classregistry.register(self, self.interfaces) print ""Would register class %s now."" % self def __add__(self, other): class AutoClass(self, other): pass return AutoClass # Alternatively, to autogenerate the classname as well as the class: # return type(self.__name__ + other.__name__, (self, other), {}) def unregister(self): # classregistry.unregister(self) print ""Would unregister class %s now."" % self class MyObject: __metaclass__ = MyType class NoneSample(MyObject): pass # Will print ""NoneType None"" print type(NoneSample), repr(NoneSample) class Example(MyObject): def __init__(self, value): self.value = value @make_hook def add(self, other): return self.__class__(self.value + other.value) # Will unregister the class Example.unregister() inst = Example(10) # Will fail with an AttributeError #inst.unregister() print inst + inst class Sibling(MyObject): pass ExampleSibling = Example + Sibling # ExampleSibling is now a subclass of both Example and Sibling (with no # content of its own) although it will believe it's called 'AutoClass' print ExampleSibling print ExampleSibling.__mro__ </code></pre>"
|
6 |
+
https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python,"<p>I want to merge two dictionaries into a new dictionary.</p> <pre><code>x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} z = merge(x, y) >>> z {'a': 1, 'b': 3, 'c': 4} </code></pre> <p>Whenever a key <code>k</code> is present in both dictionaries, only the value <code>y[k]</code> should be kept.</p>","<h2>How can I merge two Python dictionaries in a single expression?</h2> <p>For dictionaries <code>x</code> and <code>y</code>, their shallowly-merged dictionary <code>z</code> takes values from <code>y</code>, replacing those from <code>x</code>.</p> <ul> <li><p>In Python 3.9.0 or greater (released 17 October 2020, <a href=""https://www.python.org/dev/peps/pep-0584/"" rel=""noreferrer""><code>PEP-584</code></a>, <a href=""https://bugs.python.org/issue36144"" rel=""noreferrer"">discussed here</a>):</p> <pre class=""lang-py prettyprint-override""><code>z = x | y </code></pre> </li> <li><p>In Python 3.5 or greater:</p> <pre class=""lang-py prettyprint-override""><code>z = {**x, **y} </code></pre> </li> <li><p>In Python 2, (or 3.4 or lower) write a function:</p> <pre class=""lang-py prettyprint-override""><code>def merge_two_dicts(x, y): z = x.copy() # start with keys and values of x z.update(y) # modifies z with keys and values of y return z </code></pre> <p>and now:</p> <pre class=""lang-py prettyprint-override""><code>z = merge_two_dicts(x, y) </code></pre> </li> </ul> <h3>Explanation</h3> <p>Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:</p> <pre class=""lang-py prettyprint-override""><code>x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} </code></pre> <p>The desired result is to get a new dictionary (<code>z</code>) with the values merged, and the second dictionary's values overwriting those from the first.</p> <pre class=""lang-py prettyprint-override""><code>>>> z {'a': 1, 'b': 3, 'c': 4} </code></pre> <p>A new syntax for this, proposed in <a href=""https://www.python.org/dev/peps/pep-0448"" rel=""noreferrer"">PEP 448</a> and <a href=""https://mail.python.org/pipermail/python-dev/2015-February/138564.html"" rel=""noreferrer"">available as of Python 3.5</a>, is</p> <pre class=""lang-py prettyprint-override""><code>z = {**x, **y} </code></pre> <p>And it is indeed a single expression.</p> <p>Note that we can merge in with literal notation as well:</p> <pre class=""lang-py prettyprint-override""><code>z = {**x, 'foo': 1, 'bar': 2, **y} </code></pre> <p>and now:</p> <pre class=""lang-py prettyprint-override""><code>>>> z {'a': 1, 'b': 3, 'foo': 1, 'bar': 2, 'c': 4} </code></pre> <p>It is now showing as implemented in the <a href=""https://www.python.org/dev/peps/pep-0478/#features-for-3-5"" rel=""noreferrer"">release schedule for 3.5, PEP 478</a>, and it has now made its way into the <a href=""https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations"" rel=""noreferrer"">What's New in Python 3.5</a> document.</p> <p>However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:</p> <pre class=""lang-py prettyprint-override""><code>z = x.copy() z.update(y) # which returns None since it mutates z </code></pre> <p>In both approaches, <code>y</code> will come second and its values will replace <code>x</code>'s values, thus <code>b</code> will point to <code>3</code> in our final result.</p> <h2>Not yet on Python 3.5, but want a <em>single expression</em></h2> <p>If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a <em>single expression</em>, the most performant while the correct approach is to put it in a function:</p> <pre class=""lang-py prettyprint-override""><code>def merge_two_dicts(x, y): """Given two dictionaries, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z </code></pre> <p>and then you have a single expression:</p> <pre class=""lang-py prettyprint-override""><code>z = merge_two_dicts(x, y) </code></pre> <p>You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:</p> <pre class=""lang-py prettyprint-override""><code>def merge_dicts(*dict_args): """ Given any number of dictionaries, shallow copy and merge into a new dict, precedence goes to key-value pairs in latter dictionaries. """ result = {} for dictionary in dict_args: result.update(dictionary) return result </code></pre> <p>This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries <code>a</code> to <code>g</code>:</p> <pre class=""lang-py prettyprint-override""><code>z = merge_dicts(a, b, c, d, e, f, g) </code></pre> <p>and key-value pairs in <code>g</code> will take precedence over dictionaries <code>a</code> to <code>f</code>, and so on.</p> <h2>Critiques of Other Answers</h2> <p>Don't use what you see in the formerly accepted answer:</p> <pre class=""lang-py prettyprint-override""><code>z = dict(x.items() + y.items()) </code></pre> <p>In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. <strong>In Python 3, this will fail</strong> because you're adding two <code>dict_items</code> objects together, not two lists -</p> <pre class=""lang-py prettyprint-override""><code>>>> c = dict(a.items() + b.items()) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items' </code></pre> <p>and you would have to explicitly create them as lists, e.g. <code>z = dict(list(x.items()) + list(y.items()))</code>. This is a waste of resources and computation power.</p> <p>Similarly, taking the union of <code>items()</code> in Python 3 (<code>viewitems()</code> in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, <strong>since sets are semantically unordered, the behavior is undefined in regards to precedence. So don't do this:</strong></p> <pre class=""lang-py prettyprint-override""><code>>>> c = dict(a.items() | b.items()) </code></pre> <p>This example demonstrates what happens when values are unhashable:</p> <pre class=""lang-py prettyprint-override""><code>>>> x = {'a': []} >>> y = {'b': []} >>> dict(x.items() | y.items()) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' </code></pre> <p>Here's an example where <code>y</code> should have precedence, but instead the value from <code>x</code> is retained due to the arbitrary order of sets:</p> <pre class=""lang-py prettyprint-override""><code>>>> x = {'a': 2} >>> y = {'a': 1} >>> dict(x.items() | y.items()) {'a': 2} </code></pre> <p>Another hack you should not use:</p> <pre class=""lang-py prettyprint-override""><code>z = dict(x, **y) </code></pre> <p>This uses the <code>dict</code> constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it's difficult to read, it's not the intended usage, and so it is not Pythonic.</p> <p>Here's an example of the usage being <a href=""https://code.djangoproject.com/attachment/ticket/13357/django-pypy.2.diff"" rel=""noreferrer"">remediated in django</a>.</p> <p>Dictionaries are intended to take hashable keys (e.g. <code>frozenset</code>s or tuples), but <strong>this method fails in Python 3 when keys are not strings.</strong></p> <pre class=""lang-py prettyprint-override""><code>>>> c = dict(a, **b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: keyword arguments must be strings </code></pre> <p>From the <a href=""https://mail.python.org/pipermail/python-dev/2010-April/099459.html"" rel=""noreferrer"">mailing list</a>, Guido van Rossum, the creator of the language, wrote:</p> <blockquote> <p>I am fine with declaring dict({}, **{1:3}) illegal, since after all it is abuse of the ** mechanism.</p> </blockquote> <p>and</p> <blockquote> <p>Apparently dict(x, **y) is going around as "cool hack" for "call x.update(y) and return x". Personally, I find it more despicable than cool.</p> </blockquote> <p>It is my understanding (as well as the understanding of the <a href=""https://mail.python.org/pipermail/python-dev/2010-April/099485.html"" rel=""noreferrer"">creator of the language</a>) that the intended usage for <code>dict(**y)</code> is for creating dictionaries for readability purposes, e.g.:</p> <pre class=""lang-py prettyprint-override""><code>dict(a=1, b=10, c=11) </code></pre> <p>instead of</p> <pre class=""lang-py prettyprint-override""><code>{'a': 1, 'b': 10, 'c': 11} </code></pre> <h2>Response to comments</h2> <blockquote> <p>Despite what Guido says, <code>dict(x, **y)</code> is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.</p> </blockquote> <p>Again, it doesn't work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. <code>dict</code> broke this consistency in Python 2:</p> <pre><code>>>> foo(**{('a', 'b'): None}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() keywords must be strings >>> dict(**{('a', 'b'): None}) {('a', 'b'): None} </code></pre> <p>This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.</p> <p>I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.</p> <p>More comments:</p> <blockquote> <p><code>dict(x.items() + y.items())</code> is still the most readable solution for Python 2. Readability counts.</p> </blockquote> <p>My response: <code>merge_two_dicts(x, y)</code> actually seems much clearer to me, if we're actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.</p> <blockquote> <p><code>{**x, **y}</code> does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging.</p> </blockquote> <p>Yes. I must refer you back to the question, which is asking for a <em>shallow</em> merge of <em><strong>two</strong></em> dictionaries, with the first's values being overwritten by the second's - in a single expression.</p> <p>Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:</p> <pre class=""lang-py prettyprint-override""><code>from copy import deepcopy def dict_of_dicts_merge(x, y): z = {} overlapping_keys = x.keys() & y.keys() for key in overlapping_keys: z[key] = dict_of_dicts_merge(x[key], y[key]) for key in x.keys() - overlapping_keys: z[key] = deepcopy(x[key]) for key in y.keys() - overlapping_keys: z[key] = deepcopy(y[key]) return z </code></pre> <p>Usage:</p> <pre class=""lang-py prettyprint-override""><code>>>> x = {'a':{1:{}}, 'b': {2:{}}} >>> y = {'b':{10:{}}, 'c': {11:{}}} >>> dict_of_dicts_merge(x, y) {'b': {2: {}, 10: {}}, 'a': {1: {}}, 'c': {11: {}}} </code></pre> <p>Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at <a href=""https://stackoverflow.com/a/24088493/541136"">my answer to the canonical question on a "Dictionaries of dictionaries merge"</a>.</p> <h2>Less Performant But Correct Ad-hocs</h2> <p>These approaches are less performant, but they will provide correct behavior. They will be <em>much less</em> performant than <code>copy</code> and <code>update</code> or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they <em>do</em> respect the order of precedence (latter dictionaries have precedence)</p> <p>You can also chain the dictionaries manually inside a <a href=""https://www.python.org/dev/peps/pep-0274/"" rel=""noreferrer"">dict comprehension</a>:</p> <pre class=""lang-py prettyprint-override""><code>{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7 </code></pre> <p>or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):</p> <pre class=""lang-py prettyprint-override""><code>dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2 </code></pre> <p><code>itertools.chain</code> will chain the iterators over the key-value pairs in the correct order:</p> <pre class=""lang-py prettyprint-override""><code>from itertools import chain z = dict(chain(x.items(), y.items())) # iteritems in Python 2 </code></pre> <h2>Performance Analysis</h2> <p>I'm only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)</p> <pre class=""lang-py prettyprint-override""><code>from timeit import repeat from itertools import chain x = dict.fromkeys('abcdefg') y = dict.fromkeys('efghijk') def merge_two_dicts(x, y): z = x.copy() z.update(y) return z min(repeat(lambda: {**x, **y})) min(repeat(lambda: merge_two_dicts(x, y))) min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()})) min(repeat(lambda: dict(chain(x.items(), y.items())))) min(repeat(lambda: dict(item for d in (x, y) for item in d.items()))) </code></pre> <p>In Python 3.8.1, NixOS:</p> <pre class=""lang-py prettyprint-override""><code>>>> min(repeat(lambda: {**x, **y})) 1.0804965235292912 >>> min(repeat(lambda: merge_two_dicts(x, y))) 1.636518670246005 >>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()})) 3.1779992282390594 >>> min(repeat(lambda: dict(chain(x.items(), y.items())))) 2.740647904574871 >>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items()))) 4.266070580109954 </code></pre> <pre class=""lang-sh prettyprint-override""><code>$ uname -a Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux </code></pre> <h2>Resources on Dictionaries</h2> <ul> <li><a href=""https://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented/44509302#44509302"">My explanation of Python's <strong>dictionary implementation</strong>, updated for 3.6.</a></li> <li><a href=""https://stackoverflow.com/questions/1024847/add-new-keys-to-a-dictionary/27208535#27208535"">Answer on how to add new keys to a dictionary</a></li> <li><a href=""https://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python/33737067#33737067"">Mapping two lists into a dictionary</a></li> <li><a href=""https://docs.python.org/3/tutorial/datastructures.html#dictionaries"" rel=""noreferrer"">The official Python docs on dictionaries</a></li> <li><a href=""https://www.youtube.com/watch?v=66P5FMkWoVU"" rel=""noreferrer"">The Dictionary Even Mightier</a> - talk by Brandon Rhodes at Pycon 2017</li> <li><a href=""https://www.youtube.com/watch?v=npw4s1QTmPg"" rel=""noreferrer"">Modern Python Dictionaries, A Confluence of Great Ideas</a> - talk by Raymond Hettinger at Pycon 2017</li> </ul>"
|
7 |
+
https://stackoverflow.com/questions/89228/how-do-i-execute-a-program-or-call-a-system-command,<p>How do I call an external command within Python as if I had typed it in a shell or command prompt?</p>,"<p>Use <a href=""https://docs.python.org/library/subprocess.html#subprocess.run"" rel=""noreferrer""><code>subprocess.run</code></a>:</p> <pre class=""lang-py prettyprint-override""><code>import subprocess subprocess.run(["ls", "-l"]) </code></pre> <p>Another common way is <a href=""https://docs.python.org/library/os.html#os.system"" rel=""noreferrer""><code>os.system</code></a> but you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also <code>subprocess.run</code> is generally more flexible (you can get the <a href=""https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stdout"" rel=""noreferrer""><code>stdout</code></a>, <a href=""https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stderr"" rel=""noreferrer""><code>stderr</code></a>, the <a href=""https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.returncode"" rel=""noreferrer"">"real" status code</a>, better <a href=""https://docs.python.org/library/subprocess.html#subprocess.CalledProcessError"" rel=""noreferrer"">error handling</a>, etc.). Even the <a href=""https://docs.python.org/library/os.html#os.system"" rel=""noreferrer"">documentation for <code>os.system</code></a> recommends using <code>subprocess</code> instead.</p> <p>On Python 3.4 and earlier, use <code>subprocess.call</code> instead of <code>.run</code>:</p> <pre class=""lang-py prettyprint-override""><code>subprocess.call(["ls", "-l"]) </code></pre>"
|
8 |
+
https://stackoverflow.com/questions/273192/how-do-i-create-a-directory-and-any-missing-parent-directories,"<p>How do I create a directory at a given path, and also create any missing parent directories along that path? For example, the Bash command <code>mkdir -p /path/to/nested/directory</code> does this.</p>","<p>On Python ≥ 3.5, use <a href=""https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir"" rel=""noreferrer""><code>pathlib.Path.mkdir</code></a>:</p> <pre><code>from pathlib import Path Path(""/my/directory"").mkdir(parents=True, exist_ok=True) </code></pre> <p>For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:</p> <p>Try <a href=""https://docs.python.org/library/os.path.html#os.path.exists"" rel=""noreferrer""><code>os.path.exists</code></a>, and consider <a href=""https://docs.python.org/library/os.html#os.makedirs"" rel=""noreferrer""><code>os.makedirs</code></a> for the creation.</p> <pre><code>import os if not os.path.exists(directory): os.makedirs(directory) </code></pre> <p>As noted in comments and elsewhere, there's a race condition – if the directory is created between the <code>os.path.exists</code> and the <code>os.makedirs</code> calls, the <code>os.makedirs</code> will fail with an <code>OSError</code>. Unfortunately, blanket-catching <code>OSError</code> and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.</p> <p>One option would be to trap the <code>OSError</code> and examine the embedded error code (see <a href=""https://stackoverflow.com/questions/273698/is-there-a-cross-platform-way-of-getting-information-from-pythons-oserror"">Is there a cross-platform way of getting information from Python’s OSError</a>):</p> <pre><code>import os, errno try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise </code></pre> <p>Alternatively, there could be a second <code>os.path.exists</code>, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled. </p> <p>Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.</p> <p>Modern versions of Python improve this code quite a bit, both by exposing <a href=""https://docs.python.org/3.3/library/exceptions.html?#FileExistsError"" rel=""noreferrer""><code>FileExistsError</code></a> (in 3.3+)...</p> <pre><code>try: os.makedirs(""path/to/directory"") except FileExistsError: # directory already exists pass </code></pre> <p>...and by allowing <a href=""https://docs.python.org/3.2/library/os.html#os.makedirs"" rel=""noreferrer"">a keyword argument to <code>os.makedirs</code> called <code>exist_ok</code></a> (in 3.2+).</p> <pre><code>os.makedirs(""path/to/directory"", exist_ok=True) # succeeds even if directory exists. </code></pre>"
|
9 |
+
https://stackoverflow.com/questions/522563/how-to-access-the-index-value-in-a-for-loop,"<p>How do I access the index while iterating over a sequence with a <code>for</code> loop?</p> <pre class=""lang-py prettyprint-override""><code>xs = [8, 23, 45] for x in xs: print("item #{} = {}".format(index, x)) </code></pre> <p>Desired output:</p> <pre class=""lang-none prettyprint-override""><code>item #1 = 8 item #2 = 23 item #3 = 45 </code></pre>","<p>Use the built-in function <a href=""https://docs.python.org/3/library/functions.html#enumerate"" rel=""noreferrer"" title=""enumerate""><code>enumerate()</code></a>:</p> <pre><code>for idx, x in enumerate(xs): print(idx, x) </code></pre> <p>It is <em><a href=""https://stackoverflow.com/questions/25011078/what-does-pythonic-mean"">non-pythonic</a></em> to manually index via <code>for i in range(len(xs)): x = xs[i]</code> or manually manage an additional state variable.</p> <p>Check out <a href=""https://www.python.org/dev/peps/pep-0279/"" rel=""noreferrer"" title=""PEP 279"">PEP 279</a> for more.</p>"
|
10 |
+
https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists,"<p>I have a list of lists like</p> <pre><code>[ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] </code></pre> <p>How can I flatten it to get <code>[1, 2, 3, 4, 5, 6, 7, 8, 9]</code>?</p> <hr /> <p><sub>If your list of lists comes from a nested list comprehension, the problem can be solved more simply/directly by fixing the comprehension; please see <a href=""https://stackoverflow.com/questions/1077015"">How can I get a flat result from a list comprehension instead of a nested list?</a>.</sub></p> <p><sub>The most popular solutions here generally only flatten one "level" of the nested list. See <a href=""https://stackoverflow.com/questions/2158395"">Flatten an irregular (arbitrarily nested) list of lists</a> for solutions that completely flatten a deeply nested structure (recursively, in general).</sub></p>","<p>A list of lists named <code>xss</code> can be flattened using a nested <a href=""https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions"" rel=""noreferrer"">list comprehension</a>:</p> <pre><code>flat_list = [ x for xs in xss for x in xs ] </code></pre> <p>The above is equivalent to:</p> <pre><code>flat_list = [] for xs in xss: for x in xs: flat_list.append(x) </code></pre> <p>Here is the corresponding function:</p> <pre><code>def flatten(xss): return [x for xs in xss for x in xs] </code></pre> <p>This is the fastest method. As evidence, using the <a href=""https://docs.python.org/3/library/timeit.html"" rel=""noreferrer""><code>timeit</code></a> module in the standard library, we see:</p> <pre class=""lang-bash prettyprint-override""><code>$ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' '[x for xs in xss for x in xs]' 10000 loops, best of 3: 143 usec per loop $ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' 'sum(xss, [])' 1000 loops, best of 3: 969 usec per loop $ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' 'reduce(lambda xs, ys: xs + ys, xss)' 1000 loops, best of 3: 1.1 msec per loop </code></pre> <p>Explanation: the methods based on <code>+</code> (including the implied use in <code>sum</code>) are, of necessity, <code>O(L**2)</code> when there are L sublists -- as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So, for simplicity and without actual loss of generality, say you have L sublists of M items each: the first M items are copied back and forth <code>L-1</code> times, the second M items <code>L-2</code> times, and so on; total number of copies is M times the sum of x for x from 1 to L excluded, i.e., <code>M * (L**2)/2</code>.</p> <p>The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.</p>"
|
11 |
+
https://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python,"<p>What is the difference between a method <a href=""https://peps.python.org/pep-0318/"" rel=""noreferrer"">decorated</a> with <a href=""http://docs.python.org/library/functions.html#staticmethod"" rel=""noreferrer""><code>@staticmethod</code></a> and one decorated with <a href=""http://docs.python.org/library/functions.html#classmethod"" rel=""noreferrer""><code>@classmethod</code></a>?</p>","<p>Maybe a bit of example code will help: Notice the difference in the call signatures of <code>foo</code>, <code>class_foo</code> and <code>static_foo</code>:</p> <pre><code>class A(object): def foo(self, x): print(f"executing foo({self}, {x})") @classmethod def class_foo(cls, x): print(f"executing class_foo({cls}, {x})") @staticmethod def static_foo(x): print(f"executing static_foo({x})") a = A() </code></pre> <p>Below is the usual way an object instance calls a method. The object instance, <code>a</code>, is implicitly passed as the first argument.</p> <pre><code>a.foo(1) # executing foo(<__main__.A object at 0xb7dbef0c>, 1) </code></pre> <hr /> <p><strong>With classmethods</strong>, the class of the object instance is implicitly passed as the first argument instead of <code>self</code>.</p> <pre><code>a.class_foo(1) # executing class_foo(<class '__main__.A'>, 1) </code></pre> <p>You can also call <code>class_foo</code> using the class. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance. <code>A.foo(1)</code> would have raised a TypeError, but <code>A.class_foo(1)</code> works just fine:</p> <pre><code>A.class_foo(1) # executing class_foo(<class '__main__.A'>, 1) </code></pre> <p>One use people have found for class methods is to create <a href=""https://stackoverflow.com/a/1950927/190597"">inheritable alternative constructors</a>.</p> <hr /> <p><strong>With staticmethods</strong>, neither <code>self</code> (the object instance) nor <code>cls</code> (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:</p> <pre><code>a.static_foo(1) # executing static_foo(1) A.static_foo('hi') # executing static_foo(hi) </code></pre> <p>Staticmethods are used to group functions which have some logical connection with a class to the class.</p> <hr /> <p><code>foo</code> is just a function, but when you call <code>a.foo</code> you don't just get the function, you get a "partially applied" version of the function with the object instance <code>a</code> bound as the first argument to the function. <code>foo</code> expects 2 arguments, while <code>a.foo</code> only expects 1 argument.</p> <p><code>a</code> is bound to <code>foo</code>. That is what is meant by the term "bound" below:</p> <pre><code>print(a.foo) # <bound method A.foo of <__main__.A object at 0xb7d52f0c>> </code></pre> <p>With <code>a.class_foo</code>, <code>a</code> is not bound to <code>class_foo</code>, rather the class <code>A</code> is bound to <code>class_foo</code>.</p> <pre><code>print(a.class_foo) # <bound method type.class_foo of <class '__main__.A'>> </code></pre> <p>Here, with a staticmethod, even though it is a method, <code>a.static_foo</code> just returns a good 'ole function with no arguments bound. <code>static_foo</code> expects 1 argument, and <code>a.static_foo</code> expects 1 argument too.</p> <pre><code>print(a.static_foo) # <function static_foo at 0xb7d479cc> </code></pre> <p>And of course the same thing happens when you call <code>static_foo</code> with the class <code>A</code> instead.</p> <pre><code>print(A.static_foo) # <function static_foo at 0xb7d479cc> </code></pre>"
|
12 |
+
https://stackoverflow.com/questions/509211/how-slicing-in-python-works,"<p>How does Python's <em>slice notation</em> work? That is: when I write code like <code>a[x:y:z]</code>, <code>a[:]</code>, <code>a[::2]</code> etc., how can I understand which elements end up in the slice?</p> <hr /> <p><sub>See <a href=""https://stackoverflow.com/questions/11364533"">Why are slice and range upper-bound exclusive?</a> to learn why <code>xs[0:2] == [xs[0], xs[1]]</code>, <em>not</em> <code>[..., xs[2]]</code>.</sub><br /> <sub>See <a href=""https://stackoverflow.com/questions/1403674/"">Make a new list containing every Nth item in the original list</a> for <code>xs[::N]</code>.</sub><br /> <sub>See <a href=""https://stackoverflow.com/questions/10623302"">How does assignment work with list slices?</a> to learn what <code>xs[0:2] = ["a", "b"]</code> does.</sub></p>","<p>The syntax is:</p> <pre><code>a[start:stop] # items start through stop-1 a[start:] # items start through the rest of the array a[:stop] # items from the beginning through stop-1 a[:] # a copy of the whole array </code></pre> <p>There is also the <code>step</code> value, which can be used with any of the above:</p> <pre><code>a[start:stop:step] # start through not past stop, by step </code></pre> <p>The key point to remember is that the <code>:stop</code> value represents the first value that is <em>not</em> in the selected slice. So, the difference between <code>stop</code> and <code>start</code> is the number of elements selected (if <code>step</code> is 1, the default).</p> <p>The other feature is that <code>start</code> or <code>stop</code> may be a <em>negative</em> number, which means it counts from the end of the array instead of the beginning. So:</p> <pre><code>a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items </code></pre> <p>Similarly, <code>step</code> may be a negative number:</p> <pre><code>a[::-1] # all items in the array, reversed a[1::-1] # the first two items, reversed a[:-3:-1] # the last two items, reversed a[-3::-1] # everything except the last two items, reversed </code></pre> <p>Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for <code>a[:-2]</code> and <code>a</code> only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.</p> <h3>Relationship with the <code>slice</code> object</h3> <p>A <a href=""https://docs.python.org/3/library/functions.html#slice"" rel=""noreferrer""><code>slice</code> object</a> can represent a slicing operation, i.e.:</p> <pre><code>a[start:stop:step] </code></pre> <p>is equivalent to:</p> <pre><code>a[slice(start, stop, step)] </code></pre> <p>Slice objects also behave slightly differently depending on the number of arguments, similar to <code>range()</code>, i.e. both <code>slice(stop)</code> and <code>slice(start, stop[, step])</code> are supported. To skip specifying a given argument, one might use <code>None</code>, so that e.g. <code>a[start:]</code> is equivalent to <code>a[slice(start, None)]</code> or <code>a[::-1]</code> is equivalent to <code>a[slice(None, None, -1)]</code>.</p> <p>While the <code>:</code>-based notation is very helpful for simple slicing, the explicit use of <code>slice()</code> objects simplifies the programmatic generation of slicing.</p>"
|
13 |
+
https://stackoverflow.com/questions/176918/how-to-find-the-index-for-a-given-item-in-a-list,"<p>Given a list <code>["foo", "bar", "baz"]</code> and an item in the list <code>"bar"</code>, how do I get its index <code>1</code>?</p>","<pre class=""lang-py prettyprint-override""><code>>>> ["foo", "bar", "baz"].index("bar") 1 </code></pre> <p>See <a href=""https://docs.python.org/tutorial/datastructures.html#more-on-lists"" rel=""noreferrer"">the documentation</a> for the built-in <code>.index()</code> method of the list:</p> <blockquote> <pre><code>list.index(x[, start[, end]]) </code></pre> <p>Return zero-based index in the list of the first item whose value is equal to <em>x</em>. Raises a <a href=""https://docs.python.org/library/exceptions.html#ValueError"" rel=""noreferrer""><code>ValueError</code></a> if there is no such item.</p> <p>The optional arguments <em>start</em> and <em>end</em> are interpreted as in the <a href=""https://docs.python.org/tutorial/introduction.html#lists"" rel=""noreferrer"">slice notation</a> and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.</p> </blockquote> <h2>Caveats</h2> <h3>Linear time-complexity in list length</h3> <p>An <code>index</code> call checks every element of the list in order, until it finds a match. If the list is long, and if there is no guarantee that the value will be near the beginning, this can slow down the code.</p> <p>This problem can only be completely avoided by using a different data structure. However, if the element is known to be within a certain part of the list, the <code>start</code> and <code>end</code> parameters can be used to narrow the search.</p> <p>For example:</p> <pre><code>>>> import timeit >>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000) 9.356267921015387 >>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000) 0.0004404920036904514 </code></pre> <p>The second call is orders of magnitude faster, because it only has to search through 10 elements, rather than all 1 million.</p> <h3>Only the index of the <em>first match</em> is returned</h3> <p>A call to <code>index</code> searches through the list in order until it finds a match, and <em>stops there.</em> If there could be more than one occurrence of the value, and all indices are needed, <code>index</code> cannot solve the problem:</p> <pre><code>>>> [1, 1].index(1) # the `1` index is not found. 0 </code></pre> <p>Instead, use a <a href=""/questions/34835951/"">list comprehension or generator expression to do the search</a>, with <a href=""/questions/522563/""><code>enumerate</code> to get indices</a>:</p> <pre><code>>>> # A list comprehension gives a list of indices directly: >>> [i for i, e in enumerate([1, 2, 1]) if e == 1] [0, 2] >>> # A generator comprehension gives us an iterable object... >>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1) >>> # which can be used in a `for` loop, or manually iterated with `next`: >>> next(g) 0 >>> next(g) 2 </code></pre> <p>The list comprehension and generator expression techniques still work if there is only one match, and are more generalizable.</p> <h3>Raises an exception if there is no match</h3> <p>As noted in the documentation above, using <code>.index</code> will raise an exception if the searched-for value is not in the list:</p> <pre><code>>>> [1, 1].index(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: 2 is not in list </code></pre> <p>If this is a concern, either <a href=""https://stackoverflow.com/questions/12934190"">explicitly check first</a> using <code>item in my_list</code>, or handle the exception with <code>try</code>/<code>except</code> as appropriate.</p> <p>The explicit check is simple and readable, but it must iterate the list a second time. See <a href=""https://stackoverflow.com/questions/11360858"">What is the EAFP principle in Python?</a> for more guidance on this choice.</p>"
|
14 |
+
https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops,"<pre class=""lang-py prettyprint-override""><code>d = {'x': 1, 'y': 2, 'z': 3} for key in d: print(key, 'corresponds to', d[key]) </code></pre> <p>How does Python recognize that it needs only to read the <code>key</code> from the dictionary? Is <code>key</code> a special keyword, or is it simply a variable?</p>","<p><code>key</code> is just a variable name. </p> <pre><code>for key in d: </code></pre> <p>will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:</p> <p>For Python 3.x:</p> <pre><code>for key, value in d.items(): </code></pre> <p>For Python 2.x:</p> <pre><code>for key, value in d.iteritems(): </code></pre> <p>To test for yourself, change the word <code>key</code> to <code>poop</code>.</p> <p>In Python 3.x, <code>iteritems()</code> was replaced with simply <code>items()</code>, which returns a set-like view backed by the dict, like <code>iteritems()</code> but even better. This is also available in 2.7 as <code>viewitems()</code>. </p> <p>The operation <code>items()</code> will work for both 2 and 3, but in 2 it will return a list of the dictionary's <code>(key, value)</code> pairs, which will not reflect changes to the dict that happen after the <code>items()</code> call. If you want the 2.x behavior in 3.x, you can call <code>list(d.items())</code>.</p>"
|
15 |
+
https://stackoverflow.com/questions/16476924/how-can-i-iterate-over-rows-in-a-pandas-dataframe,"<p>I have a pandas dataframe, <code>df</code>:</p> <pre class=""lang-none prettyprint-override""><code> c1 c2 0 10 100 1 11 110 2 12 120 </code></pre> <p>How do I iterate over the rows of this dataframe? For every row, I want to access its elements (values in cells) by the name of the columns. For example:</p> <pre class=""lang-py prettyprint-override""><code>for row in df.rows: print(row['c1'], row['c2']) </code></pre> <hr /> <p>I found a <a href=""https://stackoverflow.com/questions/7837722/what-is-the-most-efficient-way-to-loop-through-dataframes-with-pandas"">similar question</a>, which suggests using either of these:</p> <ul> <li> <pre class=""lang-py prettyprint-override""><code>for date, row in df.T.iteritems(): </code></pre> </li> <li> <pre class=""lang-py prettyprint-override""><code>for row in df.iterrows(): </code></pre> </li> </ul> <p>But I do not understand what the <code>row</code> object is and how I can work with it.</p>","<p><a href=""https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html#pandas-dataframe-iterrows"" rel=""noreferrer""><code>DataFrame.iterrows</code></a> is a generator which yields both the index and row (as a Series):</p> <pre><code>import pandas as pd df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]}) df = df.reset_index() # make sure indexes pair with number of rows for index, row in df.iterrows(): print(row['c1'], row['c2']) </code></pre> <pre><code>10 100 11 110 12 120 </code></pre> <hr /> <p>Obligatory disclaimer from the <a href=""https://pandas.pydata.org/docs/user_guide/basics.html#iteration"" rel=""noreferrer"">documentation</a></p> <blockquote> <p>Iterating through pandas objects is generally <strong>slow</strong>. In many cases, iterating manually over the rows is not needed and can be avoided with one of the following approaches:</p> <ul> <li>Look for a <em>vectorized</em> solution: many operations can be performed using built-in methods or NumPy functions, (boolean) indexing, …</li> <li>When you have a function that cannot work on the full DataFrame/Series at once, it is better to use <a href=""https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html#pandas.DataFrame.apply"" rel=""noreferrer"" title=""pandas.DataFrame.apply""><code>apply()</code></a> instead of iterating over the values. See the docs on <a href=""https://pandas.pydata.org/docs/user_guide/basics.html#basics-apply"" rel=""noreferrer"">function application</a>.</li> <li>If you need to do iterative manipulations on the values but performance is important, consider writing the inner loop with cython or numba. See the <a href=""https://pandas.pydata.org/docs/user_guide/enhancingperf.html#enhancingperf"" rel=""noreferrer"">enhancing performance</a> section for some examples of this approach.</li> </ul> </blockquote> <p>Other answers in this thread delve into greater depth on alternatives to iter* functions if you are interested to learn more.</p>"
|
16 |
+
https://stackoverflow.com/questions/423379/how-to-use-a-global-variable-in-a-function,"<p>How do I create or use a global variable inside a function?</p> <p>How do I use a global variable that was defined in one function inside other functions?</p> <hr /> <p><sub>Failing to use the <code>global</code> keyword where appropriate often causes <code>UnboundLocalError</code>. The precise rules for this are explained at <a href=""https://stackoverflow.com/questions/370357"">UnboundLocalError on local variable when reassigned after first use</a>. Generally, please close other questions as a duplicate of <em>that</em> question when an explanation is sought, and <em>this</em> question when someone simply needs to know the <code>global</code> keyword.</sub></p>","<p>You can use a global variable within other functions by declaring it as <code>global</code> <strong>within each function that assigns a value to it</strong>:</p> <pre><code>globvar = 0 def set_globvar_to_one(): global globvar # Needed to modify global copy of globvar globvar = 1 def print_globvar(): print(globvar) # No need for global declaration to read value of globvar set_globvar_to_one() print_globvar() # Prints 1 </code></pre> <p>Since it's unclear whether <code>globvar = 1</code> is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the <code>global</code> keyword.</p> <p>See other answers if you want to share a global variable across modules.</p>"
|
17 |
+
https://stackoverflow.com/questions/415511/how-do-i-get-the-current-time-in-python,<p>How do I get the current time in Python?</p>,"<p>Use <a href=""https://docs.python.org/3/library/datetime.html"" rel=""noreferrer""><code>datetime</code></a>:</p> <pre><code>>>> import datetime >>> now = datetime.datetime.now() >>> now datetime.datetime(2009, 1, 6, 15, 8, 24, 78915) >>> print(now) 2009-01-06 15:08:24.789150 </code></pre> <p>For just the clock time without the date:</p> <pre><code>>>> now.time() datetime.time(15, 8, 24, 78915) >>> print(now.time()) 15:08:24.789150 </code></pre> <hr /> <p>To save typing, you can import the <code>datetime</code> object from the <a href=""https://docs.python.org/3/library/datetime.html"" rel=""noreferrer""><code>datetime</code></a> module:</p> <pre><code>>>> from datetime import datetime </code></pre> <p>Then remove the prefix <code>datetime.</code> from all of the above.</p>"
|
18 |
+
https://stackoverflow.com/questions/6470428/how-to-catch-multiple-exceptions-in-one-line-in-the-except-block,"<p>I know that I can do:</p> <pre><code>try: # do something that may fail except: # do this if ANYTHING goes wrong </code></pre> <p>I can also do this:</p> <pre><code>try: # do something that may fail except IDontLikeYouException: # say please except YouAreTooShortException: # stand on a ladder </code></pre> <p>But if I want to do the same thing inside two different exceptions, the best I can think of right now is to do this:</p> <pre><code>try: # do something that may fail except IDontLikeYouException: # say please except YouAreBeingMeanException: # say please </code></pre> <p>Is there any way that I can do something like this (since the action to take in both exceptions is to <code>say please</code>):</p> <pre><code>try: # do something that may fail except IDontLikeYouException, YouAreBeingMeanException: # say please </code></pre> <p>Now this really won't work, as it matches the syntax for:</p> <pre><code>try: # do something that may fail except Exception, e: # say please </code></pre> <p>So, my effort to catch the two distinct exceptions doesn't exactly come through.</p> <p>Is there a way to do this?</p>","<p>From <a href=""https://docs.python.org/3/tutorial/errors.html#handling-exceptions"" rel=""noreferrer"">Python Documentation</a>:</p> <blockquote> <p>An except clause may name multiple exceptions as a parenthesized tuple, for example</p> </blockquote> <pre><code>except (IDontLikeYouException, YouAreBeingMeanException) as e: pass </code></pre> <p>Or, for Python 2 only:</p> <pre><code>except (IDontLikeYouException, YouAreBeingMeanException), e: pass </code></pre> <p>Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using <code>as</code>.</p>"
|
19 |
+
https://stackoverflow.com/questions/123198/how-to-copy-files,<p>How do I copy a file in Python?</p>,"<p><a href=""http://docs.python.org/3/library/shutil.html"" rel=""noreferrer""><code>shutil</code></a> has many methods you can use. One of which is:</p> <pre><code>import shutil shutil.copyfile(src, dst) # 2nd option shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp </code></pre> <ul> <li>Copy the contents of the file named <code>src</code> to a file named <code>dst</code>. Both <code>src</code> and <code>dst</code> need to be the entire filename of the files, including path.</li> <li>The destination location must be writable; otherwise, an <code>IOError</code> exception will be raised.</li> <li>If <code>dst</code> already exists, it will be replaced.</li> <li>Special files such as character or block devices and pipes cannot be copied with this function.</li> <li>With <code>copy</code>, <code>src</code> and <code>dst</code> are path names given as <code>str</code>s.</li> </ul> <p>Another <code>shutil</code> method to look at is <a href=""https://docs.python.org/3/library/shutil.html#shutil.copy2"" rel=""noreferrer""><code>shutil.copy2()</code></a>. It's similar but preserves more metadata (e.g. time stamps).</p> <p>If you use <code>os.path</code> operations, use <code>copy</code> rather than <code>copyfile</code>. <code>copyfile</code> will only accept strings.</p>"
|
20 |
+
https://stackoverflow.com/questions/448271/what-is-init-py-for,"<p>What is <a href=""https://docs.python.org/3/tutorial/modules.html#packages"" rel=""noreferrer""><code>__init__.py</code></a> for in a Python source directory?</p>","<p>It used to be a required part of a package (<a href=""https://docs.python.org/3/reference/import.html#regular-packages"" rel=""noreferrer"">old, pre-3.3 ""regular package""</a>, not <a href=""https://docs.python.org/3/reference/import.html#namespace-packages"" rel=""noreferrer"">newer 3.3+ ""namespace package""</a>).</p> <p><a href=""https://docs.python.org/3/reference/import.html#regular-packages"" rel=""noreferrer"">Here's the documentation.</a></p> <blockquote> <p>Python defines two types of packages, regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an <code>__init__.py</code> file. When a regular package is imported, this <code>__init__.py</code> file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The <code>__init__.py</code> file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.</p> </blockquote> <p>But just click the link, it contains an example, more information, and an explanation of namespace packages, the kind of packages without <code>__init__.py</code>.</p>"
|
21 |
+
https://stackoverflow.com/questions/606191/convert-bytes-to-a-string-in-python-3,"<p>I captured the standard output of an external program into a <code>bytes</code> object:</p> <pre><code>>>> from subprocess import * >>> stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] >>> stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>I want to convert that to a normal Python string, so that I can print it like this:</p> <pre><code>>>> print(stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 </code></pre> <p>How do I convert the <code>bytes</code> object to a <code>str</code> with Python 3?</p> <hr /> <p><sub>See <a href=""https://stackoverflow.com/questions/7585435"">Best way to convert string to bytes in Python 3?</a> for the other way around.</sub></p>","<p><a href=""https://docs.python.org/3/library/stdtypes.html#bytes.decode"" rel=""noreferrer"">Decode the <code>bytes</code> object</a> to produce a string:</p> <pre><code>>>> b"abcde".decode("utf-8") 'abcde' </code></pre> <p>The above example <em>assumes</em> that the <code>bytes</code> object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in!</p>"
|