text
stringlengths
185
26.5k
<s>[INST] Find out how much memory is being used by an object in Python How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. [/INST] There...
<s>[INST] flask - how do you get a query string from flask Not obvious from the flask documention on how to get the query string. I am new, looked at the docs, could not find! So @app.route('/') @app.route('/data') def data(): query_string=?????? return render_template("data.html") [/INST] from flask impor...
<s>[INST] Get key with the least value from a dictionary If I have a Python dictionary, how do I get the key to the entry which contains the minimum value? I was thinking about something to do with the min() function... Given the input: {320:1, 321:0, 322:3} It would return 321. [/INST] Best: min(d, key=d.get) -- no ...
<s>[INST] Python append dictionary to dictionary I have two existing dictionaries, and I wish to 'append' one of them to the other. By that I mean that the key,values of the other dictionary should be made into the first dictionary. For example: orig = { 'A': 1, 'B': 2, 'C': 3, } extra = { 'D': 4, 'E': ...
<s>[INST] Why does range(start, end) not include end? >>> range(1,11) gives you [1,2,3,4,5,6,7,8,9,10] Why not 1-11? Did they just decide to do it like that at random or does it have some value I am not seeing? [/INST] Because it's more common to call range(0, 10) which returns [0,1,2,3,4,5,6,7,8,9] which contains 1...
<s>[INST] Which is faster in Python: x**.5 or math.sqrt(x)? I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power? UPDATE This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What...
<s>[INST] Test if a variable is a list or tuple In python, what's the best way to test if a variable contains a list or a tuple? (ie. a collection) Is isinstance as evil as suggested here? http://www.canonical.org/~kragen/isinstance/ Update : the most common reason I want to distinguish a list from a string is when I h...
<s>[INST] Installing SciPy and NumPy using pip I'm trying to create required libraries in a package I'm distributing. It requires both the SciPy and NumPy libraries. While developing, I installed both using apt-get install scipy which installed SciPy 0.9.0 and NumPy 1.5.1, and it worked fine. I would like to do the sa...
<s>[INST] Find String index from last in Python I think it might be a silly question but as I'm totally new to Python, i don't know anything about it. I want to find the last position of a target string in given str as a input. For ex. str='hello' and target='l' then it should output 3. How can i do this? [/INST] Use ...
<s>[INST] e.printStackTrace equivalent in python I know that print e {where e is Exception} prints the occurred exception but, I was trying to find the python equivalent of e.printStackTrace() that exactly traces the exception what line it occurred and prints the entire trace of it. Could anyone please tell me the equi...
<s>[INST] Python When I catch an exception, how do I get the type, file, and line number? Catching an exception that would print like this: Traceback (most recent call last): File "c:/tmp.py", line 1, in <module> 4 / 0 ZeroDivisionError: integer division or modulo by zero I want to format it into: ZeroDivisonErr...
<s>[INST] Python3 error: "Import error: No module name urllib2" Here's my code: import urllib2.request response = urllib2.urlopen("http://www.google.com") html = response.read() print(html) Any help? [/INST] As stated in the urllib2 documentation at http://docs.python.org/library/urllib2.html: The urllib2 module ha...
<s>[INST] Why doesn't Python have a sign function? I can't understand why Python doesn't have a sign function. It has an abs builtin (which I consider sign's sister), but no sign. In python 2.6 there is even a copysign function (in math), but no sign. Why bother to write a copysign(x,y) when you could just write a sign...
<s>[INST] Python normal arguments vs. keyword arguments How are "keyword arguments" different from regular arguments? Can't all arguments be passed as name=value instead of using positional syntax? [/INST] there are two related concepts, both called "keyword arguments". On the calling side, which is what other comment...
<s>[INST] Activate a virtualenv via fabric as deploy user I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull. def git_pull(): sudo('su deploy') # here i need to switch...
<s>[INST] datetime.datetime.utcnow() why no tzinfo? datetime.datetime.utcnow() datetime.datetime(2010, 2, 25, 4, 14, 37, 366086) Why does this datetime not have any tz info say its a utc date. [/INST] That means it is timezone naive, so you can't use it with datetime.astimezone you can give it a timezone like this im...
<s>[INST] Is it possible to implement a Python for range loop without an iterator variable? Is is possible to do this; for i in range(some_number): #do something without the i? If you just want to do something x amount of times and don't need the iterator. [/INST] Off the top of my head, no. I think the best you ...
<s>[INST] Adding Python Path on Windows 7 I've been trying to add the Python path to the command line on Windows 7, yet no matter the method I try, nothing seems to work. I've used the set command, I've tried adding it through the Edit Environment variables prompt etc. Further more if I run the set command on the comma...
<s>[INST] Python: How do I format a date in Jinja2? Using Jinja2, how do I format a date field? I know in Python I can simply do this: print car.date_of_manufacture.strftime('%Y-%m-%d') But how do I format the date in Jinja2? Thanks. [/INST] There are two ways to do it. The direct approach would be to simply call (an...
<s>[INST] How do you use the ellipsis slicing syntax in Python? This came up in Hidden features of Python, but I can't see good documentation or examples that explain how the feature works. [/INST] The ellipsis is used to slice higher-dimensional data structures. It's designed to mean at this point, insert as many f...
<s>[INST] Explaining Python's '__enter__' and '__exit__' this is i saw in someone's code: def __enter__(self): return self def __exit__(self, type, value, tb): self.stream.close() from __future__ import with_statement#for python2.5 class a(object): def __enter__(self): print 's...
<s>[INST] Difference between map, applymap and apply methods in Pandas Can you tell me when to use these vectorization methods with basic examples? I see that map is a Series method whereas the rest are DataFrame methods. I got confused about apply and applymap methods though. Why do we have two methods for applying a ...
<s>[INST] What is __main__.py? What is the __main__.py file for, what sort of code should I put into it, and when should I have one? [/INST] Often, a Python program is run by naming a .py file on the command line: $ python my_program.py You can also create a directory or zipfile full of code, and include a __main__.p...
<s>[INST] Use cases for the 'setdefault' dict method The addition of collections.defaultdict in Python 2.5 greatly reduced the need for dict's setdefault method. This question is for our collective education: What is setdefault still useful for, today in Python 2.6/2.7? What popular use cases of setdefault were supers...
<s>[INST] Multiprocessing: How to use Pool.map on a function defined in a class? When I run something like: from multiprocessing import Pool p = Pool(5) def f(x): return x*x p.map(f, [1,2,3]) it works fine. However, putting this as a function of a class: class calculate(object): def run(self): def f...
<s>[INST] Best way to format integer as string with leading zeros? I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python: function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i<($cnt-st...
<s>[INST] Write to UTF-8 file in Python I'm really confused with the codecs.open function. When I do: file = codecs.open("temp", "w", "utf-8") file.write(codecs.BOM_UTF8) file.close() It gives me the error UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) If I do: fi...
<s>[INST] Is it possible only to declare a variable without assigning any value in Python? Is it possible to declare a variable in Python, like so?: var so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why? EDIT: I want to do this for...
<s>[INST] Python Requests throwing up SSLError I'm working on a simple script that involves CAS, jspring security check, redirection, etc. I would like to use Kenneth Reitz's python requests because it's a great piece of work! However, CAS requires getting validated via SSL so I have to get past that step first. I d...
<s>[INST] Lexical closures in Python While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) Note that this example mindfully avoids lamb...
<s>[INST] How To Use The Pass Statement In Python I am in the process of learning Python and I have reached the section about the pass statement. The guide I'm using defines it as being a Null statement that is commonly used as a placeholder. I still don't fully understand what that means though. Can someone show me a...
<s>[INST] How to state in requirements.txt a direct github source I've installed a library using the command pip install git+git://github.com/mozilla/elasticutils.git which installs it directly from a Github repository. This works fine and I want to have that dependency in my requirements.txt. I've looked at other t...
<s>[INST] Bubble Sort Homework In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them. This is my attempt in Python: mylist = [12, 5, 13, 8, 9, 65] def bubble(badList): length = len(badList) - 1...
<s>[INST] Does Python have a built in function for string natural sort? Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort. Natural sort: The order by which files in Windows are sorted. For instance, the following list is naturally sorted (what I want): ['elm0', 'e...
<s>[INST] Django Passing Custom Form Parameters to Formset This was fixed in Django 1.9 with form_kwargs. I have a Django Form that looks like this: class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField(...
<s>[INST] Why does Python print unicode characters when the default encoding is ASCII? From the Python 2.6 shell: >>> import sys >>> print sys.getdefaultencoding() ascii >>> print u'\xe9' é >>> I expected to have either some gibberish or an Error after the print statement, since the "é" character isn't part of ASCI...
<s>[INST] Image library for Python 3 What is python-3 using instead of PIL for manipulating Images? [/INST] The "friendly PIL fork" Pillow works on Python 2 and 3. Check out the Github project for support matrix and so on. </s>
<s>[INST] Ignore python multiple return value Say I have a Python function that returns multiple values in a tuple: def func(): return 1, 2 Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way tha...
<s>[INST] Python datetime to string without microsecond component I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is 2011-11-03 11:07:04 (followed by +00:00, but that's not ger...
<s>[INST] Named colors in matplotlib What named colors are available in matplotlib for use in plots? I can find a list on the matplotlib documentation that claims that these are the only names: b: blue g: green r: red c: cyan m: magenta y: yellow k: black w: white However, I've found that these colors can also be use...
<s>[INST] How to format a floating number to fixed width in Python How do I format a floating number to a fixed width with the following requirements: Leading zero if n < 1 Add trailing decimal zero(s) to fill up fixed width Truncate decimal digits past fixed width Align all decimal points For example: % formatter so...
<s>[INST] Calculate difference in keys contained in two Python dictionaries Suppose I have two Python dictionaries - dictA and dictB. I need to find out if there are any keys which are present in dictB but not in dictA. What is the fastest way to go about it? Should I convert the dictionary keys into a set and then go ...
<s>[INST] Python function global variables? So I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (I am trying to call the global copy of a variable created in a separate function.) x = somevalue de...
<s>[INST] 'too many values to unpack', iterating over a dict. key=>string, value=>list I am getting the 'too many values to unpack' error. Any idea how I can fix this? first_names = ['foo', 'bar'] last_names = ['gravy', 'snowman'] fields = { 'first_names': first_names, 'last_name': last_names, } for f...
<s>[INST] Converting NumPy array into Python List structure? How do I convert a NumPy array to a Python List (for example [[1,2,3],[4,5,6]] ), and do it reasonably fast? [/INST] Use tolist(): import numpy as np >>> np.array([[1,2,3],[4,5,6]]).tolist() [[1, 2, 3], [4, 5, 6]] </s>
<s>[INST] best way to extract subset of key-value pairs from python dictionary object I have a big dictionary object that has several key value pairs (about 16), I am only interested in 3 of them. What is the best way (shortest/efficient/elegant) to achieve that? The best I know is: bigdict = {'a':1,'b':2,....,'z':26} ...
<s>[INST] py2exe - generate single executable file I thought I heard that py2exe was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used? Basically I'm thinking of it giving me a single executable file that does something...
<s>[INST] Project structure for Google App Engine I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is BowlSK. However, as it has grown, and features...
<s>[INST] How can I filter a date of a DateTimeField in Django? I am trying to filter a DateTimeField comparing with a date. I mean: MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time". Is there an ...
<s>[INST] Why does the expression 0 < 0 == 0 return False in Python? Looking into Queue.py in Python 2.6, I found this construct that I found a bit strange: def full(self): """Return True if the queue is full, False otherwise (not reliable!).""" self.mutex.acquire() n = 0 < self.maxsize == self._qsize()...
<s>[INST] How do I write good/correct package __init__.py files My package has the following structure: mobilescouter/ __init__.py #1 mapper/ __init__.py #2 lxml/ __init__.py #3 vehiclemapper.py vehiclefeaturemapper.py vehiclefeaturesetmapper.py ...
<s>[INST] How to get a variable name as a string in Python? I would like to be able to get the name of a variable as a string but I don't know if Python has that much introspection capabilities. Something like: >>> print(my_var.__name__) 'my_var' I want to do that because I have a bunch of vars I'd like to turn into a...
<s>[INST] "Pretty" Continuous Integration for Python This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at.. For example, compared to.. phpUnderControl Jenkins Hudson CruiseControl.rb ..and others, BuildBot looks rather.. archaic I'm currently playing with Hudson, but it is ve...
<s>[INST] Python syntax for "if a or b or c but not all of them" I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.) What's the ideal syntax for something like: if a and (not b or not c) or b and (not a or not c) ...
<s>[INST] pip broke. how to fix DistributionNotFound error? Whenever i try to use pip I get an error. For exampple: $ sudo pip install gevent-websocket Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pkg_resources import load_entry_point File "/usr/lib/python2.7/dist-packages/p...
<s>[INST] Concatenate item in list to strings Is there a simpler way to concatenate string items in list into a single string? Can I use the str.join() function to join items in list? E.g. this is the input ['this','is','a','sentence'] and this is the desired output this-is-a-sentence sentence = ['this','is','a','sente...
<s>[INST] Executing Python script from Django shell I need to execute a Python script from the Django shell. I tried ./manage.py shell << my_script.py But it didn't work. It was just kinda waiting for me to write something. [/INST] The << part is wrong, use < instead: $ ./manage.py shell < myscript.py You could also...
<s>[INST] bash: pip: command not found I downloaded pip and ran python setup.py install and everything worked just fine. The very next step in the tutorial is to run pip install <lib you want> but before it even tries to find anything online I get an error "bash: pip: command not found". This is on Mac OS X, which I'm ...
<s>[INST] Get all object attributes in Python? Is there a way to get all attributes/methods/fields/etc. of an object in Python? vars() is close to what I want, but it doesn't work unless an object has a __dict__, which isn't always true (e.g. it's not true for a list, a dict, etc.). [/INST] Use the built-in function d...
<s>[INST] what is difference between __init__ and __call__ in python? I want to know what is difference between __init__ and __call__ methods? For example : class test: def __init__(self): self.a = 10 def __call__(self): b = 20 [/INST] The first is used to initialise newly created object, and receive...
<s>[INST] How to sort my paws? In my previous question I got an excellent answer that helped me detect where a paw hit a pressure plate, but now I'm struggling to link these results to their corresponding paws: I manually annotated the paws (RF=right front, RH= right hind, LF=left front, LH=left hind). As you can see ...
<s>[INST] Concatenating two lists - difference between '+=' and extend() I've seen there are actually two (maybe more) ways to concatenate lists in Python: One way is to use the extend() method: a = [1, 2] b = [2, 3] b.extend(a) the other to use the plus(+) operator: b += a Now I wonder: Which of those two options is...
<s>[INST] Why is printing to stdout so slow? Can it be sped up? I've always been amazed/frustrated with how long it takes to simply output to the terminal with a print statement. After some recent painfully slow logging I decided to look into it and was quite surprised to find that almost all the time spent is waiting...
<s>[INST] Is there a python equivalent of Ruby's 'rvm'? Q: Do we have anything functionally equivalent in Python to the Ruby version manager 'rvm'? (RVM lets you easily switch completely between different versions of the ruby interpreter and different sets of gems (modules). Everything concerning download-build-insta...
<s>[INST] How to generate dynamic (parametrized) unit tests in python? I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this: import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsa...
<s>[INST] Event system in Python What event system for Python do you use? I'm already aware of pydispatcher, but I was wondering what else can be found, or is commonly used? I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend. [/IN...
<s>[INST] Django FileField with upload_to determined at runtime I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA_ROOT/joe as opposed to having everyone's files go to MEDIA_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks: class Content(...
<s>[INST] How can I convert a Python dictionary to a list of tuples? If I have a dictionary like: { 'a': 1, 'b': 2, 'c': 3 } How can I convert it to this? [ ('a', 1), ('b', 2), ('c', 3) ] And how can I convert it to this? [ (1, 'a'), (2, 'b'), (3, 'c') ] [/INST] >>> d = { 'a': 1, 'b': 2, 'c': 3 } >>> d.items() [('a...
<s>[INST] How to access the local Django webserver from outside world I followed the instructions here to run Django using the built-in webserver and was able to successfully run it using python manage.py runserver. If I access 127.0.0.1:port locally from the webserver, I get the Django page indicating it worked. I re...
<s>[INST] how to access dictionary element in django template? I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object. {% for choice in choices %} {{choice.choice}} - {{votes[choice.id]}} <br /> {% endfor %} it rais...
<s>[INST] Does Python have a package/module management system? Does Python have a package/module management system, similar to how Ruby has rubygems where you can do gem install packagename? On Installing Python Modules, I only see references to python setup.py install, but that requires you to find the package first. ...
<s>[INST] How can I parse a time string containing milliseconds in it with python? I am able to parse strings containing date/time with time.strptime >>> import time >>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S') (2009, 3, 30, 16, 31, 32, 0, 89, -1) How can I parse a time string that contains milliseconds...
<s>[INST] Sorting list based on values from another list? I am a list of strings like this: X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1] What is the shortest way of sorting X using values from Y to get the following output? ["a", "d", "h", "b", "c", "e", "i", ...
<s>[INST] Python idiom to return first item or None I'm sure there's a simpler way of doing this that's just not occurring to me. I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works: my_...
<s>[INST] Django CSRF check failing with an Ajax POST request I could use some help complying with Django's CSRF protection mechanism via my AJAX post. I've followed the directions here: http://docs.djangoproject.com/en/dev/ref/contrib/csrf/ I've copied the AJAX sample code they have on that page exactly: http://docs.d...
<s>[INST] Python: How to "perfectly" override a dict How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase. It would seem that should be some tiny set of primitives I can override to make this work, but all my research and attempts have made it...
<s>[INST] What is getattr() exactly and how do I use it? I was reading about the getattr() function. The problem is that I still can't grasp the idea of its usage. The only thing I understand about getattr() is that getattr(li, "pop") is the same as calling li.pop. I didn't understand when the book mentioned how you us...
<s>[INST] Object of custom type as dictionary key What must I do to use my objects of a custom type as keys in a Python dictionary (where I don't want the "object id" to act as the key) , e.g. class MyThing: def __init__(self,name,location,length): self.name = name self.location = location ...
<s>[INST] Python Linked List What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by '(1 2 3 4 5). Python's lists, [1, 2, 3, 4, 5], and tuples, (1, 2, 3, 4, 5), are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, an...
<s>[INST] Python - Create a list with initial capacity Code like this often happens: l = [] while foo: #baz l.append(bar) #qux This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements. In Java, you can create an...
<s>[INST] What is the difference between Python and IPython? What exactly is the difference between Python and IPython? If I write code in Python, will it run in IPython as is or does it need to be modified? I know IPython is supposed to be an interactive shell for Python, but is that all? Or is there a language called...
<s>[INST] Java "Virtual Machine" vs. Python "Interpreter" parlance? It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? [/INST] A virtual machine is a virtual computing envir...
<s>[INST] How do I install the yaml package for Python? I have a Python program that uses YAML. I attempted to install it on a new server using pip install yaml and it returns the following: $ sudo pip install yaml Downloading/unpacking yaml Could not find any downloads that satisfy the requirement yaml No distribut...
<s>[INST] Truncate Python DateTime What is a classy way to way truncate a python datetime object? In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0. I would like the output to also be a datetime object, not a string. [/INST] I think this is what you're looking for....
<s>[INST] How to pull a random record using Django's ORM? I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. I'm using Django 1.0.2. While first 3 of them are easy to pull u...
<s>[INST] Wrap long lines in Python How do I wrap long lines in Python without sacrificing indentation? For example: def fun(): print '{0} Here is a really long sentence with {1}'.format(3, 5) Suppose this goes over the 79 character recommended limit. The way I read it, here is how to indent it: def fun(): p...
<s>[INST] How to install python modules without root access? I'm taking some university classes and have been given an 'instructional account', which is a school account I can ssh into to do work. I want to run my computationally intensive Numpy, matplotlib, scipy code on that machine, but I cannot install these module...
<s>[INST] json.dumps vs flask.jsonify I am not sure I understand the purpose of flask.jsonify method. I try to make json string from this: data = {"id": str(album.id), "title": album.title} but what I get with json.dumps differs from what I get with flask.jsonify. json.dumps(data): [{"id": "4ea856fd6506ae0db42702dd", ...
<s>[INST] Removing pip's cache? I need to install psycopg2 v2.4.1 specifically. I accidentally did: pip install psycopg2 Instead of: pip install psycopg2==2.4.1 That installs 2.4.4 instead of the earlier version. Now even after I pip uninstall psycopg2 and attempt to reinstall with the correct version, it appears ...
<s>[INST] Using pip behind a proxy I'm trying to use pip behind a proxy at work. I'm not a networking expert so bear with me if this super obvious. One of the answers from this post suggested using CNTLM. I installed and configured it per this other post, but running cntlm.exe -c cntlm.ini -I -M http://google.com gave ...
<s>[INST] What is the reason for performing a double fork when creating a daemon? I'm trying to create a daemon in python. I've found the following question, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found p...
<s>[INST] how to get the return value from a thread in python? How can I access that return value 'foo' from the thread? def foo(bar): print 'hello {0}'.format(bar) return 'foo' from threading import Thread t = Thread(target=foo, args=('world!',)) t.start() x = t.join() print x The one obvious way to do it,...
<s>[INST] In Python, what does it mean if an object is subscriptable or not? Which types of objects fall into the domain of "subscriptable"? [/INST] It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. Th...
<s>[INST] Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)? I want to slice a NumPy nxn array. I want to extract an arbitrary selection of m rows and columns of that array (i.e. without any pattern in the numbers of rows/columns), making it a new, mxm array. For this example let...
<s>[INST] Python dictionary, how to keep keys/values in same order as declared? new to Python and had a question about dictionaries. I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want i...
<s>[INST] Django database query: How to filter objects by date range? I've got a field in one model like class Sample(models.Model): date = fields.DateField(auto_now=False) Now, I need to filter the objects by a data range, for example, all the objects that has date between 1 Jan 2011 to 31 Jan 2011? Thanks for yo...
<s>[INST] Compiling with cython and mingw produces gcc: error: unrecognized command line option '-mno-cygwin' I'm trying to compile a python extension with cython in win 7 64-bit using mingw (64-bit). I'm working with Python 2.6 (Active Python 2.6.6) and with the adequate distutils.cfg file (setting mingw as the compil...
<s>[INST] Abstract methods in Python I am having trouble in using inheritance with Python. While the concept seems too easy for me in Java yet up till now I have been unable to understand in Python which is surprising to me at least. I have a prototype which follow: class Shape(): def __init__(self, shape_name): ...
<s>[INST] Python - merge items of two lists into a list of tuples What's the pythonic way of achieving the following? list_a = [1, 2, 3, 4] list_b = [5, 6, 7, 8] #Need to create a of tuples from list_a and list_b list_c = [(1,5), (2,6), (3,7), (4,8)] Each member of list_c is a tuple, whose first member is from list_...
<s>[INST] How to get indices of N maximum values in a numpy array? Numpy proposes a way to get the index of the maximum value of an array via np.argmax. I would like a similar thing, but returning the indexes of the N maximum values. For instance, if I have an array [1, 3, 2, 4, 5], it function(array, n=3) would retur...