text
stringlengths
185
26.5k
<s>[INST] Python reverse / invert a mapping Given a dictionary like so: my_map = { 'a': 1, 'b':2 } How can one invert this map to get: inv_map = { 1: 'a', 2: 'b' } EDITOR NOTE: map changed to my_map to avoid conflicts with the built-in function, map. Some comments may be affected below. [/INST] For Python 2.7.x inv_map = {v: k for k, v in my_map.iteritems()} For Python 3+: inv_map = {v: k for k, v in my_map.items()} </s>
<s>[INST] Command Line Arguments In Python I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? Related What’s the best way to grab/parse command line arguments passed to a Python script? Implementing a “[command] [action] [parameter]” style command-line interfaces? How can I process command line arguments in Python? How do I format positional argument help using Python’s optparse? [/INST] import sys print "\n".join(sys.argv) sys.argv is a list that contains all the arguments passed to the script on the command line. Basically, import sys print sys.argv[1:] </s>
<s>[INST] How to capitalize the first letter of each word in a string (Python)? s = 'the brown fox' ...do something here... s should be : 'The Brown Fox' What's the easiest way to do this? [/INST] The .title() method of a string (either ASCII or Unicode is fine) does this: >>> "hello world".title() 'Hello World' >>> u"hello world".title() u'Hello World' However, look out for strings with embedded apostrophes, as noted in the docs. The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result: >>> "they're bill's friends from the UK".title() "They'Re Bill'S Friends From The Uk" </s>
<s>[INST] What is the quickest way to HTTP GET in Python? What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like: contents = url.get("http://example.com/foo/bar") But all I can find using Google are httplib and urllib - and I am unable to find a shortcut in those libraries. Does standard Python 2.5 have a shortcut in some form as above, or should I write a function url_get? I would prefer not to capture the output of shelling out to wget or curl. [/INST] Python 2.x: import urllib2 urllib2.urlopen("http://example.com/foo/bar").read() Python 3.x: import urllib.request urllib.request.urlopen("http://example.com/foo/bar").read() Documentation for urllib.request and read. How is that? </s>
<s>[INST] How to check if type of a variable is string? Is there a way to check if the type of a variable in python is string.. like isinstance(x,int); for integer values? [/INST] In Python 2.x, you would do isinstance(s, basestring) basestring is the abstract superclass of str and unicode. It can be used to test whether an object is an instance of str or unicode. Equivalent code: isinstance(s, (str, unicode)) In Python 3.x, it would be isinstance(s, str) (basestring is not defined in Python 3.) </s>
<s>[INST] Why are there no ++ and --​ operators in Python? Why are there no ++ and -- operators in Python? [/INST] It's not because it doesn't make sense; it makes perfect sense to define "x++" as "x += 1, evaluating to the previous binding of x". If you want to know the original reason, you'll have to either wade through old Python mailing lists or ask somebody who was there (eg. Guido), but it's easy enough to justify after the fact: Simple increment and decrement aren't needed as much as in other languages. You don't write things like for(int i = 0; i < 10; ++i) in Python very often; instead you do things like for i in range(0, 10). Since it's not needed nearly as often, there's much less reason to give it its own special syntax; when you do need to increment, += is usually just fine. It's not a decision of whether it makes sense, or whether it can be done--it does, and it can. It's a question of whether the benefit is worth adding to the core syntax of the language. Remember, this is four operators--postinc, postdec, preinc, predec, and each of these would need to have its own class overloads; they all need to be specified, and tested; it would add opcodes to the language (implying a larger, and therefore slower, VM engine); every class that supports a logical increment would need to implement them (on top of += and -=). This is all redundant with += and -=, so it would become a net loss. </s>
<s>[INST] What does functools.wraps do? In a comment on the answer to another question, someone said they weren't sure what functools.wraps was doing. So I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly? [/INST] When you use a decorator, you're replacing one function with another. In other words, if you have a decorator def logged(func): def with_logging(*args, **kwargs): print func.__name__ + " was called" return func(*args, **kwargs) return with_logging then when you say @logged def f(x): """does some math""" return x + x * x it's exactly the same as saying def f(x): """does some math""" return x + x * x f = logged(f) and your function f is replaced with the function with_logging. Unfortunately, this means that if you then say print f.__name__ it will print with_logging because that's the name of your new function. In fact, if you look at the docstring for f, it will be blank because with_logging has no docstring, and so the docstring you wrote won't be there anymore. Also, if you look at the pydoc result for that function, it won't be listed as taking one argument x; instead it'll be listed as taking *args and **kwargs because that's what with_logging takes. If using a decorator always meant losing this information about a function, it would be a serious problem. That's why we have functools.wraps. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since wraps is itself a decorator, the following code does the correct thing: from functools import wraps def logged(func): @wraps(func) def with_logging(*args, **kwargs): print func.__name__ + " was called" return func(*args, **kwargs) return with_logging @logged def f(x): """does some math""" return x + x * x print f.__name__ # prints 'f' print f.__doc__ # prints 'does some math' </s>
<s>[INST] Should I put #! (shebang) in Python scripts, and what form should it take? Should I put the shebang in my Python scripts? In what form? #!/usr/bin/env python or #!/usr/local/bin/python Are these equally portable? Which form is used most? Note: the tornado project uses the shebang. On the other hand the Django project doesn't. [/INST] The shebang line in any script determines the script's ability to be executed like an standalone executable without typing python beforehand in the terminal or when double clicking it in a file manager(when configured properly). It isn't necessary but generally put there so when someone sees the file opened in an editor, they immediately know what they're looking at. However, which shebang line you use IS important; Correct usage is: #!/usr/bin/env python #!/usr/bin/env python Usually defaults to python 2.7.latest, and the following defaults to 3.latest #!/usr/bin/env python3 DO NOT Use: #!/usr/local/bin/python "python may be installed at /usr/bin/python or /bin/python in those cases, the above #! will fail." --"#!/usr/bin/env python" vs "#!/usr/local/bin/python" </s>
<s>[INST] Why are some float < integer comparisons four times slower than others? When comparing floats to integers, some pairs of values take much longer to be evaluated than other values of a similar magnitude. For example: >>> import timeit >>> timeit.timeit("562949953420000.7 < 562949953421000") # run 1 million times 0.5387085462592742 But if the float or integer is made smaller or larger by a certain amount, the comparison runs much more quickly: >>> timeit.timeit("562949953420000.7 < 562949953422000") # integer increased by 1000 0.1481498428446173 >>> timeit.timeit("562949953423001.8 < 562949953421000") # float increased by 3001.1 0.1459577925548956 Changing the comparison operator (e.g. using == or > instead) does not affect the times in any noticeable way. This is not solely related to magnitude because picking larger or smaller values can result in faster comparisons, so I suspect it is down to some unfortunate way the bits line up. Clearly, comparing these values is more than fast enough for most use cases. I am simply curious as to why Python seems to struggle more with some pairs of values than with others. [/INST] A comment in the Python source code for float objects acknowledges that: Comparison is pretty much a nightmare This is especially true when comparing a float to an integer, because, unlike floats, integers in Python can be arbitrarily large and are always exact. Trying to cast the integer to a float might lose precision and make the comparison inaccurate. Trying to cast the float to an integer is not going to work either because any fractional part will be lost. To get around this problem, Python performs a series of checks, returning the result if one of the checks succeeds. It compares the signs of the two values, then whether the integer is "too big" to be a float, then compares the exponent of the float to the length of the integer. If all of these checks fail, it is necessary to construct two new Python objects to compare in order to obtain the result. When comparing a float v to an integer/long w, the worst case is that: v and w have the same sign (both positive or both negative), the integer w has few enough bits that it can be held in the size_t type (typically 32 or 64 bits), the integer w has at least 49 bits, the exponent of the float v is the same as the number of bits in w. And this is exactly what we have for the values in the question: >>> import math >>> math.frexp(562949953420000.7) # gives the float's (significand, exponent) pair (0.9999999999976706, 49) >>> (562949953421000).bit_length() 49 We see that 49 is both the exponent of the float and the number of bits in the integer. Both numbers are positive and so the four criteria above are met. Choosing one of the values to be larger (or smaller) can change the number of bits of the integer, or the value of the exponent, and so Python is able to determine the result of the comparison without performing the expensive final check. This is specific to the CPython implementation of the language. The comparison in more detail The float_richcompare function handles the comparison between two values v and w. Below is a step-by-step description of the checks that the function performs. The comments in the Python source are actually very helpful when trying to understand what the function does, so I've left them in where relevant. I've also summarised these checks in a list at the foot of the answer. The main idea is to map the Python objects v and w to two appropriate C doubles, i and j, which can then be easily compared to give the correct result. Both Python 2 and Python 3 use the same ideas to do this (the former just handles int and long types separately). The first thing to do is check that v is definitely a Python float and map it to a C double i. Next the function looks at whether w is also a float and maps it to a C double j. This is the best case scenario for the function as all the other checks can be skipped. The function also checks to see whether v is inf or nan: static PyObject* float_richcompare(PyObject *v, PyObject *w, int op) { double i, j; int r = 0; assert(PyFloat_Check(v)); i = PyFloat_AS_DOUBLE(v); if (PyFloat_Check(w)) j = PyFloat_AS_DOUBLE(w); else if (!Py_IS_FINITE(i)) { if (PyLong_Check(w)) j = 0.0; else goto Unimplemented; } Now we know that if w failed these checks, it is not a Python float. Now the function checks if it's a Python integer. If this is the case, the easiest test is to extract the sign of v and the sign of w (return 0 if zero, -1 if negative, 1 if positive). If the signs are different, this is all the information needed to return the result of the comparison: else if (PyLong_Check(w)) { int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; int wsign = _PyLong_Sign(w); size_t nbits; int exponent; if (vsign != wsign) { /* Magnitudes are irrelevant -- the signs alone * determine the outcome. */ i = (double)vsign; j = (double)wsign; goto Compare; } } If this check failed, then v and w have the same sign. The next check counts the number of bits in the integer w. If it has too many bits then it can't possibly be held as a float and so must be larger in magnitude than the float v: nbits = _PyLong_NumBits(w); if (nbits == (size_t)-1 && PyErr_Occurred()) { /* This long is so large that size_t isn't big enough * to hold the # of bits. Replace with little doubles * that give the same outcome -- w is so large that * its magnitude must exceed the magnitude of any * finite float. */ PyErr_Clear(); i = (double)vsign; assert(wsign != 0); j = wsign * 2.0; goto Compare; } On the other hand, if the integer w has 48 or fewer bits, it can safely turned in a C double j and compared: if (nbits <= 48) { j = PyLong_AsDouble(w); /* It's impossible that <= 48 bits overflowed. */ assert(j != -1.0 || ! PyErr_Occurred()); goto Compare; } From this point onwards, we know that w has 49 or more bits. It will be convenient to treat w as a positive integer, so change the sign and the comparison operator as necessary: if (nbits <= 48) { /* "Multiply both sides" by -1; this also swaps the * comparator. */ i = -i; op = _Py_SwappedOp[op]; } Now the function looks at the exponent of the float. Recall that a float can be written (ignoring sign) as significand * 2exponent and that the significand represents a number between 0.5 and 1: (void) frexp(i, &exponent); if (exponent < 0 || (size_t)exponent < nbits) { i = 1.0; j = 2.0; goto Compare; } This checks two things. If the exponent is less than 0 then the float is smaller than 1 (and so smaller in magnitude than any integer). Or, if the exponent is less than the number of bits in w then we have that v < |w| since significand * 2exponent is less than 2nbits. Failing these two checks, the function looks to see whether the exponent is greater than the number of bit in w. This shows that significand * 2exponent is greater than 2nbits and so v > |w|: if ((size_t)exponent > nbits) { i = 2.0; j = 1.0; goto Compare; } If this check did not succeed we know that the exponent of the float v is the same as the number of bits in the integer w. The only way that the two values can be compared now is to construct two new Python integers from v and w. The idea is to discard the fractional part of v, double the integer part, and then add one. w is also doubled and these two new Python objects can be compared to give the correct return value. Using an example with small values, 4.65 < 4 would be determined by the comparison (2*4)+1 == 9 < 8 == (2*4) (returning false). { double fracpart; double intpart; PyObject *result = NULL; PyObject *one = NULL; PyObject *vv = NULL; PyObject *ww = w; // snip fracpart = modf(i, &intpart); // split i (the double that v mapped to) vv = PyLong_FromDouble(intpart); // snip if (fracpart != 0.0) { /* Shift left, and or a 1 bit into vv * to represent the lost fraction. */ PyObject *temp; one = PyLong_FromLong(1); temp = PyNumber_Lshift(ww, one); // left-shift doubles an integer ww = temp; temp = PyNumber_Lshift(vv, one); vv = temp; temp = PyNumber_Or(vv, one); // a doubled integer is even, so this adds 1 vv = temp; } // snip } } For brevity I've left out the additional error-checking and garbage-tracking Python has to do when it creates these new objects. Needless to say, this adds additional overhead and explains why the values highlighted in the question are significantly slower to compare than others. Here is a summary of the checks that are performed by the comparison function. Let v be a float and cast it as a C double. Now, if w is also a float: Check whether w is nan or inf. If so, handle this special case separately depending on the type of w. If not, compare v and w directly by their representations as C doubles. If w is an integer: Extract the signs of v and w. If they are different then we know v and w are different and which is the greater value. (The signs are the same.) Check whether w has too many bits to be a float (more than size_t). If so, w has greater magnitude than v. Check if w has 48 or fewer bits. If so, it can be safely cast to a C double without losing its precision and compared with v. (w has more than 48 bits. We will now treat w as a positive integer having changed the compare op as appropriate.) Consider the exponent of the float v. If the exponent is negative, then v is less than 1 and therefore less than any positive integer. Else, if the exponent is less than the number of bits in w then it must be less than w. If the exponent of v is greater than the number of bits in w then v is greater than w. (The exponent is the same as the number of bits in w.) The final check. Split v into its integer and fractional parts. Double the integer part and add 1 to compensate for the fractional part. Now double the integer w. Compare these two new integers instead to get the result. </s>
<s>[INST] "is" operator behaves unexpectedly with integers Why does the following behave unexpectedly in Python? >>> a = 256 >>> b = 256 >>> a is b True # This is an expected result >>> a = 257 >>> b = 257 >>> a is b False # What happened here? Why is this False? >>> 257 is 257 True # Yet the literal numbers compare properly I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100. Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the is operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not? [/INST] Take a look at this: >>> a = 256 >>> b = 256 >>> id(a) 9987148 >>> id(b) 9987148 >>> a = 257 >>> b = 257 >>> id(a) 11662816 >>> id(b) 11662828 EDIT: Here's what I found in the Python 2 documentation, "Plain Integer Objects" (It's the same for Python 3): The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-) </s>
<s>[INST] What does Ruby have that Python doesn't, and vice versa? There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody choosing, as they might not have the same tastes in development as I do. It would therefore be interesting to list the differences, objectively. So no "Python's lambdas sucks". Instead explain what Ruby's lambdas can do that Python's can't. No subjectivity. Example code is good! Don't have several differences in one answer, please. And vote up the ones you know are correct, and down those you know are incorrect (or are subjective). Also, differences in syntax is not interesting. We know Python does with indentation what Ruby does with brackets and ends, and that @ is called self in Python. UPDATE: This is now a community wiki, so we can add the big differences here. Ruby has a class reference in the class body In Ruby you have a reference to the class (self) already in the class body. In Python you don't have a reference to the class until after the class construction is finished. An example: class Kaka puts self end self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python (outside method definitions). All classes are mutable in Ruby This lets you develop extensions to core classes. Here's an example of a rails extension: class String def starts_with?(other) head = self[0, other.length] head == other end end Python (imagine there were no ''.startswith method): def starts_with(s, prefix): return s[:len(prefix)] == prefix You could use it on any sequence (not just strings). In order to use it you should import it explicitly e.g., from some_module import starts_with. Ruby has Perl-like scripting features Ruby has first class regexps, $-variables, the awk/perl line by line input loop and other features that make it more suited to writing small shell scripts that munge text files or act as glue code for other programs. Ruby has first class continuations Thanks to the callcc statement. In Python you can create continuations by various techniques, but there is no support built in to the language. Ruby has blocks With the "do" statement you can create a multi-line anonymous function in Ruby, which will be passed in as an argument into the method in front of do, and called from there. In Python you would instead do this either by passing a method or with generators. Ruby: amethod { |here| many=lines+of+code goes(here) } Python (Ruby blocks correspond to different constructs in Python): with amethod() as here: # `amethod() is a context manager many=lines+of+code goes(here) Or for here in amethod(): # `amethod()` is an iterable many=lines+of+code goes(here) Or def function(here): many=lines+of+code goes(here) amethod(function) # `function` is a callback Interestingly, the convenience statement in Ruby for calling a block is called "yield", which in Python will create a generator. Ruby: def themethod yield 5 end themethod do |foo| puts foo end Python: def themethod(): yield 5 for foo in themethod(): print foo Although the principles are different, the result is strikingly similar. Ruby supports functional style (pipe-like) programming more easily myList.map(&:description).reject(&:empty?).join("\n") Python: descriptions = (f.description() for f in mylist) "\n".join(filter(len, descriptions)) Python has built-in generators (which are used like Ruby blocks, as noted above) Python has support for generators in the language. In Ruby 1.8 you can use the generator module which uses continuations to create a generator from a block. Or, you could just use a block/proc/lambda! Moreover, in Ruby 1.9 Fibers are, and can be used as, generators, and the Enumerator class is a built-in generator 4 docs.python.org has this generator example: def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] Contrast this with the above block examples. Python has flexible name space handling In Ruby, when you import a file with require, all the things defined in that file will end up in your global namespace. This causes namespace pollution. The solution to that is Rubys modules. But if you create a namespace with a module, then you have to use that namespace to access the contained classes. In Python, the file is a module, and you can import its contained names with from themodule import *, thereby polluting the namespace if you want. But you can also import just selected names with from themodule import aname, another or you can simply import themodule and then access the names with themodule.aname. If you want more levels in your namespace you can have packages, which are directories with modules and an __init__.py file. Python has docstrings Docstrings are strings that are attached to modules, functions and methods and can be introspected at runtime. This helps for creating such things as the help command and automatic documentation. def frobnicate(bar): """frobnicate takes a bar and frobnicates it >>> bar = Bar() >>> bar.is_frobnicated() False >>> frobnicate(bar) >>> bar.is_frobnicated() True """ Ruby's equivalent are similar to javadocs, and located above the method instead of within it. They can be retrieved at runtime from the files by using 1.9's Method#source_location example use Python has multiple inheritance Ruby does not ("on purpose" -- see Ruby's website, see here how it's done in Ruby). It does reuse the module concept as a type of abstract classes. Python has list/dict comprehensions Python: res = [x*x for x in range(1, 10)] Ruby: res = (0..9).map { |x| x * x } Python: >>> (x*x for x in range(10)) <generator object <genexpr> at 0xb7c1ccd4> >>> list(_) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Ruby: p = proc { |x| x * x } (0..9).map(&p) Python 2.7+: >>> {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} Ruby: >> Hash[{1=>2, 3=>4}.map{|x,y| [x,(y*y).to_s]}] => {1=>"4", 3=>"16"} Python has decorators Things similar to decorators can also be created in Ruby, and it can also be argued that they aren't as necessary as in Python. Syntax differences Ruby requires "end" or "}" to close all of its scopes, while Python uses white-space only. There have been recent attempts in Ruby to allow for whitespace only indentation http://github.com/michaeledgar/seamless [/INST] Ruby has the concepts of blocks, which are essentially syntactic sugar around a section of code; they are a way to create closures and pass them to another method which may or may not use the block. A block can be invoked later on through a yield statement. For example, a simple definition of an each method on Array might be something like: class Array def each for i in self yield(i) # If a block has been passed, control will be passed here. end end end Then you can invoke this like so: # Add five to each element. [1, 2, 3, 4].each{ |e| puts e + 5 } > [6, 7, 8, 9] Python has anonymous functions/closures/lambdas, but it doesn't quite have blocks since it's missing some of the useful syntactic sugar. However, there's at least one way to get it in an ad-hoc fashion. See, for example, here. </s>
<s>[INST] super() raises "TypeError: must be type, not classobj" for new-style class The following use of super() raises a TypeError: why? >>> from HTMLParser import HTMLParser >>> class TextParser(HTMLParser): ... def __init__(self): ... super(TextParser, self).__init__() ... self.all_data = [] ... >>> TextParser() (...) TypeError: must be type, not classobj There is a similar question on StackOverflow: python super() raises TypeError ! Why?, where the error is explained by the fact that the user class is not a new-style class. However, the class above is a new-style class, as it inherits from object: >>> isinstance(HTMLParser(), object) True What am I missing? How can I use super(), here? Using HTMLParser.__init__(self) instead of super(TextParser, self).__init__() would work, but I would like to understand the TypeError. PS: Joachim pointed out that being a new-style-class instance is not equivalent to being an object. I read the opposite many times, hence my confusion (example of new-style class instance test based on object instance test: http://stackoverflow.com/revisions/2655651/3). [/INST] Alright, it's the usual "super() cannot be used with an old-style class". However, the important point is that the correct test for "is this a new-style instance (i.e. object)?" is >>> class OldStyle: pass >>> instance = OldStyle() >>> issubclass(instance.__class__, object) False and not (as in the question): >>> isinstance(instance, object) True For classes, the correct "is this a new-style class" test is: >>> issubclass(OldStyle, object) # OldStyle is not a new-style class False >>> issubclass(int, object) # int is a new-style class True The crucial point is that with old-style classes, the class of an instance and its type are distinct. Here, OldStyle().__class__ is OldStyle, which does not inherit from object, while type(OldStyle()) is the instance type, which does inherit from object. Basically, an old-style class just creates objects of type instance (whereas a new-style class creates objects whose type is the class itself). This is probably why the instance OldStyle() is an object: its type() inherits from object (the fact that its class does not inherit from object does not count: old-style classes merely construct new objects of type instance). Partial reference: http://stackoverflow.com/a/9699961/42973. PS: The difference between a new-style class and an old-style one can also be seen with: >>> type(OldStyle) # OldStyle creates objects but is not itself a type classobj >>> isinstance(OldStyle, type) False >>> type(int) # A new-style class is a type type (old-style classes are not types, so they cannot be the type of their instances). </s>
<s>[INST] Get difference between two lists I have two lists in Python, like these: temp1 = ['One', 'Two', 'Three', 'Four'] temp2 = ['One', 'Two'] I need to create a third list with items from the first list which aren't present in the second one. From the example I have to get: temp3 = ['Three', 'Four'] Are there any fast ways without cycles and checking? [/INST] In [5]: list(set(temp1) - set(temp2)) Out[5]: ['Four', 'Three'] </s>
<s>[INST] How do I get the path and name of the file that is currently executing? I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. For example, let's say I have three files. Using execfile: script_1.py calls script_2.py. In turn, script_2.py calls script_3.py. How can I get the file name and path of script_3.py, from code within script_3.py, without having to pass that information as arguments from script_2.py? (Executing os.getcwd() returns the original starting script's filepath not the current file's.) [/INST] __file__ as others have said. You may want to use: os.path.realpath(__file__) </s>
<s>[INST] Pretty printing XML in Python What is the best way (or even the various ways) to pretty print xml in Python? [/INST] import xml.dom.minidom xml = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string) pretty_xml_as_string = xml.toprettyxml() </s>
<s>[INST] How to move a file in Python I looked into the Python os interface, but was unable to locate a method to move a file. How would I do the equivalent of $ mv ... in Python? >>> source_files = '/PATH/TO/FOLDER/*' >>> destination_folder = 'PATH/TO/FOLDER' >>> # equivalent of $ mv source_files destination_folder [/INST] os.rename() or shutil.move() Both employ the same syntax: os.rename("path/to/current/file.foo", "path/to/new/desination/for/file.foo") shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo") Note that in both cases the directory in which the new file is being created must already exist, (but, on Windows, a file with that name must not or an exception will be raised). Note also, you must include the file name (file.foo) in both the source and destination arguments. If it is changed, the file will be renamed as well as moved. As has been noted in comments on other answers, shutil.move simply calls os.rename in most cases. However, if the destination is on a different disk than the source, it will instead copy and then delete the source file. </s>
<s>[INST] How do I find the location of Python module sources? How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the datetime module in particular, but I'm interested in a more general answer as well. [/INST] For a pure python module you can find the source by looking at themodule.__file__. The datetime module, however, is written in C, and therefore datetime.__file__ points to a .so file (there is no datetime.__file__ on Windows), and therefore, you can't see the source. If you download a python source tarball and extract it, the modules' code can be found in the Modules subdirectory. For example, if you want to find the datetime code for python 2.6, you can look at Python-2.6/Modules/datetimemodule.c You can also find the latest Mercurial version on the web at https://hg.python.org/cpython/file/tip/Modules/_datetimemodule.c </s>
<s>[INST] Measure time elapsed in Python? What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I'm using the timeit module wrong, but the docs are just confusing for me. import timeit start = timeit.timeit() print "hello" end = timeit.timeit() print end - start [/INST] If you just want to measure the elapsed wall-clock time between two points, you could use time.time(): import time start = time.time() print("hello") end = time.time() print(end - start) This gives the execution time in seconds. edit A better option might be to use time.clock (thanks @Amber): On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond. </s>
<s>[INST] clang error: unknown argument: '-mno-fused-madd' (python package installation failure) I get the following error when attempting to install psycopg2 via pip on Mavericks 10.9: clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] Not sure how to proceed and have searched here and elsewhere for this particular error. Any help is much appreciated! Here is the complete output from pip: $ pip install psycopg2 Downloading/unpacking psycopg2 Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded Running setup.py (path:/private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2/setup.py) egg_info for package psycopg2 Installing collected packages: psycopg2 Running setup.py install for psycopg2 building 'psycopg2._psycopg' extension cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.5.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090303 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/local/Cellar/postgresql/9.3.3/include -I/usr/local/Cellar/postgresql/9.3.3/include/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-intel-2.7/psycopg/psycopgmodule.o clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] clang: note: this will be a hard error (cannot be downgraded to a warning) in the future error: command 'cc' failed with exit status 1 Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip-bnWiwB-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.macosx-10.9-intel-2.7 creating build/lib.macosx-10.9-intel-2.7/psycopg2 copying lib/__init__.py -> build/lib.macosx-10.9-intel-2.7/psycopg2 copying lib/_json.py -> build/lib.macosx-10.9-intel-2.7/psycopg2 copying lib/_range.py -> build/lib.macosx-10.9-intel-2.7/psycopg2 copying lib/errorcodes.py -> build/lib.macosx-10.9-intel-2.7/psycopg2 copying lib/extensions.py -> build/lib.macosx-10.9-intel-2.7/psycopg2 copying lib/extras.py -> build/lib.macosx-10.9-intel-2.7/psycopg2 copying lib/pool.py -> build/lib.macosx-10.9-intel-2.7/psycopg2 copying lib/psycopg1.py -> build/lib.macosx-10.9-intel-2.7/psycopg2 copying lib/tz.py -> build/lib.macosx-10.9-intel-2.7/psycopg2 creating build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/__init__.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/dbapi20.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/dbapi20_tpc.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_async.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_bug_gc.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_bugX000.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_cancel.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_connection.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_copy.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_cursor.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_dates.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_extras_dictcursor.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_green.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_lobject.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_module.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_notify.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_psycopg2_dbapi20.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_quote.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_transaction.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_types_basic.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_types_extras.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/test_with.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/testconfig.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests copying tests/testutils.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests running build_ext building 'psycopg2._psycopg' extension creating build/temp.macosx-10.9-intel-2.7 creating build/temp.macosx-10.9-intel-2.7/psycopg cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.5.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090303 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/local/Cellar/postgresql/9.3.3/include -I/usr/local/Cellar/postgresql/9.3.3/include/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-intel-2.7/psycopg/psycopgmodule.o clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] clang: note: this will be a hard error (cannot be downgraded to a warning) in the future error: command 'cc' failed with exit status 1 ---------------------------------------- Cleaning up... Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip-bnWiwB-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2 [/INST] You can tell clang to not raise this as an error by setting the following environment variables prior compilation: export CFLAGS=-Qunused-arguments export CPPFLAGS=-Qunused-arguments Then pip install psycopg2should work. I had the same when trying to pip install lxml. Edit: if you are installing as superuser (which will likely be the case if you are trying to append to /Library/Python/2.7/site-packages, the native Apple factory-installed Python distribution which ships with OS X, rather than to some other Python distribution which you have subsequently installed yourself), then you will need to do, as described by @Thijs Kuipers in comments below: sudo -E pip install psycopg2 or the equivalent, for whatever other package name you may be substituting in place of psycopg2. UPDATE [2014-05-16]: Apple has fixed this problem with updated system Pythons (2.7, 2.6, and 2.5) in OS X 10.9.3 so the workaround is no longer necessary when using the latest Mavericks and Xcode 5.1+. However, as of now, the workaround is still required for OS X 10.8.x (Mountain Lion, currently 10.8.5) if you are using Xcode 5.1+ there. </s>
<s>[INST] Dead simple argparse example wanted: 1 argument, 3 results The documentation for the argparse python module, while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. Likewise for many questions here on the stack. I don't need to do math on the command line or meddle with formatting lines on the screen or change option characters. All I want to do is "if arg is A, do this, if B do that, if none of the above show help and quit". [/INST] Here's the way I do it with argparse (with multiple args): parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('-f','--foo', help='Description for foo argument', required=True) parser.add_argument('-b','--bar', help='Description for bar argument', required=True) args = vars(parser.parse_args()) args will be a dictionary containing the arguments: if args['foo'] == 'Hello': # code here if args['bar'] == 'World': # code here In your case simply add only one argument. </s>
<s>[INST] Python Image Library fails with message "decoder JPEG not available" - PIL PIL does support JPEG in my system. Whenever I do an upload, my code is failing with: File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available How can I resolve this? [/INST] libjpeg-dev is required to be able to process jpegs with pillow (or PIL), so you need to install it and then recompile pillow. It also seems that libjpeg8-dev is needed on Ubuntu 14.04 If you're still using PIL then you should really be using pillow these days though, so first pip uninstall PIL before following these instructions to switch, or if you have a good reason for sticking with PIL then replace "pillow" with "PIL" in the below). On Ubuntu: # install libjpeg-dev with apt sudo apt-get install libjpeg-dev # if you're on Ubuntu 14.04, also install this sudo apt-get install libjpeg8-dev # reinstall pillow pip install --no-cache-dir -I pillow If that doesn't work, try one of the below, depending on whether you are on 64bit or 32bit Ubuntu. For Ubuntu x64: sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib Or for Ubuntu 32bit: sudo ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib/ sudo ln -s /usr/lib/i386-linux-gnu/libfreetype.so.6 /usr/lib/ sudo ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib/ Then reinstall pillow: pip install --no-cache-dir -I pillow (Edits to include feedback from comments. Thanks Charles Offenbacher for pointing out this differs for 32bit, and t-mart for suggesting use of --no-cache-dir). </s>
<s>[INST] Convert a Unicode string to a string in Python (containing extra symbols) How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string? [/INST] title = u"Klüft skräms inför på fédéral électoral große" import unicodedata unicodedata.normalize('NFKD', title).encode('ascii','ignore') 'Kluft skrams infor pa federal electoral groe' </s>
<s>[INST] Converting from a string to boolean in Python? Does anyone know how to do convert from a string to a boolean in Python? I found this link. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc. EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True. [/INST] Really, you just compare the string to whatever you expect to accept as representing true, so you can do this: s == 'True' Or to checks against a whole bunch of values: s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'] Be cautious when using the following: >>> bool("foo") True >>> bool("") False Empty strings evaluate to False, but everything else evaluates to True. So this should not be used for any kind of parsing purposes. </s>
<s>[INST] Python: check if an object is a list or tuple (but not string) This is what I normally do in order to ascertain that the input is a list/tuple - but not a str. Because many times I stumbled upon bugs where a function passes a str object by mistake, and the target function does for x in lst assuming that lst is actually a list or tuple. assert isinstance(lst, (list, tuple)) My question is: is there a better way of achieving this? [/INST] I think assert not isinstance(lst, basestring) Is actually what you want, otherwise you'll miss out on a lot of things which act like lists, but aren't subclasses of list or tuple. </s>
<s>[INST] How do I use Python's itertools.groupby()? I haven't been able to find an understandable explanation of how to actually use Python's itertools.groupby() function. What I'm trying to do is this: Take a list - in this case, the children of an objectified lxml element Divide it into groups based on some criteria Then later iterate over each of these groups separately. I've reviewed the documentation, and the examples, but I've had trouble trying to apply them beyond a simple list of numbers. So, how do I use of itertools.groupby()? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated. [/INST] As Sebastjan said, you first have to sort your data. This is important. The part I didn't get is that in the example construction groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) k is the current grouping key, and g is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the groupby iterator itself returns iterators. Here's an example of that, using clearer variable names: from itertools import groupby things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")] for key, group in groupby(things, lambda x: x[0]): for thing in group: print "A %s is a %s." % (thing[1], key) print " " This will give you the output: A bear is a animal. A duck is a animal. A cactus is a plant. A speed boat is a vehicle. A school bus is a vehicle. In this example, things is a list of tuples where the first item in each tuple is the group the second item belongs to. The groupby() function takes two arguments: (1) the data to group and (2) the function to group it with. Here, lambda x: x[0] tells groupby() to use the first item in each tuple as the grouping key. In the above for statement, groupby returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group. Here's a slightly different example with the same data, using a list comprehension: for key, group in groupby(things, lambda x: x[0]): listOfThings = " and ".join([thing[1] for thing in group]) print key + "s: " + listOfThings + "." This will give you the output: animals: bear and duck. plants: cactus. vehicles: speed boat and school bus. </s>
<s>[INST] Flatten (an irregular) list of lists in Python Yes, I know this subject has been covered before (here, here, here, here), but as far as I know, all solutions, except for one, fail on a list like this: L = [[[1, 2, 3], [4, 5]], 6] Where the desired output is [1, 2, 3, 4, 5, 6] Or perhaps even better, an iterator. The only solution I saw that works for an arbitrary nesting is found in this question: def flatten(x): result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result flatten(L) Is this the best model? Did I overlook something? Any problems? [/INST] Using generator functions can make your example a little easier to read and probably boost the performance. Python 2 def flatten(l): for el in l: if isinstance(el, collections.Iterable) and not isinstance(el, basestring): for sub in flatten(el): yield sub else: yield el I used the Iterable ABC added in 2.6. Python 3 In Python 3, the basestring is no more, but you can use a tuple of str and bytes to get the same effect there. The yield from operator returns an item from a generator one at a time. This syntax for delegating to a subgenerator was added in 3.3 def flatten(l): for el in l: if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)): yield from flatten(el) else: yield el </s>
<s>[INST] How to read large file, line by line in python I want to iterate over each line of an entire file. One way to do this is by reading the entire file, saving it to a list, then going over the line of interest. This method uses a lot of memory, so I am looking for an alternative. My code so far: for each_line in fileinput.input(input_file): do_something(each_line) for each_line_again in fileinput.input(input_file): do_something(each_line_again) Executing this code gives an error message: device active. Any suggestions? EDIT: The purpose is to calculate pair-wise string similarity, meaning for each line in file, I want to calculate the Levenshtein distance with every other line. [/INST] Nobody has given the correct, fully Pythonic way to read a file. It's the following: with open(...) as f: for line in f: <do something with line> The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered IO and memory management so you don't have to worry about large files. There should be one -- and preferably only one -- obvious way to do it. </s>
<s>[INST] How to sort (list/tuple) of lists/tuples? I have some data either in list contains lists, or list contains tuples. data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)] And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I store tuples or lists in my list? Since tuples are more inflexible. [/INST] sorted_by_second = sorted(data, key=lambda tup: tup[1]) or: data.sort(key=lambda tup: tup[1]) # sorts in place </s>
<s>[INST] How to re import an updated package while in Python Interpreter? I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me. [/INST] "Reload is no longer a function in Python 3. Use imp.reload() instead" copied from comments Use the reload builtin function: https://docs.python.org/2/library/functions.html#reload When reload(module) is executed: Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time. As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero. The names in the module namespace are updated to point to any new or changed objects. Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired. Example: # Make a simple function that prints "version 1" shell1$ echo 'def x(): print "version 1"' > mymodule.py # Run the module shell2$ python >>> import mymodule >>> mymodule.x() version 1 # Change mymodule to print "version 2" (without exiting the python REPL) shell2$ echo 'def x(): print "version 2"' > mymodule.py # Back in that same python session >>> reload(mymodule) <module 'mymodule' from 'mymodule.pyc'> >>> mymodule.x() version 2 </s>
<s>[INST] What is the purpose of the single underscore "_" variable in Python? What is the meaning of _ after for in this code? if tbh.bag: n = 0 for _ in tbh.bag.atom_set(): n += 1 [/INST] _ has 3 main conventional uses in Python: To hold the result of the last executed statement in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit For translation lookup in i18n (imported from the corresponding C conventions, I believe), as in code like: raise forms.ValidationError(_("Please enter a correct username")) As a general purpose "throwaway" variable name to indicate that part of a function result is being deliberately ignored, as in code like: label, has_label, _ = text.partition(':') The latter two purposes can conflict, so it is necessary to avoid using _ as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __, as their throwaway variable for exactly this reason). </s>
<s>[INST] Fastest way to list all primes below N This is the best algorithm I could come up. def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes >>> timeit.Timer(stmt='get_primes.get_primes(1000000)', setup='import get_primes').timeit(1) 1.1499958793645562 Can it be made even faster? This code has a flaw: Since numbers is an unordered set, there is no guarantee that numbers.pop() will remove the lowest number from the set. Nevertheless, it works (at least for me) for some input numbers: >>> sum(get_primes(2000000)) 142913828922L #That's the correct sum of all numbers below 2 million >>> 529 in get_primes(1000) False >>> 529 in get_primes(530) True [/INST] Warning: timeit results may vary due to differences in hardware or version of Python. Below is a script which compares a number of implementations: ambi_sieve_plain, rwh_primes, rwh_primes1, rwh_primes2, sieveOfAtkin, sieveOfEratosthenes, sundaram3, sieve_wheel_30, ambi_sieve (requires numpy) primesfrom3to (requires numpy) primesfrom2to (requires numpy) Many thanks to stephan for bringing sieve_wheel_30 to my attention. Credit goes to Robert William Hanks for primesfrom2to, primesfrom3to, rwh_primes, rwh_primes1, and rwh_primes2. Of the plain Python methods tested, with psyco, for n=1000000, rwh_primes1 was the fastest tested. +---------------------+-------+ | Method | ms | +---------------------+-------+ | rwh_primes1 | 43.0 | | sieveOfAtkin | 46.4 | | rwh_primes | 57.4 | | sieve_wheel_30 | 63.0 | | rwh_primes2 | 67.8 | | sieveOfEratosthenes | 147.0 | | ambi_sieve_plain | 152.0 | | sundaram3 | 194.0 | +---------------------+-------+ Of the plain Python methods tested, without psyco, for n=1000000, rwh_primes2 was the fastest. +---------------------+-------+ | Method | ms | +---------------------+-------+ | rwh_primes2 | 68.1 | | rwh_primes1 | 93.7 | | rwh_primes | 94.6 | | sieve_wheel_30 | 97.4 | | sieveOfEratosthenes | 178.0 | | ambi_sieve_plain | 286.0 | | sieveOfAtkin | 314.0 | | sundaram3 | 416.0 | +---------------------+-------+ Of all the methods tested, allowing numpy, for n=1000000, primesfrom2to was the fastest tested. +---------------------+-------+ | Method | ms | +---------------------+-------+ | primesfrom2to | 15.9 | | primesfrom3to | 18.4 | | ambi_sieve | 29.3 | +---------------------+-------+ Timings were measured using the command: python -mtimeit -s"import primes" "primes.{method}(1000000)" with {method} replaced by each of the method names. primes.py: #!/usr/bin/env python import psyco; psyco.full() from math import sqrt, ceil import numpy as np def rwh_primes(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Returns a list of primes < n """ sieve = [True] * n for i in xrange(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1) return [2] + [i for i in xrange(3,n,2) if sieve[i]] def rwh_primes1(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Returns a list of primes < n """ sieve = [True] * (n/2) for i in xrange(3,int(n**0.5)+1,2): if sieve[i/2]: sieve[i*i/2::i] = [False] * ((n-i*i-1)/(2*i)+1) return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]] def rwh_primes2(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a list of primes, 2 <= p < n """ correction = (n%6>1) n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6] sieve = [True] * (n/3) sieve[0] = False for i in xrange(int(n**0.5)/3+1): if sieve[i]: k=3*i+1|1 sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1) sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1) return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]] def sieve_wheel_30(N): # http://zerovolt.com/?p=88 ''' Returns a list of primes <= N using wheel criterion 2*3*5 = 30 Copyright 2009 by zerovolt.com This code is free for non-commercial purposes, in which case you can just leave this comment as a credit for my work. If you need this code for commercial purposes, please contact me by sending an email to: info [at] zerovolt [dot] com.''' __smallp = ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997) wheel = (2, 3, 5) const = 30 if N < 2: return [] if N <= const: pos = 0 while __smallp[pos] <= N: pos += 1 return list(__smallp[:pos]) # make the offsets list offsets = (7, 11, 13, 17, 19, 23, 29, 1) # prepare the list p = [2, 3, 5] dim = 2 + N // const tk1 = [True] * dim tk7 = [True] * dim tk11 = [True] * dim tk13 = [True] * dim tk17 = [True] * dim tk19 = [True] * dim tk23 = [True] * dim tk29 = [True] * dim tk1[0] = False # help dictionary d # d[a , b] = c ==> if I want to find the smallest useful multiple of (30*pos)+a # on tkc, then I need the index given by the product of [(30*pos)+a][(30*pos)+b] # in general. If b < a, I need [(30*pos)+a][(30*(pos+1))+b] d = {} for x in offsets: for y in offsets: res = (x*y) % const if res in offsets: d[(x, res)] = y # another help dictionary: gives tkx calling tmptk[x] tmptk = {1:tk1, 7:tk7, 11:tk11, 13:tk13, 17:tk17, 19:tk19, 23:tk23, 29:tk29} pos, prime, lastadded, stop = 0, 0, 0, int(ceil(sqrt(N))) # inner functions definition def del_mult(tk, start, step): for k in xrange(start, len(tk), step): tk[k] = False # end of inner functions definition cpos = const * pos while prime < stop: # 30k + 7 if tk7[pos]: prime = cpos + 7 p.append(prime) lastadded = 7 for off in offsets: tmp = d[(7, off)] start = (pos + prime) if off == 7 else (prime * (const * (pos + 1 if tmp < 7 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 11 if tk11[pos]: prime = cpos + 11 p.append(prime) lastadded = 11 for off in offsets: tmp = d[(11, off)] start = (pos + prime) if off == 11 else (prime * (const * (pos + 1 if tmp < 11 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 13 if tk13[pos]: prime = cpos + 13 p.append(prime) lastadded = 13 for off in offsets: tmp = d[(13, off)] start = (pos + prime) if off == 13 else (prime * (const * (pos + 1 if tmp < 13 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 17 if tk17[pos]: prime = cpos + 17 p.append(prime) lastadded = 17 for off in offsets: tmp = d[(17, off)] start = (pos + prime) if off == 17 else (prime * (const * (pos + 1 if tmp < 17 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 19 if tk19[pos]: prime = cpos + 19 p.append(prime) lastadded = 19 for off in offsets: tmp = d[(19, off)] start = (pos + prime) if off == 19 else (prime * (const * (pos + 1 if tmp < 19 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 23 if tk23[pos]: prime = cpos + 23 p.append(prime) lastadded = 23 for off in offsets: tmp = d[(23, off)] start = (pos + prime) if off == 23 else (prime * (const * (pos + 1 if tmp < 23 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 29 if tk29[pos]: prime = cpos + 29 p.append(prime) lastadded = 29 for off in offsets: tmp = d[(29, off)] start = (pos + prime) if off == 29 else (prime * (const * (pos + 1 if tmp < 29 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # now we go back to top tk1, so we need to increase pos by 1 pos += 1 cpos = const * pos # 30k + 1 if tk1[pos]: prime = cpos + 1 p.append(prime) lastadded = 1 for off in offsets: tmp = d[(1, off)] start = (pos + prime) if off == 1 else (prime * (const * pos + tmp) )//const del_mult(tmptk[off], start, prime) # time to add remaining primes # if lastadded == 1, remove last element and start adding them from tk1 # this way we don't need an "if" within the last while if lastadded == 1: p.pop() # now complete for every other possible prime while pos < len(tk1): cpos = const * pos if tk1[pos]: p.append(cpos + 1) if tk7[pos]: p.append(cpos + 7) if tk11[pos]: p.append(cpos + 11) if tk13[pos]: p.append(cpos + 13) if tk17[pos]: p.append(cpos + 17) if tk19[pos]: p.append(cpos + 19) if tk23[pos]: p.append(cpos + 23) if tk29[pos]: p.append(cpos + 29) pos += 1 # remove exceeding if present pos = len(p) - 1 while p[pos] > N: pos -= 1 if pos < len(p) - 1: del p[pos+1:] # return p list return p def sieveOfEratosthenes(n): """sieveOfEratosthenes(n): return the list of the primes < n.""" # Code from: <dickinsm@gmail.com>, Nov 30 2006 # http://groups.google.com/group/comp.lang.python/msg/f1f10ced88c68c2d if n <= 2: return [] sieve = range(3, n, 2) top = len(sieve) for si in sieve: if si: bottom = (si*si - 3) // 2 if bottom >= top: break sieve[bottom::si] = [0] * -((bottom - top) // si) return [2] + [el for el in sieve if el] def sieveOfAtkin(end): """sieveOfAtkin(end): return a list of all the prime numbers <end using the Sieve of Atkin.""" # Code by Steve Krenzel, <Sgk284@gmail.com>, improved # Code: https://web.archive.org/web/20080324064651/http://krenzel.info/?p=83 # Info: http://en.wikipedia.org/wiki/Sieve_of_Atkin assert end > 0 lng = ((end-1) // 2) sieve = [False] * (lng + 1) x_max, x2, xd = int(sqrt((end-1)/4.0)), 0, 4 for xd in xrange(4, 8*x_max + 2, 8): x2 += xd y_max = int(sqrt(end-x2)) n, n_diff = x2 + y_max*y_max, (y_max << 1) - 1 if not (n & 1): n -= n_diff n_diff -= 2 for d in xrange((n_diff - 1) << 1, -1, -8): m = n % 12 if m == 1 or m == 5: m = n >> 1 sieve[m] = not sieve[m] n -= d x_max, x2, xd = int(sqrt((end-1) / 3.0)), 0, 3 for xd in xrange(3, 6 * x_max + 2, 6): x2 += xd y_max = int(sqrt(end-x2)) n, n_diff = x2 + y_max*y_max, (y_max << 1) - 1 if not(n & 1): n -= n_diff n_diff -= 2 for d in xrange((n_diff - 1) << 1, -1, -8): if n % 12 == 7: m = n >> 1 sieve[m] = not sieve[m] n -= d x_max, y_min, x2, xd = int((2 + sqrt(4-8*(1-end)))/4), -1, 0, 3 for x in xrange(1, x_max + 1): x2 += xd xd += 6 if x2 >= end: y_min = (((int(ceil(sqrt(x2 - end))) - 1) << 1) - 2) << 1 n, n_diff = ((x*x + x) << 1) - 1, (((x-1) << 1) - 2) << 1 for d in xrange(n_diff, y_min, -8): if n % 12 == 11: m = n >> 1 sieve[m] = not sieve[m] n += d primes = [2, 3] if end <= 3: return primes[:max(0,end-2)] for n in xrange(5 >> 1, (int(sqrt(end))+1) >> 1): if sieve[n]: primes.append((n << 1) + 1) aux = (n << 1) + 1 aux *= aux for k in xrange(aux, end, 2 * aux): sieve[k >> 1] = False s = int(sqrt(end)) + 1 if s % 2 == 0: s += 1 primes.extend([i for i in xrange(s, end, 2) if sieve[i >> 1]]) return primes def ambi_sieve_plain(n): s = range(3, n, 2) for m in xrange(3, int(n**0.5)+1, 2): if s[(m-3)/2]: for t in xrange((m*m-3)/2,(n>>1)-1,m): s[t]=0 return [2]+[t for t in s if t>0] def sundaram3(max_n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/2073279#2073279 numbers = range(3, max_n+1, 2) half = (max_n)//2 initial = 4 for step in xrange(3, max_n+1, 2): for i in xrange(initial, half, step): numbers[i-1] = 0 initial += 2*(step+1) if initial > half: return [2] + filter(None, numbers) ################################################################################ # Using Numpy: def ambi_sieve(n): # http://tommih.blogspot.com/2009/04/fast-prime-number-generator.html s = np.arange(3, n, 2) for m in xrange(3, int(n ** 0.5)+1, 2): if s[(m-3)/2]: s[(m*m-3)/2::m]=0 return np.r_[2, s[s>0]] def primesfrom3to(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Returns a array of primes, p < n """ assert n>=2 sieve = np.ones(n/2, dtype=np.bool) for i in xrange(3,int(n**0.5)+1,2): if sieve[i/2]: sieve[i*i/2::i] = False return np.r_[2, 2*np.nonzero(sieve)[0][1::]+1] def primesfrom2to(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a array of primes, 2 <= p < n """ sieve = np.ones(n/3 + (n%6==2), dtype=np.bool) sieve[0] = False for i in xrange(int(n**0.5)/3+1): if sieve[i]: k=3*i+1|1 sieve[ ((k*k)/3) ::2*k] = False sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)] if __name__=='__main__': import itertools import sys def test(f1,f2,num): print('Testing {f1} and {f2} return same results'.format( f1=f1.func_name, f2=f2.func_name)) if not all([a==b for a,b in itertools.izip_longest(f1(num),f2(num))]): sys.exit("Error: %s(%s) != %s(%s)"%(f1.func_name,num,f2.func_name,num)) n=1000000 test(sieveOfAtkin,sieveOfEratosthenes,n) test(sieveOfAtkin,ambi_sieve,n) test(sieveOfAtkin,ambi_sieve_plain,n) test(sieveOfAtkin,sundaram3,n) test(sieveOfAtkin,sieve_wheel_30,n) test(sieveOfAtkin,primesfrom3to,n) test(sieveOfAtkin,primesfrom2to,n) test(sieveOfAtkin,rwh_primes,n) test(sieveOfAtkin,rwh_primes1,n) test(sieveOfAtkin,rwh_primes2,n) Running the script tests that all implementations give the same result. </s>
<s>[INST] How do you express binary literals in Python? How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: >>> 0x12AF 4783 >>> 0x100 256 and octal: >>> 01267 695 >>> 0100 64 How do you use literals to express binary in Python? Summary of Answers Python 2.5 and earlier: can express binary using int('01010101111',2) but not with a literal. Python 2.5 and earlier: there is no way to express binary literals. Python 2.6 beta: You can do like so: 0b1100111 or 0B1100111. Python 2.6 beta: will also allow 0o27 or 0O27 (second character is the letter O) to represent an octal. Python 3.0 beta: Same as 2.6, but will no longer allow the older 027 syntax for octals. [/INST] For reference—future Python possibilities: Starting with Python 2.6 you can express binary literals using the prefix 0b or 0B: >>> 0b101111 47 You can also use the new bin function to get the binary representation of a number: >>> bin(173) '0b10101101' Development version of the documentation: What's New in Python 2.6 </s>
<s>[INST] Showing the stack trace from a running Python application I have this Python application that gets stuck from time to time and I can't find out where. Is there any way to signal Python interpreter to show you the exact code that's running? Some kind of on-the-fly stacktrace? Related questions: Print current call stack from a method in Python code Check what a running process is doing: print stack trace of an uninstrumented Python program [/INST] I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals): import code, traceback, signal def debug(sig, frame): """Interrupt running process, and provide a python prompt for interactive debugging.""" d={'_frame':frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) i = code.InteractiveConsole(d) message = "Signal received : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) i.interact(message) def listen(): signal.signal(signal.SIGUSR1, debug) # Register handler To use, just call the listen() function at some point when your program starts up (You could even stick it in site.py to have all python programs use it), and let it run. At any point, send the process a SIGUSR1 signal, using kill, or in python: os.kill(pid, signal.SIGUSR1) This will cause the program to break to a python console at the point it is currently at, showing you the stack trace, and letting you manipulate the variables. Use control-d (EOF) to continue running (though note that you will probably interrupt any I/O etc at the point you signal, so it isn't fully non-intrusive. I've another script that does the same thing, except it communicates with the running process through a pipe (to allow for debugging backgrounded processes etc). Its a bit large to post here, but I've added it as a python cookbook recipe. </s>
<s>[INST] Creating a JSON response using Django and Python I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working. This is the server-side script: /* RECEIVE VALUE */ $validateValue=$_POST['validateValue']; $validateId=$_POST['validateId']; $validateError=$_POST['validateError']; /* RETURN VALUE */ $arrayToJs = array(); $arrayToJs[0] = $validateId; $arrayToJs[1] = $validateError; if($validateValue =="Testuser"){ // Validate?? $arrayToJs[2] = "true"; // RETURN TRUE echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; // RETURN ARRAY WITH success } else{ for($x=0;$x<1000000;$x++){ if($x == 990000){ $arrayToJs[2] = "false"; echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; // RETURNS ARRAY WITH ERROR. } } } And this is the converted code def validate_user(request): if request.method == 'POST': vld_value = request.POST.get('validateValue') vld_id = request.POST.get('validateId') vld_error = request.POST.get('validateError') array_to_js = [vld_id, vld_error, False] if vld_value == "TestUser": array_to_js[2] = True x = simplejson.dumps(array_to_js) return HttpResponse(x) else: array_to_js[2] = False x = simplejson.dumps(array_to_js) error = 'Error' return render_to_response('index.html',{'error':error},context_instance=RequestContext(request)) return render_to_response('index.html',context_instance=RequestContext(request)) I'm using simplejson to encode the Python list (so it will return a JSON array). I couldn't figure out the problem yet. But I think that I did something wrong about the 'echo'. [/INST] I usually use a dictionary, not a list to return JSON content. import json from django.http import HttpResponse response_data = {} response_data['result'] = 'error' response_data['message'] = 'Some error message' Pre-Django 1.7 you'd return it like this: return HttpResponse(json.dumps(response_data), content_type="application/json") For Django 1.7+, use JsonResponse as shown in this SO answer like so : from django.http import JsonResponse return JsonResponse({'foo':'bar'}) </s>
<s>[INST] How do I correctly clean up a Python object? class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) __del__(self) above fails with an AttributeError exception. I understand Python doesn't guarantee the existence of "global variables" (member data in this context?) when __del__() is invoked. If that is the case and this is the reason for the exception, how do I make sure the object destructs properly? [/INST] I'd recommend using Python's with statement for managing resources that need to be cleaned up. The problem with using an explicit close() statement is that you have to worry about people forgetting to call it at all or forgetting to place it in a finally block to prevent a resource leak when an exception occurs. To use the with statement, create a class with the following methods: def __enter__(self) def __exit__(self, exc_type, exc_value, traceback) In your example above, you'd use class Package: def __init__(self): self.files = [] def __enter__(self): return self # ... def __exit__(self, exc_type, exc_value, traceback): for file in self.files: os.unlink(file) Then, when someone wanted to use your class, they'd do the following: with Package() as package_obj: # use package_obj The variable package_obj will be an instance of type Package (it's the value returned by the __enter__ method). Its __exit__ method will automatically be called, regardless of whether or not an exception occurs. You could even take this approach a step further. In the example above, someone could still instantiate Package using its constructor without using the with clause. You don't want that to happen. You can fix this by creating a PackageResource class that defines the __enter__ and __exit__ methods. Then, the Package class would be defined strictly inside the __enter__ method and returned. That way, the caller never could instantiate the Package class without using a with statement: class PackageResource: def __enter__(self): class Package: ... self.package_obj = Package() return self.package_obj def __exit__(self, exc_type, exc_value, traceback): self.package_obj.cleanup() You'd use this as follows: with PackageResource() as package_obj: # use package_obj </s>
<s>[INST] Proper way to use **kwargs in Python What is the proper way to use **kwargs in Python when it comes to default values? kwargs returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? class ExampleClass: def __init__(self, **kwargs): self.val = kwargs['val'] self.val2 = kwargs.get('val2') A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use. [/INST] You can pass a default value to get() for keys that are not in the dictionary: self.val2 = kwargs.get('val2',"default value") However, if you plan on using a particular argument with a particular default value, why not use named arguments in the first place? def __init__(self, val2="default value", **kwargs): </s>
<s>[INST] No module named pkg_resources I'm deploying a Django app to a dev server and am hitting this error when i run pip install requirements.txt: Traceback (most recent call last): File "/var/www/mydir/virtualenvs/dev/bin/pip", line 5, in <module> from pkg_resources import load_entry_point ImportError: No module named pkg_resources pkg_resources appears to be distributed with setuptools. Initially I thought this might not be installed to the python in the virtualenv so I installed setuptools (2.6, same version as Python) to the Python site-packages in the virtualenv with the following command sh setuptools-0.6c11-py2.6.egg --install-dir /var/www/mydir/virtualenvs/dev/lib/python2.6/site-packages EDIT This only happens inside the virtualenv. If I open a console outside the virtualenv then pkg_resources is present but I am still getting the same error. Any ideas as to why pkg_resources is not on the path? [/INST] I encountered the same ImportError today while trying to use pip. Somehow the setuptools package had been deleted in my Python environment. To fix the issue, run the setup script for setuptools: wget https://bootstrap.pypa.io/ez_setup.py -O - | python (or if you don't have wget installed (e.g. OS X), try curl https://bootstrap.pypa.io/ez_setup.py | python possibly with sudo prepended.) If you have any version of distribute, or any setuptools below 0.6, you will have to uninstall it first.* See Installation Instructions for further details. * If you already have a working distribute, upgrading it to the "compatibility wrapper" that switches you over to setuptools is easier. But if things are already broken, don't try that. </s>
<s>[INST] Rename Files in Python I'm trying to rename some files in a directory using Python. Say I have a file called CHEESE_CHEESE_TYPE.*** and want to remove CHEESE_ so my resulting filename would be CHEESE_TYPE I'm trying to use the os.path.split but it's not working properly. I have also considered using string manipulations, but have not been successful with that either. [/INST] Do you want something like this? $ ls cheese_cheese_type.bar cheese_cheese_type.foo $ python >>> import os >>> for filename in os.listdir("."): ... if filename.startswith("cheese_"): ... os.rename(filename, filename[7:]) ... >>> $ ls cheese_type.bar cheese_type.foo </s>
<s>[INST] Find which version of package is installed with pip Using pip, is it possible to figure out which version of a package is currently installed? I know about pip install XYZ --upgrade but I am wondering if there is anything like pip info XYZ. If not what would be the best way to tell what version I am currently using. [/INST] As of pip 1.3, there is a pip show command. $ pip show Jinja2 --- Name: Jinja2 Version: 2.7.3 Location: /path/to/virtualenv/lib/python2.7/site-packages Requires: markupsafe In older versions, pip freeze and grep should do the job nicely. $ pip freeze | grep Jinja2 Jinja2==2.7.3 </s>
<s>[INST] How to create a GUID/UUID in Python How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python? [/INST] If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution. Ex: >>> import uuid >>> uuid.uuid4() UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14') </s>
<s>[INST] IndentationError: unindent does not match any outer indentation level When I compile the Python code below, I get IndentationError: unindent does not match any outer indentation level import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result Why? [/INST] EDIT: Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search&replace to replace all tabs with a few spaces. Try this: import sys def Factorial(n): # return factorial result = 1 for i in range (1,n): result = result * i print "factorial is ",result return result print Factorial(10) </s>
<s>[INST] A Transpose/Unzip Function in Python (inverse of zip) I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. For example: original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) Is there a builtin function that does that? [/INST] zip is its own inverse! Provided you use the special * operator. >>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] The way this works is by calling zip with the arguments: zip(('a', 1), ('b', 2), ('c', 3), ('d', 4)) … except the arguments are passed to zip directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big. </s>
<s>[INST] What is the most "pythonic" way to iterate over a list in chunks? I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way: for i in xrange(0, len(ints), 4): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better? while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] Still doesn't quite "feel" right, though. :-/ Related question: How do you split a list into evenly sized chunks in Python? [/INST] def chunker(seq, size): return (seq[pos:pos + size] for pos in xrange(0, len(seq), size)) Simple. Easy. Fast. Works with any sequence: text = "I am a very, very helpful text" for group in chunker(text, 7): print repr(group), # 'I am a ' 'very, v' 'ery hel' 'pful te' 'xt' print '|'.join(chunker(text, 10)) # I am a ver|y, very he|lpful text animals = ['cat', 'dog', 'rabbit', 'duck', 'bird', 'cow', 'gnu', 'fish'] for group in chunker(animals, 3): print group # ['cat', 'dog', 'rabbit'] # ['duck', 'bird', 'cow'] # ['gnu', 'fish'] </s>
<s>[INST] What exactly do "u" and "r" string flags do in Python, and what are raw string literals? While asking this question, I realized I didn't know much about raw strings. For somebody claiming to be a Django trainer, this sucks. I know what an encoding is, and I know what u alone does since I get what is Unicode. But what does r do exactly? What kind of string does it result in? And above all, what the heck does ur do? Finally, is there any reliable way to go back from a Unicode string to a simple raw string? Ah, and by the way, if your system and your text editor charset are set to UTF-8, does u actually do anything? [/INST] There's not really any "raw string"; there are raw string literals, which are exactly the string literals marked by a 'r' before the opening quote. A "raw string literal" is a slightly different syntax for a string literal, in which a backslash, \, is taken as meaning "just a backslash" (except when it comes right before a quote that would otherwise terminate the literal) -- no "escape sequences" to represent newlines, tabs, backspaces, form-feeds, and so on. In normal string literals, each backslash must be doubled up to avoid being taken as the start of an escape sequence. This syntax variant exists mostly because the syntax of regular expression patterns is heavy with backslashes (but never at the end, so the "except" clause above doesn't matter) and it looks a bit better when you avoid doubling up each of them -- that's all. It also gained some popularity to express native Windows file paths (with backslashes instead of regular slashes like on other platforms), but that's very rarely needed (since normal slashes mostly work fine on Windows too) and imperfect (due to the "except" clause above). r'...' is a byte string (in Python 2.*), ur'...' is a Unicode string (again, in Python 2.*), and any of the other three kinds of quoting also produces exactly the same types of strings (so for example r'...', r'''...''', r"...", r"""...""" are all byte strings, and so on). Not sure what you mean by "going back" - there is no intrinsically back and forward directions, because there's no raw string type, it's just an alternative syntax to express perfectly normal string objects, byte or unicode as they may be. And yes, in Python 2.*, u'...' is of course always distinct from just '...' -- the former is a unicode string, the latter is a byte string. What encoding the literal might be expressed in is a completely orthogonal issue. E.g., consider (Python 2.6): >>> sys.getsizeof('ciao') 28 >>> sys.getsizeof(u'ciao') 34 the Unicode object of course takes more memory space (very small difference for a very short string, obviously;-). </s>
<s>[INST] How to save a Python interactive session? I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like script I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach? UPDATE: I am really amazed at the quality and usefulness of these packages. For those with a similar itch: IPython -- should have been using this for ages, kind of what I had in mind reinteract -- very impressive, I want to learn more about visualization and this seems like it will shine there. Sort of a gtk/gnome desktop app that renders graphs inline. Imagine a hybrid shell + graphing calculator + mini eclipse. Source distribution here: http://www.reinteract.org/trac/wiki/GettingIt . Built fine on Ubuntu, integrates into gnome desktop, Windows and Mac installers too. bpython -- extremely cool, lots of nice features, autocomplete(!), rewind, one keystroke save to file, indentation, well done. Python source distribution, pulled a couple of dependencies from sourceforge. I am converted, these really fill a need between interpreter and editor. [/INST] IPython is extremely useful if you like using interactive sessions. For example for your usecase there is the %save magic command, you just input %save my_useful_session 10-20 23 to save input lines 10 to 20 and 23 to my_useful_session.py. (to help with this, every line is prefixed by its number) Look at the videos on the documentation page to get a quick overview of the features. </s>
<s>[INST] Python: about catching ANY exception How can I write a try/except block that catches all exceptions? [/INST] Apart from a bare except: clause (which as others have said you shouldn't use), you can simply catch Exception: import traceback import logging try: whatever() except Exception as e: logging.error(traceback.format_exc()) # Logs the error appropriately. You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating. The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script. </s>
<s>[INST] Check if a Python list item contains a string inside another string I have a list: my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456'] and want to search for items that contain the string 'abc'. How can I do that? if 'abc' in my_list: would check if 'abc' exists in the list but it is a part of 'abc-123' and 'abc-456', 'abc' does not exist on its own. So how can I get all items that contain 'abc' ? [/INST] If you only want to check for the presence of abc in any string in the list, you could try some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456'] if any("abc" in s for s in some_list): # whatever If you really want to get all the items containing abc, use matching = [s for s in some_list if "abc" in s] </s>
<s>[INST] Elegant Python function to convert CamelCase to snake_case? Example: >>> convert('CamelCase') 'camel_case' [/INST] This is pretty thorough: def convert(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() Works with all these (and doesn't harm already-un-cameled versions): >>> convert('CamelCase') 'camel_case' >>> convert('CamelCamelCase') 'camel_camel_case' >>> convert('Camel2Camel2Case') 'camel2_camel2_case' >>> convert('getHTTPResponseCode') 'get_http_response_code' >>> convert('get2HTTPResponseCode') 'get2_http_response_code' >>> convert('HTTPResponseCode') 'http_response_code' >>> convert('HTTPResponseCodeXYZ') 'http_response_code_xyz' Or if you're going to call it a zillion times, you can pre-compile the regexes: first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') def convert(name): s1 = first_cap_re.sub(r'\1_\2', name) return all_cap_re.sub(r'\1_\2', s1).lower() Don't forget to import the regular expression module import re </s>
<s>[INST] Maximum and Minimum values for ints I am looking for minimum and maximum values for integers in python. For eg., in Java, we have Integer.MIN_VALUE and Integer.MAX_VALUE. Is there something like this in python? [/INST] In Python 2, there's sys.maxint: >>> sys.maxint 9223372036854775807 And you can calculate the minimum value with -sys.maxint - 1 as seen here. Of course Python just switches from plain to long integers once you exceed this value. In Python 3 this value has no significance at all for integers. (However, a closely related value is still available as sys.maxsize, in case you're actually looking for the machine's word size.) </s>
<s>[INST] Is it worth using Python's re.compile? Is there any benefit in using compile for regular expressions in Python? h = re.compile('hello') h.match('hello world') vs re.match('hello', 'hello world') [/INST] I've had a lot of experience running a compiled regex 1000s of times versus compiling on-the-fly, and have not noticed any perceivable difference. Obviously, this is anecdotal, and certainly not a great argument against compiling, but I've found the difference to be negligible. EDIT: After a quick glance at the actual Python 2.5 library code, I see that Python internally compiles AND CACHES regexes whenever you use them anyway (including calls to re.match()), so you're really only changing WHEN the regex gets compiled, and shouldn't be saving much time at all - only the time it takes to check the cache (a key lookup on an internal dict type). From module re.py (comments are mine): def match(pattern, string, flags=0): return _compile(pattern, flags).match(string) def _compile(*key): # Does cache check at top of function cachekey = (type(key[0]),) + key p = _cache.get(cachekey) if p is not None: return p # ... # Does actual compilation on cache miss # ... # Caches compiled regex if len(_cache) >= _MAXCACHE: _cache.clear() _cache[cachekey] = p return p I still often pre-compile regular expressions, but only to bind them to a nice, reusable name, not for any expected performance gain. </s>
<s>[INST] Why is 'x' in ('x',) faster than 'x' == 'x'? >>> timeit.timeit("'x' in ('x',)") 0.04869917374131205 >>> timeit.timeit("'x' == 'x'") 0.06144205736110564 Also works for tuples with multiple elements, both versions seem to grow linearly: >>> timeit.timeit("'x' in ('x', 'y')") 0.04866674801541748 >>> timeit.timeit("'x' == 'x' or 'x' == 'y'") 0.06565782838087131 >>> timeit.timeit("'x' in ('y', 'x')") 0.08975995576448526 >>> timeit.timeit("'x' == 'y' or 'x' == 'y'") 0.12992391047427532 Based on this, I think I should totally start using in everywhere instead of ==! [/INST] As I mentioned to David Wolever, there's more to this than meets the eye; both methods dispatch to is; you can prove this by doing min(Timer("x == x", setup="x = 'a' * 1000000").repeat(10, 10000)) #>>> 0.00045456900261342525 min(Timer("x == y", setup="x = 'a' * 1000000; y = 'a' * 1000000").repeat(10, 10000)) #>>> 0.5256857610074803 The first can only be so fast because it checks by identity. To find out why one would take longer than the other, let's trace through execution. They both start in ceval.c, from COMPARE_OP since that is the bytecode involved TARGET(COMPARE_OP) { PyObject *right = POP(); PyObject *left = TOP(); PyObject *res = cmp_outcome(oparg, left, right); Py_DECREF(left); Py_DECREF(right); SET_TOP(res); if (res == NULL) goto error; PREDICT(POP_JUMP_IF_FALSE); PREDICT(POP_JUMP_IF_TRUE); DISPATCH(); } This pops the values from the stack (technically it only pops one) PyObject *right = POP(); PyObject *left = TOP(); and runs the compare: PyObject *res = cmp_outcome(oparg, left, right); cmp_outcome is this: static PyObject * cmp_outcome(int op, PyObject *v, PyObject *w) { int res = 0; switch (op) { case PyCmp_IS: ... case PyCmp_IS_NOT: ... case PyCmp_IN: res = PySequence_Contains(w, v); if (res < 0) return NULL; break; case PyCmp_NOT_IN: ... case PyCmp_EXC_MATCH: ... default: return PyObject_RichCompare(v, w, op); } v = res ? Py_True : Py_False; Py_INCREF(v); return v; } This is where the paths split. The PyCmp_IN branch does int PySequence_Contains(PyObject *seq, PyObject *ob) { Py_ssize_t result; PySequenceMethods *sqm = seq->ob_type->tp_as_sequence; if (sqm != NULL && sqm->sq_contains != NULL) return (*sqm->sq_contains)(seq, ob); result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS); return Py_SAFE_DOWNCAST(result, Py_ssize_t, int); } Note that a tuple is defined as static PySequenceMethods tuple_as_sequence = { ... (objobjproc)tuplecontains, /* sq_contains */ }; PyTypeObject PyTuple_Type = { ... &tuple_as_sequence, /* tp_as_sequence */ ... }; So the branch if (sqm != NULL && sqm->sq_contains != NULL) will be taken and *sqm->sq_contains, which is the function (objobjproc)tuplecontains, will be taken. This does static int tuplecontains(PyTupleObject *a, PyObject *el) { Py_ssize_t i; int cmp; for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i), Py_EQ); return cmp; } ...Wait, wasn't that PyObject_RichCompareBool what the other branch took? Nope, that was PyObject_RichCompare. That code path was short so it likely just comes down to the speed of these two. Let's compare. int PyObject_RichCompareBool(PyObject *v, PyObject *w, int op) { PyObject *res; int ok; /* Quick result when objects are the same. Guarantees that identity implies equality. */ if (v == w) { if (op == Py_EQ) return 1; else if (op == Py_NE) return 0; } ... } The code path in PyObject_RichCompareBool pretty much immediately terminates. For PyObject_RichCompare, it does PyObject * PyObject_RichCompare(PyObject *v, PyObject *w, int op) { PyObject *res; assert(Py_LT <= op && op <= Py_GE); if (v == NULL || w == NULL) { ... } if (Py_EnterRecursiveCall(" in comparison")) return NULL; res = do_richcompare(v, w, op); Py_LeaveRecursiveCall(); return res; } The Py_EnterRecursiveCall/Py_LeaveRecursiveCall combo are not taken in the previous path, but these are relatively quick macros that'll short-circuit after incrementing and decrementing some globals. do_richcompare does: static PyObject * do_richcompare(PyObject *v, PyObject *w, int op) { richcmpfunc f; PyObject *res; int checked_reverse_op = 0; if (v->ob_type != w->ob_type && ...) { ... } if ((f = v->ob_type->tp_richcompare) != NULL) { res = (*f)(v, w, op); if (res != Py_NotImplemented) return res; ... } ... } This does some quick checks to call v->ob_type->tp_richcompare which is PyTypeObject PyUnicode_Type = { ... PyUnicode_RichCompare, /* tp_richcompare */ ... }; which does PyObject * PyUnicode_RichCompare(PyObject *left, PyObject *right, int op) { int result; PyObject *v; if (!PyUnicode_Check(left) || !PyUnicode_Check(right)) Py_RETURN_NOTIMPLEMENTED; if (PyUnicode_READY(left) == -1 || PyUnicode_READY(right) == -1) return NULL; if (left == right) { switch (op) { case Py_EQ: case Py_LE: case Py_GE: /* a string is equal to itself */ v = Py_True; break; case Py_NE: case Py_LT: case Py_GT: v = Py_False; break; default: ... } } else if (...) { ... } else { ...} Py_INCREF(v); return v; } Namely, this shortcuts on left == right... but only after doing if (!PyUnicode_Check(left) || !PyUnicode_Check(right)) if (PyUnicode_READY(left) == -1 || PyUnicode_READY(right) == -1) All in all the paths then look something like this (manually recursively inlining, unrolling and pruning known branches) POP() # Stack stuff TOP() # # case PyCmp_IN: # Dispatch on operation # sqm != NULL # Dispatch to builtin op sqm->sq_contains != NULL # *sqm->sq_contains # # cmp == 0 # Do comparison in loop i < Py_SIZE(a) # v == w # op == Py_EQ # ++i # cmp == 0 # # res < 0 # Convert to Python-space res ? Py_True : Py_False # Py_INCREF(v) # # Py_DECREF(left) # Stack stuff Py_DECREF(right) # SET_TOP(res) # res == NULL # DISPATCH() # vs POP() # Stack stuff TOP() # # default: # Dispatch on operation # Py_LT <= op # Checking operation op <= Py_GE # v == NULL # w == NULL # Py_EnterRecursiveCall(...) # Recursive check # v->ob_type != w->ob_type # More operation checks f = v->ob_type->tp_richcompare # Dispatch to builtin op f != NULL # # !PyUnicode_Check(left) # ...More checks !PyUnicode_Check(right)) # PyUnicode_READY(left) == -1 # PyUnicode_READY(right) == -1 # left == right # Finally, doing comparison case Py_EQ: # Immediately short circuit Py_INCREF(v); # # res != Py_NotImplemented # # Py_LeaveRecursiveCall() # Recursive check # Py_DECREF(left) # Stack stuff Py_DECREF(right) # SET_TOP(res) # res == NULL # DISPATCH() # Now, PyUnicode_Check and PyUnicode_READY are pretty cheap since they only check a couple of fields, but it should be obvious that the top one is a smaller code path, it has fewer function calls, only one switch statement and is just a bit thinner. TL;DR: Both dispatch to if (left_pointer == right_pointer); the difference is just how much work they do to get there. in just does less. </s>
<s>[INST] How do I run Python code from Sublime Text 2? I want to set up a complete Python IDE in Sublime Text 2. I want to know how to run the Python code from within the editor. Is it done using build system? How do I do it ? [/INST] Tools -> Build System -> (choose) Python then: To Run: Tools -> Build -or- Ctrl + B CMD + B (OSX) This would start your file in the console which should be at the bottom of the editor. To Stop: Ctrl + Break or Tools -> Cancel Build You can find out where your Break key is here: http://en.wikipedia.org/wiki/Break_key. Note: CTRL + C will NOT work. What to do when Ctrl + Break does not work: Go to: Preferences -> Key Bindings - User and paste the line below: {"keys": ["ctrl+shift+c"], "command": "exec", "args": {"kill": true} } Now, you can use ctrl+shift+c instead of CTRL+BREAK </s>
<s>[INST] How to print a class or objects of class using print()? I am learning the ropes in Python. When I try to print an object of class Foobar using the print() function, I get an output like this: <__main__.Foobar instance at 0x7ff2a18c> Is there a way I can set the printing behaviour (or the string representation) of a class and its objects? For instance, when I call print() on a class object, I would like to print its data members in a certain format. How to achieve this in Python? If you are familiar with C++ classes, the above can be achieved for the standard ostream by adding a friend ostream& operator << (ostream&, const Foobar&) method for the class. [/INST] >>> class Test: ... def __repr__(self): ... return "Test()" ... def __str__(self): ... return "member of Test" ... >>> t = Test() >>> t Test() >>> print t member of Test The __str__ method is what happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt). If this isn't the most Pythonic method, I apologize, because I'm still learning too - but it works. If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing. </s>
<s>[INST] Convert a list of characters into a string If I have a list of chars: a = ['a','b','c','d'] How do I convert it into a single string? a = 'abcd' [/INST] Use the join method of the empty string to join all of the strings together with the empty string in between, like so: >>> a = ['a', 'b', 'c', 'd'] >>> ''.join(a) 'abcd' </s>
<s>[INST] What's the idiomatic syntax for prepending to a short python list? list.append() is the obvious choice for adding to the end of a list. Here's a reasonable explanation for the missing list.prepend(). Assuming my list is short and performance concerns are negligible, is list.insert(0, x) or list[0:0] = [x] idiomatic? [/INST] The s.insert(0, x) form is the most common. Whenever you see it though, it may be time to consider using a collections.deque instead of a list. </s>
<s>[INST] Which exception should I raise on bad/illegal argument combinations in Python? I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so: def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass The only annoyance with this is that every package has its own, usually slightly differing BadValueError. I know that in Java there exists java.lang.IllegalArgumentException -- is it well understood that everybody will be creating their own BadValueErrors in Python or is there another, preferred method? [/INST] I would just raise ValueError, unless you need a more specific exception.. def import_to_orm(name, save=False, recurse=False): if recurse and not save: raise ValueError("save must be True if recurse is True") There's really no point in doing class BadValueError(ValueError):pass - your custom class is identical in use to ValueError, so why not use that? </s>
<s>[INST] Python urlencode querystring I am trying to urlencode this string before I submit. queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; [/INST] Python 2 What you're looking for is urllib.quote_plus: >>> urllib.quote_plus('string_of_characters_like_these:$#@=?%^Q^$') 'string_of_characters_like_these%3A%24%23%40%3D%3F%25%5EQ%5E%24' Python 3 In Python 3, you the urllib package has been broken into smaller components. You'll use urllib.parse.quote_plus() (note the parse child module). </s>
<s>[INST] How to check Django version I have to use Python and Django for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. But how do I make sure whether Django uses the 2.6 or 2.7 version and what version of modules Django uses? [/INST] Django 1.5 supports Python 2.6.5 and later. If you're under Linux and want to check the Python version you're using, run python -V from the command line. If you want to check the Django version, open a Python console and type import django django.VERSION </s>
<s>[INST] Fastest way to check if a value exist in a list I'm searching for the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is? I know all values in the list are unique like my example. My first methods I try is(3.8sec in my real code): a = [4,2,3,1,5,6] if a.count(7) == 1: b=a.index(7) "Do something with variable b" My second methods I try is (2x faster:1.9sec on my real code): a = [4,2,3,1,5,6] try: b=a.index(7) except ValueError: "Do nothing" Else: "Do something with variable b" Proposed methods from S.O. user (2.74sec on my real code): a = [4,2,3,1,5,6] if 7 in a: a.index(7) In my real code , first method take 3.81sec and the second methods take 1.88sec. It's a good improvement but: I'm a beginner with Python/scripting and I want to know if a fastest way exist to do the same things and save more process time? More specific explication for my application: In the API of blender a can access to a list of particles: particles = [1,2,3,4...etc.] From there , I can access to it's location: particles[x].location = [x,y,z] And I test for each particles if a neighbour exist by searching in the location of each particles like: if [x+1,y,z] in particles.location "find the identity of this neighbour particles in x:the index of the particles array" particles.index([x+1,y,z]) [/INST] 7 in a Clearest and fastest way to do it. You can also consider using a set, but constructing that set from your list may take more time than faster membership testing will save. The only way to be certain is to benchmark well. (this also depends on what operations you require) </s>
<s>[INST] How do I get my python program to sleep for 50 milliseconds? How do I get my python program to sleep for 50 milliseconds? [/INST] Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from time import sleep >>> sleep(0.05) >>> </s>
<s>[INST] What's the difference between eval, exec, and compile in Python? I've been looking at dynamic evaluation of Python code, and come across the eval() and compile() functions, and the exec statement. Can someone please explain the difference between eval and exec, and how the different modes of compile() fit in? [/INST] exec is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example: exec('print(5)') # prints 5. # exec 'print 5' if you use Python 2.x, nor the exec neither the print is a function there exec('print(5)\nprint(6)') # prints 5{newline}6. exec('if True: print(6)') # prints 6. exec('5') # does nothing and returns nothing. eval is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example: x = eval('5') # x <- 5 x = eval('%d + 6' % x) # x <- 11 x = eval('abs(%d)' % -100) # x <- 100 x = eval('x = 5') # INVALID; assignment is not an expression. x = eval('if 1: x = 4') # INVALID; if is a statement, not an expression. compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows: compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid. compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here. compile(string, '', 'single') is like the exec mode, but it will ignore everything except for the first statement. Note that an if/else statement with its results is considered a single statement. </s>
<s>[INST] How to find out the number of CPUs using python I want to know the number of CPUs on the local machine using Python. The result should be user/real as output by time(1) when called with an optimally scaling userspace-only program. [/INST] If you have python with a version >= 2.6 you can simply use import multiprocessing multiprocessing.cpu_count() http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count </s>
<s>[INST] What is the best way to remove accents in a Python unicode string? I have a Unicode string in Python, and I would like to remove all the accents (diacritics). I found on the Web an elegant way to do this in Java: convert the Unicode string to its long normalized form (with a separate character for letters and diacritics) remove all the characters whose Unicode type is "diacritic". Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3? Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart. [/INST] How about this: import unicodedata def strip_accents(s): return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') This works on greek letters, too: >>> strip_accents(u"A \u00c0 \u0394 \u038E") u'A A \u0394 \u03a5' >>> The character category "Mn" stands for Nonspacing_Mark, which is similar to unicodedata.combining in MiniQuark's answer (I didn't think of unicodedata.combining, but it is probably the better solution, because it's more explicit). And keep in mind, these manipulations may significantly alter the meaning of the text. Accents, Umlauts etc. are not "decoration". </s>
<s>[INST] Simple Digit Recognition OCR in OpenCV-Python I am trying to implement a "Digit Recognition OCR" in OpenCV-Python (cv2). It is just for learning purposes. I would like to learn both KNearest and SVM features in OpenCV. I have 100 samples (i.e. images) of each digit. I would like to train with them. There is a sample letter_recog.py that comes with OpenCV sample. But i still couldn't figure out on how to use it. I don't understand what are the samples, responses etc. Also, it loads a txt file at first, which i didn't understand first. Later on searching a little bit, i could find a letter_recognition.data in cpp samples. I used it and made a code for cv2.KNearest in the model of letter_recog.py (just for testing): import numpy as np import cv2 fn = 'letter-recognition.data' a = np.loadtxt(fn, np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') }) samples, responses = a[:,1:], a[:,0] model = cv2.KNearest() retval = model.train(samples,responses) retval, results, neigh_resp, dists = model.find_nearest(samples, k = 10) print results.ravel() It gave me an array of size 20000, i don't understand what it is. Questions: 1) What is letter_recognition.data file ? How to build that file from my own data set? 2) What does results.reval() denote? 3) How we can write a simple digit recognition tool using letter_recognition.data file (either KNearest or SVM)? [/INST] Well, I decided to workout myself on my question to solve above problem. What i wanted is to implement a simpl OCR using KNearest or SVM features in OpenCV. And below is what i did and how. ( it is just for learning how to use KNearest for simple OCR purposes). 1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file. It contains a letter, along with 16 features of that letter. And this SOF helped me to find it. These 16 features are explained in the paperLetter Recognition Using Holland-Style Adaptive Classifiers. ( Although i didn't understand some of the features at end) 2) Since i knew, without understanding all those features, it is difficult to do that method. i tried some other papers, but all were a little difficult for a beginner. So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, i just wanted it to work, at least with the least accuracy) I took below image for my training data: ( I know the amount of training data is less. But, since all letters are of same font and size, i decided to try on this). To prepare the data for training, i made a small code in OpenCV. It does following things: a) It loads the image. b) Selects the digits ( obviously by contour finding and applying constraints on area and height of letters to avoid false detections). c) Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in box. d) Once corresponding digit key is pressed, it resizes this box to 10x10 and saves 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses). e) Then save both the arrays in separate txt files. At the end of manual classification of digits, all the digits in the train data( train.png) are labeled manually by ourselves, image will look like below: Below is the code i used for above purpose ( of course, not so clean): import sys import numpy as np import cv2 im = cv2.imread('pitrain.png') im3 = im.copy() gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,5),0) thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2) ################# Now finding Contours ################### contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) samples = np.empty((0,100)) responses = [] keys = [i for i in range(48,58)] for cnt in contours: if cv2.contourArea(cnt)>50: [x,y,w,h] = cv2.boundingRect(cnt) if h>28: cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2) roi = thresh[y:y+h,x:x+w] roismall = cv2.resize(roi,(10,10)) cv2.imshow('norm',im) key = cv2.waitKey(0) if key == 27: # (escape to quit) sys.exit() elif key in keys: responses.append(int(chr(key))) sample = roismall.reshape((1,100)) samples = np.append(samples,sample,0) responses = np.array(responses,np.float32) responses = responses.reshape((responses.size,1)) print "training complete" np.savetxt('generalsamples.data',samples) np.savetxt('generalresponses.data',responses) Now we enter in to training and testing part. For testing part i used below image, which has same type of letters i used to train. For training we do as follows: a) Load the txt files we already saved earlier b) create a instance of classifier we are using ( here, it is KNearest) c) Then we use KNearest.train function to train the data For testing purposes, we do as follows: a) We load the image used for testing b) process the image as earlier and extract each digit using contour methods c) Draw bounding box for it, then resize to 10x10, and store its pixel values in an array as done earlier. d) Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognises the correct digit.) I included last two steps ( training and testing) in single code below: import cv2 import numpy as np ####### training part ############### samples = np.loadtxt('generalsamples.data',np.float32) responses = np.loadtxt('generalresponses.data',np.float32) responses = responses.reshape((responses.size,1)) model = cv2.KNearest() model.train(samples,responses) ############################# testing part ######################### im = cv2.imread('pi.png') out = np.zeros(im.shape,np.uint8) gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2) contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: if cv2.contourArea(cnt)>50: [x,y,w,h] = cv2.boundingRect(cnt) if h>28: cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2) roi = thresh[y:y+h,x:x+w] roismall = cv2.resize(roi,(10,10)) roismall = roismall.reshape((1,100)) roismall = np.float32(roismall) retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1) string = str(int((results[0][0]))) cv2.putText(out,string,(x,y+h),0,1,(0,255,0)) cv2.imshow('im',im) cv2.imshow('out',out) cv2.waitKey(0) And it worked , below is the result i got: Here it worked with 100% accuracy, for which the reason, i assume, is all digits are of same kind and same size. But any way, this is a good start to go for beginners ( i hope so). </s>
<s>[INST] How do I make python to wait for a pressed key I want my script to wait until the user presses any key. How do I do that? [/INST] One way to do this in Python 2, is to use raw_input(): raw_input("Press Enter to continue...") In python3 it's just input() </s>
<s>[INST] Find all packages installed with easy_install/pip? Is there a way to find all Python PyPI packages that were installed with easy_install or pip? I mean, excluding everything that was/is installed with the distributions tools (in this case apt-get on Debian). [/INST] pip freeze will output a list of installed packages and their versions. It also allows you to write those packages to a file that can later be used to set up a new environment. http://www.pip-installer.org/en/latest/index.html#freezing-requirements </s>
<s>[INST] Short Description of Scoping Rules What exactly are the Python scoping rules? If I have some code: code1 class Foo: code2 def spam..... code3 for code4..: code5 x() Where is x found? Some possible choices include the list above: In the enclosing source file In the class namespace In the function definition In the for loop index variable Inside the for loop Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently? There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers. [/INST] Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply) LEGB Rule. L, Local — Names assigned in any way within a function (def or lambda)), and not declared global in that function. E, Enclosing function locals — Name in the local scope of any and all enclosing functions (def or lambda), from inner to outer. G, Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file. B, Built-in (Python) — Names preassigned in the built-in names module : open,range,SyntaxError,... So, in the case of code1 class Foo: code2 def spam..... code3 for code4..: code5 x() The for loop does not have its own namespace. In LEGB order, the scopes would be L : local, in the current def. E : Enclosed function, any enclosing functions (if def spam was in another def) G : Global. Were there any declared globally in the module? B : Any builtin x() in Python. </s>
<s>[INST] Does Python have an ordered set? Python has an ordered dictionary, what about an ordered set? [/INST] There is an ordered set recipe for this which is referred to from the Python 2 Documentation. This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same as a normal set, except that initialisation should be done with a list. OrderedSet([1, 2, 3]) This is a MutableSet, so the signature for .union doesn't match that of set, but since it includes __or__ something similar can easily be added: @staticmethod def union(*sets): union = OrderedSet() union.union(*sets) return union def union(self, *sets): for set in sets: self |= set </s>
<s>[INST] time.sleep -- sleeps thread or process? In Python for the *nix, does time.sleep() block the thread or the process? [/INST] It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep(), the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program: import time from threading import Thread class worker(Thread): def run(self): for x in xrange(0,11): print x time.sleep(1) class waiter(Thread): def run(self): for x in xrange(100,103): print x time.sleep(5) def run(): worker().start() waiter().start() Which will print: >>> thread_test.run() 0 100 >>> 1 2 3 4 5 101 6 7 8 9 10 102 </s>
<s>[INST] Python list of lists, changes reflected across sublists unexpectedly I needed to create a list of lists in Python, so I typed the following: myList = [[1] * 4] * 3 The list looked like this: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] Then I changed one of the innermost values: myList[0][0] = 5 Now my list looks like this: [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]] which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it? [/INST] When you write [x]*3 you get, essentially, the list [x, x, x]. That is, a list with 3 references to the same x. When you then modify this single x it is visible via all three references to it. To fix it, you need to make sure that you create a new list at each position. One way to do it is [[1]*4 for n in range(3)] </s>
<s>[INST] How to break out of multiple loops in Python? Given the following code (that doesn't work): while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied? Edit-FYI: get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns stdin.readline().strip() [/INST] My first instinct would be to refactor the nested loop into a function and use return to break out. </s>
<s>[INST] How to install python3 version of package via pip on Ubuntu? I have both python2.7 and python3.2 installed in Ubuntu 12.04. The symbolic link python links to python2.7. When I type: sudo pip install package-name It will default install python2 version of package-name. Some package supports both python2 and python3. How to install python3 version of package-name via pip? [/INST] Ubuntu 12.10+ and Fedora 13+ have a package called python3-pip which will install pip-3.2 (or pip-3.3, pip-3.4 or pip3 for newer versions) without needing this jumping through hoops. I came across this and fixed this without needing the likes of wget or virtualenvs (assuming Ubuntu 12.04): Install package python3-setuptools: run sudo aptitude install python3-setuptools, this will give you the command easy_install3. Install pip using Python 3's setuptools: run sudo easy_install3 pip, this will give you the command pip-3.2 like kev's solution. Install your PyPI packages: run sudo pip-3.2 install <package> (installing python packages into your base system requires root, of course). … Profit! </s>
<s>[INST] In Matplotlib, what does the argument mean in fig.add_subplot(111)? Sometimes I come across code such as this: import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] fig = plt.figure() fig.add_subplot(111) plt.scatter(x, y) plt.show() Which produces: I've been reading the documentation like crazy but I can't find an explanation for the 111. sometimes I see a 212. What does the argument of fig.add_subplot() mean? [/INST] I think this would be best explained by the following picture: To initialize the above, one would type: import matplotlib.pyplot as plt fig = plt.figure() fig.add_subplot(221) #top left fig.add_subplot(222) #top right fig.add_subplot(223) #bottom left fig.add_subplot(224) #bottom right plt.show() EDIT: Some additional information The following combinations produce asymmetrical arrangements of subplots. subplot(2,2,[1 3]) subplot(2,2,2) subplot(2,2,4) You can also use the colon operator to specify multiple locations if they are in sequence. subplot(2,2,1:2) subplot(2,2,3) subplot(2,2,4) Reference here </s>
<s>[INST] python open built-in function: difference between modes a, a+, w, w+, and r+? In the python built-in open function, what is the exact difference between the modes w, a, w+, a+, and r+? In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean. [/INST] The opening modes are exactly the same that C fopen() std library function. The BSD fopen manpage defines them as follows: The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.): ``r'' Open text file for reading. The stream is positioned at the beginning of the file. ``r+'' Open for reading and writing. The stream is positioned at the beginning of the file. ``w'' Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file. ``w+'' Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. ``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. ``a+'' Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. </s>
<s>[INST] How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? I need a way to tell what mode the shell is in from within the shell. I've tried looking at the platform module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm running on OS X 10.6) so it seems to always report 64bit even though I'm using the methods described here to force 32bit mode). [/INST] UPDATED: One way is to look at sys.maxsize as documented here: $ python-32 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)' ('7fffffff', False) $ python-64 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)' ('7fffffffffffffff', True) sys.maxsize was introduced in Python 2.6. If you need a test for older systems, this slightly more complicated test should work on all Python 2 and 3 releases: $ python-32 -c 'import struct;print( 8 * struct.calcsize("P"))' 32 $ python-64 -c 'import struct;print( 8 * struct.calcsize("P"))' 64 BTW, you might be tempted to use platform.architecture() for this. Unfortunately, its results are not always reliable, particularly in the case of OS X universal binaries. $ arch -x86_64 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32' 64bit True $ arch -i386 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32' 64bit False </s>
<s>[INST] Setting the correct encoding when piping stdout in Python When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this: # -*- coding: utf-8 -*- print u"åäö" will work fine when run normally, but fail with: UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128) when used in a pipe sequence. What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack: # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" Is there a better way to make piping work? [/INST] First, regarding this solution: # -*- coding: utf-8 -*- print u"åäö".encode('utf-8') It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone. A better solution is to change sys.stdout at the start of your program, to encode with a selected encoding. Here is one solution I found on Python: How is sys.stdout.encoding chosen?, in particular a comment by "toka": import sys import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) </s>
<s>[INST] Difference between Python's Generators and Iterators What is the difference between iterators and generators? Some examples for when you would use each case would be helpful. [/INST] iterator is a more general concept: any object whose class has a next method (__next__ in Python 3) and an __iter__ method that does return self. Every generator is an iterator, but not vice versa. A generator is built by calling a function that has one or more yield expressions (yield statements, in Python 2.5 and earlier), and is an object that meets the previous paragraph's definition of an iterator. You may want to use a custom iterator, rather than a generator, when you need a class with somewhat complex state-maintaining behavior, or want to expose other methods besides next (and __iter__ and __init__). Most often, a generator (sometimes, for sufficiently simple needs, a generator expression) is sufficient, and it's simpler to code because state maintenance (within reasonable limits) is basically "done for you" by the frame getting suspended and resumed. For example, a generator such as: def squares(start, stop): for i in xrange(start, stop): yield i * i generator = squares(a, b) or the equivalent generator expression (genexp) generator = (i*i for i in xrange(a, b)) would take more code to build as a custom iterator: class Squares(object): def __init__(self, start, stop): self.start = start self.stop = stop def __iter__(self): return self def next(self): if self.start >= self.stop: raise StopIteration current = self.start * self.start self.start += 1 return current iterator = Squares(a, b) But, of course, with class Squares you could easily offer extra methods, i.e. def current(self): return self.start if you have any actual need for such extra functionality in your application. </s>
<s>[INST] Python: user input and commandline arguments How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line? [/INST] var = raw_input("Please enter something: ") print "you entered", var </s>
<s>[INST] Elegant ways to support equivalence ("equality") in Python classes When writing custom classes it is often important to allow equivalence by means of the == and != operators. In Python, this is made possible by implementing the __eq__ and __ne__ special methods, respectively. The easiest way I've found to do this is the following method: class Foo: def __init__(self, item): self.item = item def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing __dict__s? Note: A bit of clarification--when __eq__ and __ne__ are undefined, you'll find this behavior: >>> a = Foo(1) >>> b = Foo(1) >>> a is b False >>> a == b False That is, a == b evaluates to False because it really runs a is b, a test of identity (i.e., "Is a the same object as b?"). When __eq__ and __ne__ are defined, you'll find this behavior (which is the one we're after): >>> a = Foo(1) >>> b = Foo(1) >>> a is b False >>> a == b True [/INST] You need to be careful with inheritance: >>> class Foo: def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False >>> class Bar(Foo):pass >>> b = Bar() >>> f = Foo() >>> f == b True >>> b == f False Check types more strictly, like this: def __eq__(self, other): if type(other) is type(self): return self.__dict__ == other.__dict__ return False Besides that, your approach will work fine, that's what special methods are there for. </s>
<s>[INST] How to use 'super' in Python? Can someone explain to me the difference between doing: class Child(SomeBaseClass): def __init__(self): super(Child, self).__init__() and this: class Child(SomeBaseClass): def __init__(self): SomeBaseClass.__init__(self) I've seen super being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation. [/INST] The benefits of super() in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods. However, it's almost impossible to use multiple-inheritance without super(). This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child and a mixin, their code would not work properly. </s>
<s>[INST] How do I use raw_input in Python 3 import sys print (sys.platform) print (2 ** 100) raw_input( ) I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1 What should I do to fix this? [/INST] raw_input() was renamed to input() From http://docs.python.org/dev/py3k/whatsnew/3.0.html </s>
<s>[INST] How do you convert a Python time.struct_time object into a datetime object? How do you convert a Python time.struct_time object into a datetime.datetime object? I have a library that provides the first one and a second library that wants the second one... [/INST] Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object. from time import mktime from datetime import datetime dt = datetime.fromtimestamp(mktime(struct)) </s>
<s>[INST] Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup: Python 2.6.1 64bit Django 1.2.1 MySQL 5.1.47 osx10.6 64bit I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syncdb, I get this error: Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager utility.execute() File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 257, in fetch_command klass = load_command_class(app_name, subcommand) File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 67, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/commands/syncdb.py", line 7, in <module> from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/sql.py", line 5, in <module> from django.contrib.contenttypes import generic File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/contrib/contenttypes/generic.py", line 6, in <module> from django.db import connection File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/__init__.py", line 75, in <module> connection = connections[DEFAULT_DB_ALIAS] File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 91, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 32, in load_backend return import_module('.base', backend_name) File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 14, in <module> raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb I've also installed the MySQL for Python adapter, but to no avail (maybe I installed it improperly?). Anyone dealt with this before? [/INST] I had the same error and pip install MySQL-python solved it for me. Alternate installs: If you don't have pip, easy_install MySQL-python should work. If your python is managed by a packaging system, you might have to use that system (e.g. sudo apt-get install ...) Below, Soli notes that if you receive the following error: EnvironmentError: mysql_config not found ... then you have a further system dependency issue. Solving this will vary from system to system, but for Debian-derived systems: sudo apt-get install python-mysqldb </s>
<s>[INST] What is the python "with" statement designed for? I came across the Python with statement for the first time today. I've been using Python lightly for several months and didn't even know of its existence! Given its somewhat obscure status, I thought it would be worth asking: What is the Python with statement designed to be used for? What do you use it for? Are their any gotchas I need to be aware of, or common anti-patterns associated with its use? Any cases where it is better use try..finally than with? Why isn't it used more widely? Which standard library classes are compatible with it? [/INST] I believe this has already been answered by other users before me, so I only add it for the sake of completeness: the with statement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers. More details can be found in PEP 343. For instance, the open statement is a context manager in itself, which lets you open a file, keep it open as long as the execution is in the context of the with statement where you used it, and close it as soon as you leave the context, no matter whether you have left it because of an exception or during regular control flow. The with statement can thus be used in ways similar to the RAII pattern in C++: some resource is acquired by the with statement and released when you leave the with context. Some examples are: opening files using with open(filename) as fp:, acquiring locks using with lock: (where lock is an instance of threading.Lock). You can also construct your own context managers using the contextmanager decorator from contextlib. For instance, I often use this when I have to change the current directory temporarily and then return to where I was: from contextlib import contextmanager import os @contextmanager def working_directory(path): current_dir = os.getcwd() os.chdir(path) try: yield finally: os.chdir(current_dir) with working_directory("data/stuff"): # do something within data/stuff # here I am back again in the original working directory Here's another example that temporarily redirects sys.stdin, sys.stdout and sys.stderr to some other file handle and restores them later: from contextlib import contextmanager import sys @contextmanager def redirected(**kwds): stream_names = ["stdin", "stdout", "stderr"] old_streams = {} try: for sname in stream_names: stream = kwds.get(sname, None) if stream is not None and stream != getattr(sys, sname): old_streams[sname] = getattr(sys, sname) setattr(sys, sname, stream) yield finally: for sname, stream in old_streams.iteritems(): setattr(sys, sname, stream) with redirected(stdout=open("/tmp/log.txt", "w")): # these print statements will go to /tmp/log.txt print "Test entry 1" print "Test entry 2" # back to the normal stdout print "Back to normal stdout again" And finally, another example that creates a temporary folder and cleans it up when leaving the context: from tempfile import mkdtemp from shutil import rmtree @contextmanager def temporary_dir(*args, **kwds): name = mkdtemp(*args, **kwds) try: yield name finally: shutil.rmtree(name) with temporary_dir() as dirname: # do whatever you want </s>
<s>[INST] Python: How to import other Python files How do I import other files in Python? How exactly can I import a specific python file like import file.py? How to import a folder instead of a specific file? I want to load a Python file dynamically in runtime, based on user input. I want to know how to take from the file just one specific part. For example, in main.py I have: from extra import * although this gives me all the file actions of extra.py when maybe all I want is a single definition: def gap(): print print What do I add to the import statement to just get gap from extra.py? [/INST] There are many ways to import a python file, all with their pros and cons. Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs. I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #5 Example 1, Import a python module with python interpreter: Put this in /home/el/foo/fox.py: def what_does_the_fox_say(): print("vixens cry") Get into the python interpreter: el@apollo:/home/el/foo$ python Python 2.7.3 (default, Sep 26 2013, 20:03:06) >>> import fox >>> fox.what_does_the_fox_say() vixens cry >>> You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py. Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place: Put this in /home/el/foo2/mylib.py: def moobar(): print("hi") Put this in /home/el/foo2/main.py: execfile("/home/el/foo2/mylib.py") moobar() run the file: el@apollo:/home/el/foo$ python main.py hi The function moobar was imported from mylib.py and made available in main.py Example 3, Use from ... import ... functionality: Put this in /home/el/foo3/chekov.py: def question(): print "where are the nuclear wessels?" Put this in /home/el/foo3/main.py: from chekov import question question() Run it like this: el@apollo:/home/el/foo3$ python main.py where are the nuclear wessels? If you defined other functions in chekov.py, they would not be available unless you import * Example 4, Import riaa.py if it's in a different file location from where it is imported Put this in /home/el/foo4/stuff/riaa.py: def watchout(): print "my message" Put this in /home/el/foo4/main.py: import sys import os sys.path.append(os.path.abspath("/home/el/foo4/stuff")) from riaa import * watchout() Run it: el@apollo:/home/el/foo4$ python main.py my message That imports everything in the foreign file from a different directory. Example 5, Import files in python with the bare import command: Make a new directory /home/el/foo5/ Make a new directory /home/el/foo5/herp Make an empty file named __init__.py under herp: el@apollo:/home/el/foo5/herp$ touch __init__.py el@apollo:/home/el/foo5/herp$ ls __init__.py Make a new directory /home/el/foo5/herp/derp Under derp, make another __init__.py file: el@apollo:/home/el/foo5/herp/derp$ touch __init__.py el@apollo:/home/el/foo5/herp/derp$ ls __init__.py Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there: def skycake(): print "SkyCake evolves to stay just beyond the cognitive reach of " + "the bulk of men. SKYCAKE!!" The moment of truth, Make the new file /home/el/foo5/main.py, put this in there; from herp.derp.yolo import skycake skycake() Run it: el@apollo:/home/el/foo5$ python main.py SkyCake evolves to stay just beyond the cognitive reach of the bulk of men. SKYCAKE!! The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package. If you want to see my post on how to include ALL .py files under a directory see here: http://stackoverflow.com/a/20753073/445131 Example 6, use os.system("python yourfile.py") import os os.system("python yourfile.py") Bonus protip whether you are using Mac, Linux or Windows, you need to be using python's idle editor as described here. It will unlock your python world. http://www.youtube.com/watch?v=DkW5CSZ_VII </s>
<s>[INST] Does Python's time.time() return the local or UTC timestamp? Does time.time() in the Python time module return the system's time or the time in UTC? [/INST] The time.time() function returns the number of seconds since the epoch as seconds in UTC. Here is some sample output I ran on my computer, converting it to a string as well. Python 2.7.3 (default, Apr 24 2012, 00:00:54) [GCC 4.7.0 20120414 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> ts = time.time() >>> print ts 1355563265.81 >>> import datetime >>> st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') >>> print st 2012-12-15 01:21:05 >>> The ts variable is the time returned in seconds. I then converted it to a string using the datetime library making it a string that is human readable. </s>
<s>[INST] Split string into a list in Python I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that? def split_line(text): # split the text words = text.split() # for each word in the line: for word in words: # print the word print(word) [/INST] Splits the string in text on delimiter: " ". words = text.split() Split the string in text on delimiter: ",". words = text.split(",") The words variable will be a list datatype and contain a list of words from text split on the delimiter. </s>
<s>[INST] What's the proper way to install pip, virtualenv, and distribute for Python? Short Question What is the proper way to install pip, virtualenv, and distribute? Background In my answer to SO question 4314376, I recommended using ez_setup so that you could then install pip and virtualenv as follows: curl -O http://peak.telecommunity.com/dist/ez_setup.py sudo python ez_setup.py sudo easy_install pip sudo pip install virtualenv I originally pulled these instructions from Jesse Noller's blog post So you want to use Python on the Mac?. I like the idea of keeping a clean global site-packages directory, so the only other packages I install there are virtualenvwrapper and distribute. (I recently added distribute to my toolbox because of this Python public service announcement. To install these two packages, I used: sudo pip install virtualenvwrapper curl -O http://python-distribute.org/distribute_setup.py sudo python distribute_setup.py No more setuptools and easy_install To really follow that Python public service announcement, on a fresh Python install, I would do the following: curl -O http://python-distribute.org/distribute_setup.py sudo python distribute_setup.py sudo easy_install pip sudo pip install virtualenv sudo pip install virtualenvwrapper Glyph's Rebuke In a comment to my answer to SO question 4314376, SO user Glyph stated: NO. NEVER EVER do sudo python setup.py install whatever. Write a ~/.pydistutils.cfg that puts your pip installation into ~/.local or something. Especially files named ez_setup.py tend to suck down newer versions of things like setuptools and easy_install, which can potentially break other things on your operating system. Back to the short question So Glyph's response leads me to my original question: What is the proper way to install pip, virtualenv, and distribute? [/INST] You can do this without installing anything into python itself. You don't need sudo or any privileges. You don't need to edit any files. Install virtualenv into a bootstrap virtual environment. Use the that virtual environment to create more. Since virtualenv ships with pip and distribute, you get everything from one install. Download virtualenv: http://pypi.python.org/pypi/virtualenv https://pypi.python.org/packages/source/v/virtualenv/virtualenv-12.0.7.tar.gz (or whatever is the latest version!) Unpack the source tarball Use the unpacked tarball to create a clean virtual environment. This virtual environment will be used to "bootstrap" others. All of your virtual environments will automatically contain pip and distribute. Using pip, install virtualenv into that bootstrap environment. Use that bootstrap environment to create more! Here is an example in bash: # Select current version of virtualenv: VERSION=12.0.7 # Name your first "bootstrap" environment: INITIAL_ENV=bootstrap # Set to whatever python interpreter you want for your first environment: PYTHON=$(which python) URL_BASE=https://pypi.python.org/packages/source/v/virtualenv # --- Real work starts here --- curl -O $URL_BASE/virtualenv-$VERSION.tar.gz tar xzf virtualenv-$VERSION.tar.gz # Create the first "bootstrap" environment. $PYTHON virtualenv-$VERSION/virtualenv.py $INITIAL_ENV # Don't need this anymore. rm -rf virtualenv-$VERSION # Install virtualenv into the environment. $INITIAL_ENV/bin/pip install virtualenv-$VERSION.tar.gz Now you can use your "bootstrap" environment to create more: # Create a second environment from the first: $INITIAL_ENV/bin/virtualenv py-env1 # Create more: $INITIAL_ENV/bin/virtualenv py-env2 Go nuts! Note This assumes you are not using a really old version of virtualenv. Old versions required the flags --no-site-packges (and depending on the version of Python, --distribute). Now you can create your bootstrap environment with just python virtualenv.py path-to-bootstrap or python3 virtualenv.py path-to-bootstrap. </s>
<s>[INST] How to make a Python script standalone executable to run without ANY dependency? I'm building a Python application and don't want to force my clients to install Python and modules. I also want to make my application closed-source. So, is there a way to compile Python scripts to standalone executables? [/INST] You can use py2exe as already answered and use cython to convert your key .py files in .pyc, C compiled files, like .dll in Windows and .so in linux, much harder to revert than common .pyo and .pyc files (and also gain in performance!) </s>
<s>[INST] Why isn't Python very good for functional programming? I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in this question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.) [/INST] The question you reference asks which languages promote both OO and functional programming. Python does not promote functional programming even though it works fairly well. The best argument against functional programming in Python is that imperative/OO use cases are carefully considered by Guido, while functional programming use cases are not. When I write imperative Python, it's one of the prettiest languages I know. When I write functional Python, it becomes as ugly and unpleasant as your average language that doesn't have a BDFL. Which is not to say that it's bad, just that you have to work harder than you would if you switched to a language that promotes functional programming or switched to writing OO Python. Here are the functional things I miss in Python: Pattern matching Tail recursion Large library of list functions Functional dictionary class Automatic currying Concise way to compose functions Lazy lists Simple, powerful expression syntax (Python's simple block syntax prevents Guido from adding it) No pattern matching and no tail recursion mean your basic algorithms have to be written imperatively. Recursion is ugly and slow in Python. A small list library and no functional dictionaries mean that you have to write a lot of stuff yourself. No syntax for currying or composition means that point-free style is about as full of punctuation as explicitly passing arguments. Iterators instead of lazy lists means that you have to know whether you want efficiency or persistence, and to scatter calls to list around if you want persistence. (Iterators are use-once) Python's simple imperative syntax, along with its simple LL1 parser, mean that a better syntax for if-expressions and lambda-expressions is basically impossible. Guido likes it this way, and I think he's right. </s>
<s>[INST] How to empty a list in Python? It seems so "dirty" emptying a list in this way: while len(alist) > 0 : alist.pop() Does a clear way exist to do that? [/INST] This actually removes the contents from the list, not replaces the old label with a new empty list del lst[:] example: lst1 = [1, 2, 3] lst2 = lst1 del lst1[:] print(lst2) For the sake of completeness, slice assignment achieves the same effect: lst[:] = [] and can be used to shrink a part of the list while replacing a part at the same time (but is out of scope of the question). Note that doing lst = [] does not empty the list, just creates a new object and binds it to the variable lst, but the old list will still have the same elements, and effect will be apparent if it had other variable bindings. </s>
<s>[INST] Remove specific characters from a string in python I'm trying to remove specific characters from a string using python. This is the code I'm using right now. Unfortunately it appears to do nothing to the string. for char in line: if char in " ?.!/;:": line.replace(char,'') How do I do this properly? [/INST] Strings in Python are immutable (can't be changed). Because of this, the effect of line.replace(...) is just to create a new string, rather than changing the old one. You need to rebind (assign) it to line in order to have that variable take the new value, with those characters removed. Also, the way you are doing it is going to be kind of slow, relatively. It's also likely to be a bit confusing to experienced pythonators, who will see a doubly-nested structure and think for a moment that something more complicated is going on. Starting in Python 2.6 and newer Python 2.x versions *, you can instead use str.translate, (but read on for Python 3 differences): line = line.translate(None, '!@#$') or regular expression replacement with re.sub import re line = re.sub('[!@#$]', '', line) The characters enclosed in brackets constitute a character class. Any characters in line which are in that class are replaced with the second parameter to sub: an empty string. In Python 3, strings are Unicode. You'll have to translate a little differently. kevpie mentions this in a comment on one of the answers, and it's noted in the documentation for str.translate. When calling the translate method of a Unicode string, you cannot pass the second parameter that we used above. You also can't pass None as the first parameter, or even a translation table from string.maketrans. Instead, you pass a dictionary as the only parameter. This dictionary maps the ordinal values of characters (i.e. the result of calling ord on them) to the ordinal values of the characters which should replace them, or—usefully to us—None to indicate that they should be deleted. So to do the above dance with a Unicode string you would call something like translation_table = dict.fromkeys(map(ord, '!@#$'), None) unicode_line = unicode_line.translate(translation_table) Here dict.fromkeys and map are used to succinctly generate a dictionary containing {ord('!'): None, ord('@'): None, ...} Even simpler, as another answer puts it, create the dictionary in place: unicode_line = unicode_line.translate({ord(c): None for c in '!@#$'}) * for compatibility with earlier Pythons, you can create a "null" translation table to pass in place of None: import string line = line.translate(string.maketrans('', ''), '!@#$') Here string.maketrans is used to create a translation table, which is just a string containing the characters with ordinal values 0 to 255. </s>
<s>[INST] What is memoization and how can I use it in Python? I just started Python and I've got no idea what memoization is and how to use it. Also, may I have a simplified example? [/INST] Memoization effectively refers to remembering ("memoization" -> "memorandum" -> to be remembered) results of method calls based on the method inputs and then returning the remembered result rather than computing the result again. You can think of it as a cache for method results. For further details, see page 387 for the definition in Introduction To Algorithms (3e), Cormen et al. A simple example for computing factorials using memoization in Python would be something like this: factorial_memo = {} def factorial(k): if k < 2: return 1 if k not in factorial_memo: factorial_memo[k] = k * factorial(k-1) return factorial_memo[k] You can get more complicated and encapsulate the memoization process into a class class Memoize: def __init__(self, f): self.f = f self.memo = {} def __call__(self, *args): if not args in self.memo: self.memo[args] = self.f(*args) return self.memo[args] Then: def factorial(k): if k < 2: return 1 return k * factorial(k - 1) factorial = Memoize(factorial) </s>
<s>[INST] How to overcome "datetime.datetime not JSON serializable" in python? I have a basic dict as follows: sample = {} sample['title'] = "String" sample['somedate'] = somedatetimehere When I try to do jsonify(sample) I get: TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable What can I do such that my dictionary sample can overcome the error above? Note: Though it may not be relevant, the dictionaries are generated from the retrieval of records out of mongodb where when I print out str(sample['somedate']), the output is 2012-08-08 21:46:24.862000. [/INST] Building on other answers, a simple solution based on a specific serializer that just converts datetime.datetime objects to strings. from datetime import datetime def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial raise TypeError ("Type not serializable") As seen, the code just checks to find out if object is of class datetime.datetime, and then uses .isoformat() to produce a serialized version of it, according to ISO 8601 format, YYYY-MM-DDTHH:MM:SS (which is easily decoded by JavaScript). If more complex serialized representations are sought, other code could be used instead of str() (see other answers to this question for examples). The code ends by raising an exception, to deal with the case it is called with a non-serializable type which is not datetime. This json_serial function can be used as follows: from datetime import datetime from json import dumps print dumps(datetime.now(), default=json_serial) The details about how the default parameter to json.dumps works can be found in Section Basic Usage of the json module documentation. </s>
<s>[INST] Python Print String To Text File I'm using Python to open a text document: text_file = open("Output.txt", "w") text_file.write("Purchase Amount: " 'TotalAmount') text_file.close() I want to enter the string called "TotalAmount" into the text document. Can someone please let me know how to do this? [/INST] text_file = open("Output.txt", "w") text_file.write("Purchase Amount: %s" % TotalAmount) text_file.close() If you use a context manager, the file is closed automatically for you with open("Output.txt", "w") as text_file: text_file.write("Purchase Amount: %s" % TotalAmount) If you're using Python2.6 or higher, it's preferred to use str.format() with open("Output.txt", "w") as text_file: text_file.write("Purchase Amount: {0}".format(TotalAmount)) For python2.7 and higher you can use {} instead of {0} In Python3, there is an optional file parameter to the print function with open("Output.txt", "w") as text_file: print("Purchase Amount: {}".format(TotalAmount), file=text_file) </s>
<s>[INST] Writing a list to a file with Python Is this the cleanest way to write a list to a file, since writelines() doesn't insert newline characters? file.writelines(["%s\n" % item for item in list]) It seems like there would be a standard way... [/INST] EDIT Adding info from Thomas' comment Don't forget to open the file first thefile = open('test.txt', 'w') I'd use a loop: for item in thelist: thefile.write("%s\n" % item) or: for item in thelist: print>>thefile, item If you're keen on a single function call, at least remove the square brackets [] so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings. </s>
<s>[INST] Python, extract file name from path, no matter what the os/path format Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be? For example, I'd like all of these paths to return me c: a/b/c/ a/b/c \a\b\c \a\b\c\ a\b\c a/b/../../a/b/c/ a/b/../../a/b/c [/INST] Actually, there's a function that returns exactly what you want print os.path.basename(your_path) </s>
<s>[INST] What's the difference between a Python module and a Python package? What's the difference between a Python module and a Python package? See also: What's the difference between "package" and "module" (for other languages) [/INST] Any Python file is a module, its name being the file's base name without the .py extension. A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional __init__.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file. The distinction between module and package seems to hold just at the file system level. When you import a module or a package, the corresponding object created by Python is always of type module. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules. As an example, consider the xml package in the Python standard library: its xml directory contains an __init__.py file and four sub-directories; the sub-directory etree contains an __init__.py file and, among others, an ElementTree.py file. See what happens when you try to interactively import package/modules: >>> import xml >>> type(xml) <type 'module'> >>> xml.etree.ElementTree Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'etree' >>> import xml.etree >>> type(xml.etree) <type 'module'> >>> xml.etree.ElementTree Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'ElementTree' >>> import xml.etree.ElementTree >>> type(xml.etree.ElementTree) <type 'module'> >>> xml.etree.ElementTree.parse <function parse at 0x00B135B0> In Python there also are built-in modules, such as sys, that are written in C, but I don't think you meant to consider those in your question. </s>
<s>[INST] Cannot install Lxml on Mac os x 10.9 I want to install Lxml so I can then install Scrapy. When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error: In file included from src/lxml/lxml.etree.c:314: /private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found #include "libxml/xmlversion.h" ^ 1 error generated. error: command 'cc' failed with exit status 1 I have tried using brew to install libxml2 and libxslt, both installed fine but I still cannot install lxml. Last time I was installing I needed to enable the developer tools on Xcode but since its updated to Xcode 5 it doesnt give me that option anymore. Does anyone know what I need to do? [/INST] You should install or upgrade the commandline tool for xcode. Try this in a terminal: xcode-select --install </s>
<s>[INST] Generator Expressions vs. List Comprehension When should you use generator expressions and when should you use list comprehensions in Python? # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] [/INST] John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work: def gen(): return (something for something in get_some_stuff()) print gen()[:2] # generators don't support indexing or slicing print [5,6] + gen() # generators can't be added to lists Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension. Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code. </s>