text
stringlengths
185
26.5k
<s>[INST] How do I remove packages installed with Python's easy_install? Python's easy_install makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages. What is the best way of find...
<s>[INST] In Python, how do I determine if an object is iterable? Is there a method like isiterable? The only solution I have found so far is to call hasattr(myObj, '__iter__') But I am not sure how fool-proof this is. [/INST] Checking for __iter__ works on sequence types, but it would fail on e.g. strings. I would ...
<s>[INST] Why do people write #!/usr/bin/env python on the first line of a Python script? It seems to me like the files run the same without that line. [/INST] If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH. The alternative w...
<s>[INST] What's the difference between list and tuples? What's the difference? What are the advantages / disadvantages of tuples / lists? [/INST] Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have dif...
<s>[INST] Import a module from a relative path How do I import a python module given its relative path? For example, if dirFoo contains Foo.py and dirBar, and dirBar contains Bar.py, how do I import Bar.py into Foo.py? Here's a visual representation: dirFoo\ Foo.py dirBar\ Bar.py Foo wishes to include ...
<s>[INST] ASCII value of a character in Python How do I get the ASCII value of a character as an int in Python? [/INST] From here: function ord() would get the int value of the char. And in case you want to convert back after playing with the number, function chr() does the trick. >>> ord('a') 97 >>> chr(97) '...
<s>[INST] What is a mixin, and why are they useful? In "Programming Python", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? Reading between the lines of this example (which I've linked to because it's quite long), I'm presuming it's a case of using mu...
<s>[INST] Convert bytes to a Python string I'm using this code to get standard output from an external program: >>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] The communicate() method returns an array of bytes: >>> command_stdout b'total 0\n-rw-rw-r-- 1 thomas thoma...
<s>[INST] Most elegant way to check if the string is empty in Python? Does Python have something like an empty string variable where you can do?: if myString == string.empty: Regardless what's the most elegant way to check for empty string values? I find hard coding "" every time for checking an empty string not as go...
<s>[INST] How can I do a line break (line continuation) in Python? I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax? For example, adding a bunch of strings, e = 'a' + 'b' + 'c' + 'd' and have it like this: e = 'a' + 'b' + 'c' + 'd' [/INST] What is the ...
<s>[INST] How can I get a list of locally installed Python modules? I would like to get a list of Python modules, which are in my Python installation (UNIX server). How can you get a list of Python modules installed in your computer? [/INST] help('modules') in a Python shell/prompt. </s>
<s>[INST] How to use threading in Python? I am trying to understand threading in Python. I've looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I'm having trouble understanding them. How do you clearly show tasks being divided for multi-threading? [/INST] Here's a ...
<s>[INST] How to remove a key from a python dictionary? When trying to delete a key from a dictionary, I write: if 'key' in myDict: del myDict['key'] Is there a one line way of doing this? [/INST] Use dict.pop(): my_dict.pop('key', None) This will return my_dict[key] if key exists in the dictionary, and None oth...
<s>[INST] How do I check what version of Python is running my script? How can I check what version of the Python Interpreter is interpreting my script? [/INST] This information is available in the sys.version string in the sys module: >>> import sys Human readable: >>> print (sys.version) #parentheses necessary in py...
<s>[INST] How do I parse XML in Python? I have many rows in a database that contains xml and I'm trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like: <foo> <bar> <type foobar="1"/> <type foob...
<s>[INST] How do you change the size of figures drawn with matplotlib? How do you change the size of figure drawn with matplotlib? [/INST] figure tells you the call signature: figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k') So figure(figsize=(1,1)) creates an inch-by-inch image, which will be 8...
<s>[INST] Parsing values from a JSON file in Python I have this JSON in a file: { "maps": [ { "id": "blabla", "iscategorical": "0" }, { "id": "blabla", "iscategorical": "0" } ], "masks": [ "id": "valore" ], "om_p...
<s>[INST] How can I print a literal "{}" characters in python string and also use .format on it? x = " \{ Hello \} {0} " print x.format(42) gives me : Key Error: Hello\\ I want to print the output: {Hello} 42 [/INST] You need to double the {{ and }}: >>> x = " {{ Hello }} {0} " >>> print x.format(42) ' { Hello } 42 '...
<s>[INST] If Python is interpreted, what are .pyc files? I've been given to understand that Python is an interpreted language... However, when I look at my Python source code I see .pyc files, which Windows identifies as "Compiled Python Files". Where do these come in? [/INST] I've been given to understand that Pyt...
<s>[INST] Use different Python version with virtualenv I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python? I compiled Python 2.6.2 and would like to use it with...
<s>[INST] How to import a module given the full path? How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option. [/INST] For Python 3.5+ use: import importlib.util spec = importlib.util.spec_from_file_location("module.name", "/path/to/file...
<s>[INST] Python @property versus getters and setters Here is a pure Python-specific design question: class MyClass(object): ... def get_my_attr(self): ... def set_my_attr(self, value): ... and class MyClass(object): ... @property def my_attr(self): ... @...
<s>[INST] How do I download a file over HTTP using Python? I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes. The text processing that creates/updates the XML file is written in Python. I use wget inside a Win...
<s>[INST] Way to create multiline comments? I have recently started studying Python, but I couldn't find how to implement multi-line comments. Most languages have block comment symbols like /* */ I tried this in Python, but it throws an error, so this probably is not the correct way. Does Python actually have a mul...
<s>[INST] python setup.py uninstall I have installed a python package with python setup.py install. How do I uninstall it? [/INST] You need to remove all files manually, and also undo any other stuff that installation did manually. If you don't know the list of all files, you can reinstall it with the --record option,...
<s>[INST] How do I remove/delete a folder that is not empty with Python? I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: os.remove("/folder_name"). What is the most effective way of removing/deleting a folder/directory that is no...
<s>[INST] Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster? I've been hearing a lot about the PyPy project. They claim it is 6.3 times faster than the CPython interpreter on their site. Whenever we talk about dynamic languages like Python, speed is one of the top issues. To solve this, they say PyPy is...
<s>[INST] Correct way to write line to file in Python I'm used to doing print >>f, "hi there" However, it seems that print >> is getting deprecated. What is the recommended way to do the line above? Update: Regarding all those answers with "\n"...is this universal or Unix-specific? IE, should I be doing "\r\n" on Windo...
<s>[INST] UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128) I'm having problems dealing with unicode characters from text fetched from different web pages (on different sites). I am using BeautifulSoup. The problem is that the error is not always reproducible; i...
<s>[INST] How to get file creation & modification date/times in Python? I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows. What's the best cross-platform way to get file creation & modification date/times in Python? [/INST] You have a couple of ch...
<s>[INST] Installing specific package versions with pip I'm trying to install version 1.2.2 of the MySQL_python adaptor. The current version shown in PyPi is 1.2.3. Is there a way to install the older version? I found an article stating that this should do it: pip install MySQL_python==1.2.2 When installed, however, i...
<s>[INST] What are "named tuples" in Python? Reading the changes in Python 3.1, I found something... unexpected: The sys.version_info tuple is now a named tuple: I never heard about named tuples before, and I thought elements could either be indexed by numbers (like in tuples and lists) or by keys (like in dicts). I ...
<s>[INST] Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell I have taken Problem #12 from Project Euler as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first triangle numb...
<s>[INST] 'has_key()' or 'in'? I wonder what is better to do: d = {'a': 1, 'b': 2} 'a' in d True or: d = {'a': 1, 'b': 2} d.has_key('a') True [/INST] in is definitely more pythonic. In fact has_key() was removed in Python 3.x. </s>
<s>[INST] Why is [] faster than list()? I recently compared the processing speeds of [] and list() and was surprised to discover that [] runs more than three times faster than list(). I ran the same test with {} and dict() and the results were practically identical: [] and {} both took around 0.128sec / million cycles,...
<s>[INST] How to get line count cheaply in Python? I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise? At the moment I do: def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass ...
<s>[INST] null object in Python? How do I refer to the null object in Python? [/INST] In Python, the 'null' object is the singleton None. The best way to check things for "Noneness" is to use the identity operator, is: if foo is None: ... </s>
<s>[INST] Terminating a Python script I am aware of the die() command in PHP which stops a script early. How can I do this in Python? [/INST] import sys sys.exit() details from the sys module documentation: sys.exit([arg]) Exit from Python. This is implemented by raising the SystemExit exception, so cleanup act...
<s>[INST] Differences between distribute, distutils, setuptools and distutils2? The Situation I’m trying to port an open-source library to Python 3. (SymPy, if anyone is wondering.) So, I need to run 2to3 automatically when building for Python 3. To do that, I need to use distribute. Therefore, I need to port the c...
<s>[INST] How to find if directory exists in Python In the os module in Python, is there a way to find if a directory exists, something like: >>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode True/False [/INST] You're looking for os.path.isdir, or os.path.exists if you don't care whether it's...
<s>[INST] pip install mysql-python fails with EnvironmentError: mysql_config not found This is the error I get (mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python Downloading/unpacking mysql-python Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded Running setup.py egg_info for p...
<s>[INST] How can I force division to be floating point in Python? Division keeps rounding down to 0 I have two integer values a and b, but I need their ratio in floating point. I know that a<b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a. How can I force c to be a ...
<s>[INST] Renaming columns in pandas I have a data table using pandas and column labels that I need to edit to replace the original column labels. I'd like to change the column names in a data table A where the original column names are: ['$a', '$b', '$c', '$d', '$e'] to ['a', 'b', 'c', 'd', 'e']. I have the edite...
<s>[INST] Remove items from a list while iterating in Python I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. for tup in somelist: if determine(tup): code_to_remove_tup What should I use in place of code_to_remove_tup? I can't figure out how t...
<s>[INST] Is there a function in Python to print all the current properties and values of an object? So what I'm looking for here is something like PHP's print_r function. This is so I can debug my scripts by seeing what's the state of the object in question. [/INST] You want vars() mixed with pprint: from pprint impo...
<s>[INST] mkdir -p functionality in Python Is there a way to get functionality similar to mkdir -p on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it? [/INST] mkdir -p functionality as f...
<s>[INST] Map two lists into a dictionary in Python Imagine that you have: keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') What is the simplest way to produce the following dictionary ? dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'} This code works, but I'm not really proud of it : dict = {} jun...
<s>[INST] How do you return multiple values in Python? The canonical way to return multiple values in languages that support it is often tupling. Option: Using a tuple Consider this trivial example: def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0,y1,y2) However, this quickly gets problematic as the n...
<s>[INST] Count occurrence of a character in a string What's the simplest way to count the number of occurrences of a character in a string? e.g. count the number of times 'a' appears in 'Mary had a little lamb' [/INST] str.count(sub[, start[, end]]) Return the number of non-overlapping occurrences of substring sub i...
<s>[INST] Delete an element from a dictionary Is there a way to delete an element from a dictionary in Python? I know I can just call .pop on the dictionary, but that returns the element that was removed. What I'm looking for is something returns the dictionary minus the element in question. At present I have a helper...
<s>[INST] Generate random integers between 0 and 9 How can I generate random integer numbers between 0 and 9 (inclusive) in Python? i.e. 0 1 2 3 4 5 6 7 8 9 [/INST] Try: from random import randint print(randint(0,9)) More info: https://docs.python.org/3.1/library/random.html#random.randint </s>
<s>[INST] How to create a constant in Python Is there a way to declare a constant in Python. In Java we can create constant in this manner: public static final String CONST_NAME = "Name"; What is the equivalent of the above Java constant declaration in Python? [/INST] No there is not. You cannot declare a variable or...
<s>[INST] Why does "not(True) in [False, True]" return False? If I do this: >>> False in [False, True] True That returns True. Simply because False is in the list. But if I do: >>> not(True) in [False, True] False That returns False. Whereas not(True) is equal to False: >>> not(True) False Why? [/INST] Operator pre...
<s>[INST] "Large data" work flows using pandas I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons. One day I hope to repla...
<s>[INST] Convert hex string to int in Python How do I convert a hex string to an int in Python? I may have it as "0xffff" or just "ffff". [/INST] Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell: x = int("deadbeef", 16) With the 0x prefix, Python can distinguish hex a...
<s>[INST] How do you remove duplicates from a list in whilst preserving order? Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this: def uniq(input): ...
<s>[INST] Directory listing in Python How do I get a list of all files (and directories) in a given directory in Python? [/INST] This is a way to traverse every file and directory in a directory tree: import os for dirname, dirnames, filenames in os.walk('.'): # print path to all subdirectories first. for sub...
<s>[INST] Checking whether a variable is an integer or not How do I check whether a variable is an integer? [/INST] If you need to do this, do isinstance( <var>, int ) unless you are in Python 2.x in which case you want isinstance( <var>, ( int, long ) ) Do not use type. It is almost never the right answer in Python...
<s>[INST] How do I unload (reload) a Python module? I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this? if foo.py has changed: unimport foo <-- How do I do this? import foo myfoo = foo.Foo() [/INST] You can relo...
<s>[INST] Can someone explain __all__ in Python? I have been using Python more and more, and I keep seeing the variable __all__ set in different __init__.py files. Can someone explain what this does? [/INST] Linked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list of strings definin...
<s>[INST] How do I protect Python code? I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove...
<s>[INST] What is the best project structure for a Python application? Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source c...
<s>[INST] How do I check if a variable exists? I want to check if a variable exists. Now I'm doing something like this: try: myVar except NameError: # Do something. Are there other ways without exceptions? [/INST] To check the existence of a local variable: if 'myVar' in locals(): # myVar exists. To check th...
<s>[INST] Getting the length of an array in Python In Python, is the following the only way to get the number of elements? arr.__len__() If so, why the strange syntax? [/INST] my_list = [1,2,3,4,5] len(my_list) The same works for tuples: my_tuple = (1,2,3,4,5) len(my_tuple) And strings, which are really just arrays...
<s>[INST] Is there any way to kill a Thread in Python? Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.? [/INST] It is generally a bad pattern to kill a thread abruptly, in Python and in any language. Think of the following cases: the thread is holding a critical resourc...
<s>[INST] Behaviour of increment and decrement operators in Python I notice that a pre-increment/decrement operator can be applied on a variable (like ++count). It compiles, but it does not actually change the value of the variable! What is the behavior of the pre-increment/decrement operators (++/--) in Python? Why d...
<s>[INST] Understanding kwargs in Python What are the uses for **kwargs in Python? I know you can do an objects.filter on a table and pass in a **kwargs argument.   Can I also do this for specifying time deltas i.e. timedelta(hours = time1)? How exactly does it work? Is it classes as 'unpacking'? Like a,b=1,2? [/INST...
<s>[INST] How do I find the location of my Python site-packages directory? How do I find the location of my site-packages directory? [/INST] >>> import site; site.getsitepackages() ['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] (or just first item with site.getsitepackages()[0]) </s>
<s>[INST] How can I reverse a list in python? How can I do this in python? array = [0,10,20,40] for (i = array.length() - 1 ;i >= 0; i--) I need to have the elements of an array but from the end to the beginning. [/INST] >>> L = [0,10,20,40] >>> L[::-1] [40, 20, 10, 0] Extended slice syntax is explained well here: h...
<s>[INST] Try/Except in Python: How do you properly ignore Exceptions? When you just want to do a try-except without handling the exception, how do you do it in Python? Is the following the right way to do it? try : shutil.rmtree ( path ) except : pass [/INST] try: doSomething() except: pass or try: d...
<s>[INST] How to pip install packages according to requirements.txt from a local directory? Here is the problem I have a requirements.txt that looks like: BeautifulSoup==3.2.0 Django==1.3 Fabric==1.2.0 Jinja2==2.5.5 PyYAML==3.09 Pygments==1.4 SQLAlchemy==0.7.1 South==0.7.3 amqplib==0.6.1 anyjson==0.3 ... I have a loca...
<s>[INST] What is a clean, pythonic way to have multiple constructors in Python? I can't find a definitive answer for this. AFAIK, you can't have multiple __init__ functions in a Python class. So what is a good way to solve this problem? Suppose I have an class called Cheese with the number_of_holes property. How can ...
<s>[INST] Save plot to image file instead of displaying it using Matplotlib (so it can be used in batch scripts for example) I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from Matplotlib documentation) as a starting point: from pylab import figure, axes, pie, title, show...
<s>[INST] What is the difference between range and xrange functions in Python 2.X? Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about for i in range(0, 20): for i in xrange(0, 20): [/INST] range creates a...
<s>[INST] How to debug in Django, the good way? So, I started learning to code in Python and later Django. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging ...
<s>[INST] Python List Comprehension Vs. Map Is there a reason to prefer using map() over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other? [/INST] map may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but...
<s>[INST] Should you always favor xrange() over range()? Why or why not? [/INST] For performance, especially when you're iterating over a large range, xrange() is usually better. However, there are still a few cases why you might prefer range(): In python 3, range() does what xrange() used to do and xrange() does no...
<s>[INST] How does Python's super() work with multiple inheritance? I'm pretty much new in Python object oriented programming and I have trouble understanding the super() function (new style classes) especially when it comes to multiple inheritance. For example if you have something like: class First(object): def _...
<s>[INST] Python class inherits object Is there any reason for a class declaration to inherit from object? I just found some code that does this and I can't find a good reason why. class MyClass(object): # class code follows... [/INST] Python 3.x: class MyClass(object): = new-style class class MyClass: = new-styl...
<s>[INST] How can I sort a dictionary by key? What would be a nice way to go from {2:3, 1:89, 4:5, 3:0} to {1:89, 2:3, 3:0, 4:5}? I checked some posts but they all use the "sorted" operator that returns tuples. [/INST] Standard Python dictionaries are unordered. Even if you sorted the (key,value) pairs, you wouldn't ...
<s>[INST] Adding a Method to an Existing Object Instance I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in Python, I think this is called Monkey Patching (or in some cases Duck Punching). I understand that it's not always a good decision to do so. But, how might o...
<s>[INST] How do I read a text file into a string variable in Python I use the following code segment to read a file in python with open ("data.txt", "r") as myfile: data=myfile.readlines() input file is LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE and when I print data I get ['LLKKKKKKKK...
<s>[INST] How to install psycopg2 with "pip" on Python? I'm using virtualenv and I need to install "psycopg2". I have done the following: pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160 And I have the following messages: Downloading/unpacking http:...
<s>[INST] differentiate null=True, blank=True in django When we add a database field in django we generally write models.CharField(max_length=100, null=True, blank=True). The same is done with ForeignKey, DecimalField etc. What is the basic difference in having null=True only blank=True only null=True, blank=True in...
<s>[INST] Is there a portable way to get the current username in Python? Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like os.getuid: >>> os.getuid() 42 >>> os.getusername() 'slartibartfast' I googled around and was s...
<s>[INST] Delete column from pandas DataFrame When deleting a column in a DataFrame I use: del df['column_name'] and this works great. Why can't I use: del df.column_name As you can access the column/Series as df.column_name, I expect this to work. [/INST] The best way to do this in pandas is to use drop: df = df.dr...
<s>[INST] How to check file size in python? I am writing a Python script in Windows. I want to do something based on the file size. For example, if the size is greater than 0, I will send an email to somebody, otherwise continue to other things. How do I check the file size? [/INST] Like this (credit http://www.daniw...
<s>[INST] Emulate a do-while loop in Python? I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work: l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" Inste...
<s>[INST] Display number with leading zeros Given: a = 1 b = 10 c = 100 I want to display a leading zero for all numbers with less than 2 digits, i.e.: 01 10 100 [/INST] Here you are: print "%02d" % (1,) Basically % is like printf or sprint. </s>
<s>[INST] Pythonic way to create a long multi-line string I have a very long query. I would like to split it in several lines in python. A way to do it in javascript would be using several sentences and joining them with a + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned ...
<s>[INST] How to install lxml on Ubuntu I'm having difficulty installing lxml with easy_install on Ubuntu 11. When I type $ easy_install lxml I get: Searching for lxml Reading http://pypi.python.org/simple/lxml/ Reading http://codespeak.net/lxml Best match: lxml 2.3 Downloading http://lxml.de/files/lxml-2.3.tgz Process...
<s>[INST] How does the @property decorator work? I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator. This example is from the documentation: ...
<s>[INST] Retrieving python module path I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from. How do I retrieve a module's path in python? [/INST] import a_module print a_module.__file__ Will actually give you the path to the...
<s>[INST] Removing duplicates in lists Pretty much I need to write a program to check if a list has any duplicates and if it does it removes them and returns a new list with the items that werent duplicated/removed. This is what I have but to be honest I do not know what to do. def remove_duplicates(): t = ['a', 'b...
<s>[INST] What is the difference between dict.items() and dict.iteritems()? Are there any applicable differences between dict.items() and dict.iteritems()? From the Python docs: dict.items(): Return a copy of the dictionary’s list of (key, value) pairs. dict.iteritems(): Return an iterator over the dictionary’s (k...
<s>[INST] Python `if x is not None` or `if not x is None`? I've always thought of the if not x is None version to be more clear, but Google's style guide implies (based on this excerpt) that they use if x is not None. Is there any minor performance difference (I'm assuming not), and is there any case where one really d...
<s>[INST] How do I do a not equal in Django queryset filtering? In Django model QuerySets, I see that there is a __gt and __lt for comparitive values, but is there a __ne/!=/<> (not equals?) I want to filter out using a not equals: Example: Model: bool a; int x; I want results = Model.objects.exclude(a=true, x...
<s>[INST] What is the Python 3 equivalent of "python -m SimpleHTTPServer" What is the Python 3 equivalent of python -m SimpleHTTPServer? [/INST] From the docs: The SimpleHTTPServer module has been merged into http.server in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0...
<s>[INST] Why are Python's 'private' methods not actually private? Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: __myPrivateMethod(). How, then, can one explain this >>> class MyClass: ... def myPublicMethod(self): ... ...
<s>[INST] Python __init__ and self what do they do? I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either. What I'm trying to figure out is: In a method: def method(self, blah): def __init__(...