title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Efficient storage of and access to web pages with Python | 1,548,857 | <p>So like many people I want a way to download, index/extract information and store web pages efficiently. My first thought is to use MySQL and simply shove the pages in which would let me use FULLTEXT searches which would let me do ad hoc queries easily (in case I want to see if something exists and extract it/etc.). But of course performance wise I have some concerns especially with large objects/pages and high volumes of data. So that leads me to look at things like <a href="http://couchdb.apache.org/" rel="nofollow">CouchDB</a>/search engines/etc. So to summarize, my basic requirements are:</p>
<ol>
<li>It must be Python compatible (libraries/etc.)</li>
<li>Store meta data (URL, time retrieved, any GET/POST stuff I sent), response code, etc. of the page I requested.</li>
<li>Store a copy of the original web page as sent by the server (might be content, might be 404 search page, etc.).</li>
<li>Extract information from the web page and store it in a database.</li>
<li>Have the ability to do ad hoc queries on the existing corpus of original web pages (for example a new type of information I want to extract, or to see how many of the pages have the string "fizzbuzz" or whatever in them.</li>
<li>And of course it must be open source/Linux compatible, I have no interest in something I can't modify or fiddle with.</li>
</ol>
<p>So I'm thinking several broad options are:</p>
<ol>
<li>Toss everything into MySQL, use FULLTEXT, go nuts, shard the contact if needed.</li>
<li>Toss meta data into MySQL, store the data on the file system or something like CouchDB, write some custom search stuff.</li>
<li>Toss meta data into MySQL, store the data on a file system with a web server (maybe /YYYY/MM/DD/HH/MM/SS/URL/), make sure there is no default index.html/etc specified (directory index each directory in other words) and use some search engine like <a href="http://lucene.apache.org/" rel="nofollow">Lucene</a> or <a href="http://www.sphinxsearch.com/" rel="nofollow">Sphinx</a> index the content and use that to search. Biggest downside I see here is the inefficiency of repeatedly crawling the site.</li>
<li>Other solutions?</li>
</ol>
<p>When answering please include links to any technologies you mention and if possible what programming languages it has libraries for (i.e. if it's Scala only or whatever it's probably not that useful since this is a Python project). If this question has already been asked (I'm sure it must have been) please let me know (I searched, no luck). </p>
| 1 | 2009-10-10T19:29:56Z | 1,548,911 | <p>Why do you think solution (3), the Sphinx-based one, requires "repeatedly crawling the site"? Sphinx can accept and index many different data sources, including MySQL and PostgreSQL "natively" (there are contributed add-ons for other DBs such as Firebird) -- you can keep your HTML docs as columns in your DB if you like (modern PostgreSQL versions should have no trouble with that, and I imagine that MySQL's wouldn't either), just use Sphinx superior indexing and full-text search (including stemming &c). Your metadata all comes from headers, after all (plus the HTTP request body if you want to track requests in which you POSTed data, but not the HTTP response body at any rate).</p>
<p>One important practical consideration: I would recommend standardizing on UTF-8 -- html will come to you in all sorts of weird encodings, but there's no need to get crazy supporting that at search time -- just transcode every text page to UTF-8 upon arrival (from whatever funky encoding it came in), before storing and indexing it, and live happily ever after.</p>
<p>Maybe you could special-case non-textual responses to keep <em>those</em> in files (I can imagine that devoting gigabytes in the DB to storing e.g. videos which can't be body-indexed anyway might not be a good use of resources).</p>
<p>And BTW, Sphinx does come with Python bindings, as you request.</p>
| 2 | 2009-10-10T19:56:50Z | [
"python",
"mysql",
"database"
] |
Generate a string representation of a one-hot encoding | 1,548,984 | <p>In Python, I need to generate a <code>dict</code> that maps a letter to a pre-defined "<a href="http://en.wikipedia.org/wiki/One-hot" rel="nofollow">one-hot</a>" representation of that letter. By way of illustration, the <code>dict</code> should look like this:</p>
<pre><code>{ 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0',
'B': '0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0', # ...
}
</code></pre>
<p>There is one bit (represented as a character) per letter of the alphabet. Hence each string will contain 25 zeros and one 1. The position of the <code>1</code> is determined by the position of the corresponding letter in the alphabet.</p>
<p>I came up with some code that generates this:</p>
<pre><code># Character set is explicitly specified for fine grained control
_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
n = len(_letters)
one_hot = [' '.join(['0']*a + ['1'] + ['0']*b)
for a, b in zip(range(n), range(n-1, -1, -1))]
outputs = dict(zip(_letters, one_hot))
</code></pre>
<p>Is there a more efficient/cleaner/more pythonic way to do the same thing?</p>
| 3 | 2009-10-10T20:22:06Z | 1,548,988 | <p>That seems pretty clear, concise, and Pythonic to me.</p>
| 0 | 2009-10-10T20:23:28Z | [
"python",
"data-generation"
] |
Generate a string representation of a one-hot encoding | 1,548,984 | <p>In Python, I need to generate a <code>dict</code> that maps a letter to a pre-defined "<a href="http://en.wikipedia.org/wiki/One-hot" rel="nofollow">one-hot</a>" representation of that letter. By way of illustration, the <code>dict</code> should look like this:</p>
<pre><code>{ 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0',
'B': '0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0', # ...
}
</code></pre>
<p>There is one bit (represented as a character) per letter of the alphabet. Hence each string will contain 25 zeros and one 1. The position of the <code>1</code> is determined by the position of the corresponding letter in the alphabet.</p>
<p>I came up with some code that generates this:</p>
<pre><code># Character set is explicitly specified for fine grained control
_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
n = len(_letters)
one_hot = [' '.join(['0']*a + ['1'] + ['0']*b)
for a, b in zip(range(n), range(n-1, -1, -1))]
outputs = dict(zip(_letters, one_hot))
</code></pre>
<p>Is there a more efficient/cleaner/more pythonic way to do the same thing?</p>
| 3 | 2009-10-10T20:22:06Z | 1,549,010 | <pre><code>one_hot = [' '.join(['0']*a + ['1'] + ['0']*b)
for a, b in zip(range(n), range(n-1, -1, -1))]
outputs = dict(zip(_letters, one_hot))
</code></pre>
<p>In particular, there's a <em>lot</em> of code packed into these two lines. You might try the <a href="http://www.refactoring.com/catalog/introduceExplainingVariable.html" rel="nofollow">Introduce Explaining Variable</a> refactoring. Or maybe an <a href="http://www.refactoring.com/catalog/extractMethod.html" rel="nofollow">extract method</a>.</p>
<p>Here's one example:</p>
<pre><code>def single_onehot(a, b):
return ' '.join(['0']*a + ['1'] + ['0']*b)
range_zip = zip(range(n), range(n-1, -1, -1))
one_hot = [ single_onehot(a, b) for a, b in range_zip]
outputs = dict(zip(_letters, one_hot))
</code></pre>
<p>Although you might disagree with my naming.</p>
| 1 | 2009-10-10T20:36:44Z | [
"python",
"data-generation"
] |
Generate a string representation of a one-hot encoding | 1,548,984 | <p>In Python, I need to generate a <code>dict</code> that maps a letter to a pre-defined "<a href="http://en.wikipedia.org/wiki/One-hot" rel="nofollow">one-hot</a>" representation of that letter. By way of illustration, the <code>dict</code> should look like this:</p>
<pre><code>{ 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0',
'B': '0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0', # ...
}
</code></pre>
<p>There is one bit (represented as a character) per letter of the alphabet. Hence each string will contain 25 zeros and one 1. The position of the <code>1</code> is determined by the position of the corresponding letter in the alphabet.</p>
<p>I came up with some code that generates this:</p>
<pre><code># Character set is explicitly specified for fine grained control
_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
n = len(_letters)
one_hot = [' '.join(['0']*a + ['1'] + ['0']*b)
for a, b in zip(range(n), range(n-1, -1, -1))]
outputs = dict(zip(_letters, one_hot))
</code></pre>
<p>Is there a more efficient/cleaner/more pythonic way to do the same thing?</p>
| 3 | 2009-10-10T20:22:06Z | 1,549,021 | <p>I find this to be more readable:</p>
<pre><code>from string import ascii_uppercase
one_hot = {}
for i, l in enumerate(ascii_uppercase):
bits = ['0']*26; bits[i] = '1'
one_hot[l] = ' '.join(bits)
</code></pre>
<p>If you need a more general alphabet, just enumerate over a string of the characters, and replace <code>['0']*26</code> with <code>['0']*len(alphabet)</code>.</p>
| 6 | 2009-10-10T20:40:29Z | [
"python",
"data-generation"
] |
Generate a string representation of a one-hot encoding | 1,548,984 | <p>In Python, I need to generate a <code>dict</code> that maps a letter to a pre-defined "<a href="http://en.wikipedia.org/wiki/One-hot" rel="nofollow">one-hot</a>" representation of that letter. By way of illustration, the <code>dict</code> should look like this:</p>
<pre><code>{ 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0',
'B': '0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0', # ...
}
</code></pre>
<p>There is one bit (represented as a character) per letter of the alphabet. Hence each string will contain 25 zeros and one 1. The position of the <code>1</code> is determined by the position of the corresponding letter in the alphabet.</p>
<p>I came up with some code that generates this:</p>
<pre><code># Character set is explicitly specified for fine grained control
_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
n = len(_letters)
one_hot = [' '.join(['0']*a + ['1'] + ['0']*b)
for a, b in zip(range(n), range(n-1, -1, -1))]
outputs = dict(zip(_letters, one_hot))
</code></pre>
<p>Is there a more efficient/cleaner/more pythonic way to do the same thing?</p>
| 3 | 2009-10-10T20:22:06Z | 1,549,091 | <p>In Python 2.5 and up you can use the conditional operator:</p>
<pre><code>from string import ascii_uppercase
one_hot = {}
for i, c in enumerate(ascii_uppercase):
one_hot[c] = ' '.join('1' if j == i else '0' for j in range(26))
</code></pre>
| 2 | 2009-10-10T21:13:39Z | [
"python",
"data-generation"
] |
How to set an nonexistent field in Python ClientForm? | 1,548,996 | <p>I'm using mechanize (which uses clientform) for some web crawling in python and since it doesn't support JS, I want to set a value of an unexistent input in a form (the input is generated by JS). How can I do this?</p>
<p>The error is similar to the one you get if you try to execute</p>
<pre><code>from mechanize import Browser
br = Browser()
page = br.open('http://google.com')
br.select_form(nr = 0)
br['unexistent'] = 'hello'
</code></pre>
| 5 | 2009-10-10T20:29:30Z | 1,549,036 | <p>You need to first add the control to the form, and then <code>fixup</code> the form.</p>
<pre><code>br.form.new_control('text','unexistent',{'value':''})
br.form.fixup()
br['unexistent'] = 'hello'
</code></pre>
<p>This really isn't very well documented, and in the source under <code>fixup()</code> there is the comment:</p>
<pre><code>This method should only be called once, after all controls have been
added to the form.
</code></pre>
<p>However, it doesn't look like it does anything too dangerous. Probably at least add the control first before messing with anything else in the form.</p>
| 14 | 2009-10-10T20:45:03Z | [
"python",
"mechanize",
"clientform"
] |
how to define a widget in a model attribute | 1,549,011 | <p>Simply, I write:</p>
<pre><code># forms.py
class NoteForm(ModelForm):
def __init__(self, *args, **kwargs):
super(NoteForm, self).__init__(*args, **kwargs)
#add attributes to html-field-tag:
self.fields['content'].widget.attrs['rows'] = 3
self.fields['title'].widget.attrs['size'] = 20
class Meta:
model = Note
fields = ('title','content')
</code></pre>
<p>To add or modify some attributes to the HTML tag field.</p>
<p>But in this time, I will have to do it directly in the Note model in models.py</p>
<pre><code>#models.py
class Note(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(max_length=255)
#how to define the fields.widget.attrs here ?????
</code></pre>
<p>Just FYI: Why? Because is going to work as a </p>
<pre><code>NotesFormSet = inlineformset_factory(NoteBook, Note, extra=10)
</code></pre>
<p>To add many Notes when adding/editing a NoteBook</p>
<p>NOTE: It is not django admin</p>
<p>If im not giving you sufficient context, comment plz, any hint is apreciated =')</p>
| 0 | 2009-10-10T20:37:19Z | 1,549,040 | <p>No, you still do it in a form, but you just pass that form as a parameter to <code>inlineformset_factory</code>.</p>
<pre><code>NotesFormSet = inlineformset_factory(NoteBook, Note, extra=10, form=NoteForm)
</code></pre>
| 1 | 2009-10-10T20:47:14Z | [
"python",
"django",
"django-forms"
] |
Sorting a heterogeneous list of objects in Python | 1,549,037 | <p>I have some custom objects and dictionaries that I want to sort. I want to sort both the objects the dictionaries together. I want to sort the objects by an attribute and the dictionaries by a key.</p>
<pre><code>object.name = 'Jack'
d = {'name':'Jill'}
sort_me =[object, d]
</code></pre>
<p>How do I sort this list using the object's name attribute and the dictionary's 'name' key?</p>
| 5 | 2009-10-10T20:45:18Z | 1,549,049 | <p>What you are almost certainly looking for is to use the key= option for sorted(), which provides a function which returns an arbitrary sort key for each element. This function can check the type of its argument and take various actions. For instance:</p>
<pre><code>import types
class obj(object):
def __init__(self, arg):
self.name = arg
def extract_name(obj):
if type(obj) is types.DictType:
return obj['name']
else:
return obj.__dict__['name']
d = { 'name': 'Jill'}
print sorted([obj('Jack'), d], key=extract_name)
</code></pre>
<p>More information can be found on the <a href="http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys" rel="nofollow">Python wiki</a></p>
<p>RichieHindle's suggestion of using isinstance is a good one. And while I was at it I thought it might be nice to support arbitrary element names instead of hardcoding 'name':</p>
<pre><code>def extract_elem_v2(elem_name):
def key_extractor(obj):
dct = obj if isinstance(obj, dict) else obj.__dict__
return dct[elem_name]
return key_extractor
</code></pre>
<p>Which you can use like so:</p>
<pre><code>print sorted(list_of_stuff, key=extract_elem_v2('name'))
</code></pre>
| 8 | 2009-10-10T20:51:57Z | [
"python",
"sorting"
] |
Sorting a heterogeneous list of objects in Python | 1,549,037 | <p>I have some custom objects and dictionaries that I want to sort. I want to sort both the objects the dictionaries together. I want to sort the objects by an attribute and the dictionaries by a key.</p>
<pre><code>object.name = 'Jack'
d = {'name':'Jill'}
sort_me =[object, d]
</code></pre>
<p>How do I sort this list using the object's name attribute and the dictionary's 'name' key?</p>
| 5 | 2009-10-10T20:45:18Z | 1,549,085 | <pre><code>sort_me.sort(key=attr_or_itemgetter('name'))
</code></pre>
<p>Where <code>attr_or_itemgetter()</code>:</p>
<pre><code>class attr_or_itemgetter(object):
def __init__(self, name):
self.name = name
def __call__(self, obj):
try: return getattr(obj, name)
except AttributeError:
return obj[name]
</code></pre>
<p>NOTE: It intentionally doesn't check for dictionary type, therefore <code>attr_or_itemgetter('items')</code> applied to a dictionary will return <code>dict.items</code> method.</p>
| 2 | 2009-10-10T21:09:35Z | [
"python",
"sorting"
] |
Sorting a heterogeneous list of objects in Python | 1,549,037 | <p>I have some custom objects and dictionaries that I want to sort. I want to sort both the objects the dictionaries together. I want to sort the objects by an attribute and the dictionaries by a key.</p>
<pre><code>object.name = 'Jack'
d = {'name':'Jill'}
sort_me =[object, d]
</code></pre>
<p>How do I sort this list using the object's name attribute and the dictionary's 'name' key?</p>
| 5 | 2009-10-10T20:45:18Z | 8,108,722 | <p>This worked for me. Note that <code>sort()</code> does not return the sorted list, but <code>sorted()</code> does, so if you want to pass this to a template, you should use <code>sorted</code> in the parameters, or <code>sort</code> before you pass the list as a parameter.</p>
<pre><code>itemized_action_list = list(chain(detection_point.insertbodyaction_set.all(),
detection_point.insertheaderaction_set.all(),
detection_point.modifybodyaction_set.all(),
detection_point.modifyheaderaction_set.all(),
detection_point.removebodyaction_set.all(),
detection_point.removeheaderaction_set.all(),
detection_point.redirectaction_set.all()))
sorted(itemized_action_list, key=attrgetter('priority'))
</code></pre>
| 1 | 2011-11-13T00:47:25Z | [
"python",
"sorting"
] |
Adding to local namespace in Python? | 1,549,201 | <p>Is there a way in Python to add to the locals name-space by calling a function without explicitly assigning variables locally?</p>
<p>Something like the following for example (which of course doesn't work, because locals() return a copy of the local name-space) where the print statement would print '1'.</p>
<pre><code>def A():
B(locals())
print x
def B(d):
d['x'] = 1
</code></pre>
| 4 | 2009-10-10T22:05:05Z | 1,549,221 | <p>In Python <code>2.*</code>, you can disable the normal optimizations performed by the Python compiler regarding local variable access by starting your function with <code>exec ''</code>; this will make the function very much slower (I just posted, earlier today, an answer showing how the local-variable optimization can easily speed code up by 3 or 4 times), but it will make your desired hack work. I.e., in Python 2.*:</p>
<pre><code>def A():
exec ''
B(locals())
print x
def B(d):
d['x'] = 1
A()
</code></pre>
<p>will emit <code>1</code>, as you desire.</p>
<p>This hack was disabled in Python <code>3.*</code> (where <code>exec</code> is just a function, not a statement nor a keyword any more) -- the compiler now performs the local variable optimization unconditionally, so there is no longer any way to work around it and make such hacks work.</p>
| 4 | 2009-10-10T22:12:26Z | [
"python",
"namespaces",
"class",
"methods"
] |
Adding to local namespace in Python? | 1,549,201 | <p>Is there a way in Python to add to the locals name-space by calling a function without explicitly assigning variables locally?</p>
<p>Something like the following for example (which of course doesn't work, because locals() return a copy of the local name-space) where the print statement would print '1'.</p>
<pre><code>def A():
B(locals())
print x
def B(d):
d['x'] = 1
</code></pre>
| 4 | 2009-10-10T22:05:05Z | 1,550,364 | <p>Seems pretty horrible to rely on a hack like <code>exec ''</code>. What about communicating like this with the global statement, it seems to work:</p>
<pre><code>>>> def outer():
... global x
... b()
... print x
...
>>> def b():
... global x
... x = 2
...
>>> outer()
2
</code></pre>
<p>You could create a namespace for your variables instead:</p>
<pre><code>class Namespace(object):
pass
def A():
names = Namespace()
B(names)
print names.x
def B(d):
d.x = 1
</code></pre>
<p>Then use <code>names.x</code> or <code>getattr(names, "x")</code> to access the attributes.</p>
| 1 | 2009-10-11T10:31:00Z | [
"python",
"namespaces",
"class",
"methods"
] |
Grouping data points into series | 1,549,412 | <p>I have a series of data points (tuples) in a list with a format like:</p>
<pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]
</code></pre>
<p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p>
<p>I need them grouped in lists by their first value in a series. So given an interval of 3, the above list would be broken into:</p>
<pre><code>[['a', 'b', 'a', 'd'], ['c']]
</code></pre>
<p>I wrote the following function, which works fine on small data sets. However, it is inneficient for large inputs. Any tips on how to rewrite/optimize/mininize this so I can process large data sets?</p>
<pre><code>def split_series(points, interval):
series = []
start = points[0][0]
finish = points[-1][0]
marker = start
next = start + interval
while marker <= finish:
series.append([point[1] for point in points if marker <= point[0] < next])
marker = next
next += interval
return series
</code></pre>
| 0 | 2009-10-10T23:53:56Z | 1,549,425 | <p>One way to do it (no promises on speed):</p>
<p>Break your list of tuples into two lists:
<code>[1,2,2,3,4]</code> and <code>['a','b','a','d','c']</code></p>
<p>Since the first list is sorted, you can just keep iterating over it until you get to an element out of the range. Then, you know the indexes of the start and end elements so you can just slice the strings out of second array. Continue until you've got all the intervals.</p>
<p>I'm not sure how efficient that'll be with tradition Python lists, but if your dataset is large enough, you could try using a NumPy array, which will slice really quickly.</p>
| 2 | 2009-10-11T00:02:23Z | [
"python",
"algorithm",
"series"
] |
Grouping data points into series | 1,549,412 | <p>I have a series of data points (tuples) in a list with a format like:</p>
<pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]
</code></pre>
<p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p>
<p>I need them grouped in lists by their first value in a series. So given an interval of 3, the above list would be broken into:</p>
<pre><code>[['a', 'b', 'a', 'd'], ['c']]
</code></pre>
<p>I wrote the following function, which works fine on small data sets. However, it is inneficient for large inputs. Any tips on how to rewrite/optimize/mininize this so I can process large data sets?</p>
<pre><code>def split_series(points, interval):
series = []
start = points[0][0]
finish = points[-1][0]
marker = start
next = start + interval
while marker <= finish:
series.append([point[1] for point in points if marker <= point[0] < next])
marker = next
next += interval
return series
</code></pre>
| 0 | 2009-10-10T23:53:56Z | 1,549,430 | <p>Your code is O(n<sup>2</sup>). Here's an O(n) solution:</p>
<pre><code>def split_series(points, interval):
series = []
current_group = []
marker = points[0][0]
for value, data in points:
if value >= marker + interval:
series.append(current_group)
current_group = []
marker += interval
current_group.append(data)
if current_group:
series.append(current_group)
return series
points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]
print split_series(points, 3) # Prints [['a', 'b', 'a', 'd'], ['c']]
</code></pre>
| 2 | 2009-10-11T00:06:01Z | [
"python",
"algorithm",
"series"
] |
Grouping data points into series | 1,549,412 | <p>I have a series of data points (tuples) in a list with a format like:</p>
<pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]
</code></pre>
<p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p>
<p>I need them grouped in lists by their first value in a series. So given an interval of 3, the above list would be broken into:</p>
<pre><code>[['a', 'b', 'a', 'd'], ['c']]
</code></pre>
<p>I wrote the following function, which works fine on small data sets. However, it is inneficient for large inputs. Any tips on how to rewrite/optimize/mininize this so I can process large data sets?</p>
<pre><code>def split_series(points, interval):
series = []
start = points[0][0]
finish = points[-1][0]
marker = start
next = start + interval
while marker <= finish:
series.append([point[1] for point in points if marker <= point[0] < next])
marker = next
next += interval
return series
</code></pre>
| 0 | 2009-10-10T23:53:56Z | 1,549,441 | <p>From your code, I'm assuming my prior comment is correct. The problem here appears to be that the performance is O(n^2) - you repeat the list comprehension (which iterates all items) multiple times.</p>
<p>I say, use a simple for loop. If the current item belongs in the same group as the previous one, add it to the existing inner list [["a"], ["b"]] -> [["a"], ["b", "c"]]. If it doesn't, add it to a new inner list, perhaps adding empty padding lists first.</p>
| 1 | 2009-10-11T00:11:51Z | [
"python",
"algorithm",
"series"
] |
Grouping data points into series | 1,549,412 | <p>I have a series of data points (tuples) in a list with a format like:</p>
<pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]
</code></pre>
<p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p>
<p>I need them grouped in lists by their first value in a series. So given an interval of 3, the above list would be broken into:</p>
<pre><code>[['a', 'b', 'a', 'd'], ['c']]
</code></pre>
<p>I wrote the following function, which works fine on small data sets. However, it is inneficient for large inputs. Any tips on how to rewrite/optimize/mininize this so I can process large data sets?</p>
<pre><code>def split_series(points, interval):
series = []
start = points[0][0]
finish = points[-1][0]
marker = start
next = start + interval
while marker <= finish:
series.append([point[1] for point in points if marker <= point[0] < next])
marker = next
next += interval
return series
</code></pre>
| 0 | 2009-10-10T23:53:56Z | 1,549,451 | <p>Expanding on Am's answer, use a defaultdict, and floor-divide the key by the interval to break them up correctly.</p>
<pre><code>from collections import defaultdict
def split_series(points, interval):
vals = defaultdict(list)
for key, value in points:
vals[(key-1)//interval].append(value)
return vals.values()
</code></pre>
| 1 | 2009-10-11T00:16:34Z | [
"python",
"algorithm",
"series"
] |
Grouping data points into series | 1,549,412 | <p>I have a series of data points (tuples) in a list with a format like:</p>
<pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]
</code></pre>
<p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p>
<p>I need them grouped in lists by their first value in a series. So given an interval of 3, the above list would be broken into:</p>
<pre><code>[['a', 'b', 'a', 'd'], ['c']]
</code></pre>
<p>I wrote the following function, which works fine on small data sets. However, it is inneficient for large inputs. Any tips on how to rewrite/optimize/mininize this so I can process large data sets?</p>
<pre><code>def split_series(points, interval):
series = []
start = points[0][0]
finish = points[-1][0]
marker = start
next = start + interval
while marker <= finish:
series.append([point[1] for point in points if marker <= point[0] < next])
marker = next
next += interval
return series
</code></pre>
| 0 | 2009-10-10T23:53:56Z | 1,549,466 | <p>For completeness, here's a solution with <code>itertools.groupby</code>, but the dictionary solution will probably be faster (not to mention a lot easier to read).</p>
<pre><code>import itertools
import operator
def split_series(points, interval):
start = points[0][0]
return [[v for k, v in grouper] for group, grouper in
itertools.groupby((((n - start) // interval, val)
for n, val in points), operator.itemgetter(0))]
</code></pre>
<p>Note that the above assumes you've got at least one item in each group, otherwise it'll give different results from your script, i.e.:</p>
<pre><code>>>> split_series([(1, 'a'), (2, 'b'), (6, 'a'), (6, 'd'), (11, 'c')], 3)
[['a', 'b'], ['a', 'd'], ['c']]
</code></pre>
<p>instead of</p>
<pre><code>[['a', 'b'], ['a', 'd'], [], ['c']]
</code></pre>
<p>Here's a fixed-up dictionary solution. At some point the dictionary lookup time will begin to dominate, but maybe it's fast enough for you like this.</p>
<pre><code>from collections import defaultdict
def split_series(points, interval):
offset = points[0][0]
maxval = (points[-1][0] - offset) // interval
vals = defaultdict(list)
for key, value in points:
vals[(key - offset) // interval].append(value)
return [vals[i] for i in xrange(maxval + 1)]
</code></pre>
| 2 | 2009-10-11T00:23:40Z | [
"python",
"algorithm",
"series"
] |
Grouping data points into series | 1,549,412 | <p>I have a series of data points (tuples) in a list with a format like:</p>
<pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]
</code></pre>
<p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p>
<p>I need them grouped in lists by their first value in a series. So given an interval of 3, the above list would be broken into:</p>
<pre><code>[['a', 'b', 'a', 'd'], ['c']]
</code></pre>
<p>I wrote the following function, which works fine on small data sets. However, it is inneficient for large inputs. Any tips on how to rewrite/optimize/mininize this so I can process large data sets?</p>
<pre><code>def split_series(points, interval):
series = []
start = points[0][0]
finish = points[-1][0]
marker = start
next = start + interval
while marker <= finish:
series.append([point[1] for point in points if marker <= point[0] < next])
marker = next
next += interval
return series
</code></pre>
| 0 | 2009-10-10T23:53:56Z | 1,549,467 | <p>How about using iterators for lazy evaluation?</p>
<p>This should be the equivalent of your initial solution:</p>
<pre><code>from itertools import groupby
def split_series(points, interval):
"""
>>> points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]
>>> print list(split_series(points, 3))
[['a', 'b', 'a', 'd'], ['c']]
"""
def interval_key(t):
return (t[0] - points[0][0]) // interval
groups = groupby(points, interval_key)
for group in groups:
yield [v for _, v in group[1]]
</code></pre>
| 0 | 2009-10-11T00:25:13Z | [
"python",
"algorithm",
"series"
] |
Grouping data points into series | 1,549,412 | <p>I have a series of data points (tuples) in a list with a format like:</p>
<pre><code>points = [(1, 'a'), (2, 'b'), (2, 'a'), (3, 'd'), (4, 'c')]
</code></pre>
<p>The first item in each tuple is an integer and they are assured to be sorted. The second value in each tuple is an arbitrary string.</p>
<p>I need them grouped in lists by their first value in a series. So given an interval of 3, the above list would be broken into:</p>
<pre><code>[['a', 'b', 'a', 'd'], ['c']]
</code></pre>
<p>I wrote the following function, which works fine on small data sets. However, it is inneficient for large inputs. Any tips on how to rewrite/optimize/mininize this so I can process large data sets?</p>
<pre><code>def split_series(points, interval):
series = []
start = points[0][0]
finish = points[-1][0]
marker = start
next = start + interval
while marker <= finish:
series.append([point[1] for point in points if marker <= point[0] < next])
marker = next
next += interval
return series
</code></pre>
| 0 | 2009-10-10T23:53:56Z | 1,561,542 | <p>Here's a lazy approach that uses the step behavior of xrange:</p>
<pre><code>def split_series(points, interval):
end_of_chunk = interval
chunk = []
for marker, item in points:
if marker > end_of_chunk:
for end_of_chunk in xrange(end_of_chunk, marker, interval):
yield chunk
chunk = []
end_of_chunk += interval
chunk.append(item)
yield chunk
</code></pre>
| 1 | 2009-10-13T16:57:37Z | [
"python",
"algorithm",
"series"
] |
Separately validating username and password during Django authentication | 1,549,442 | <p>When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:</p>
<ul>
<li>Username was valid, password was invalid</li>
<li>Username was invalid</li>
</ul>
<p>I am thinking that I would like to display the appropriate messages to the user in these 2 cases, rather than a single "username or password was invalid...".</p>
<p>Anyone have any experience with simple ways to do this. The crux of the matter seems to go right to the lowest level - in the django.contrib.auth.backends.ModelBackend class. The authenticate() method of this class, which takes the username and password as arguments, simply returns the User object, if authentication was successful, or None, if authentication failed. Given that this code is at the lowest level (well, lowest level that is above the database code), bypassing it seems like a lot of code is being thrown away.</p>
<p>Is the best way simply to implement a new authentication backend and add it to the AUTHENTICATION_BACKENDS setting? A backend could be implemented that returns a (User, Bool) tuple, where the User object is only None if the username did not exist and the Bool is only True if the password was correct. This, however, would break the contract that the backend has with the django.contrib.auth.authenticate() method (which is <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticate">documented</a> to return the User object on successful authentication and None otherwise).</p>
<p>Maybe, this is all a worry over nothing? Regardless of whether the username or password was incorrect, the user is probably going to have to head on over to the "Lost password" page anyway, so maybe this is all academic. I just can't help feeling, though...</p>
<p>EDIT:</p>
<p>A comment regarding the answer that I have selected:
The answer I have selected is the way to implement this feature. There is another answer, below, that discusses the potential security implications of doing this, which I also considered as the nominated answer. However, the answer I have nominated explains <em>how</em> this feature could be implemented. The security based answer discusses whether one <em>should</em> implement this feature which is, really, a different question.</p>
| 5 | 2009-10-11T00:11:56Z | 1,549,508 | <p>We had to deal with this on a site that used an external membership subscription service. Basically you do</p>
<pre><code>from django.contrib.auth.models import User
try:
user = User.objects.get(username=whatever)
# if you get here the username exists and you can do a normal authentication
except:
pass # no such username
</code></pre>
<p>In our case, if the username didn't exist, then we had to go check an HTPASSWD file that was updated by a Perl script from the external site. If the name existed in the file then we would create the user, set the password, and then do the auth.</p>
| 0 | 2009-10-11T00:49:14Z | [
"python",
"django",
"security",
"authentication"
] |
Separately validating username and password during Django authentication | 1,549,442 | <p>When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:</p>
<ul>
<li>Username was valid, password was invalid</li>
<li>Username was invalid</li>
</ul>
<p>I am thinking that I would like to display the appropriate messages to the user in these 2 cases, rather than a single "username or password was invalid...".</p>
<p>Anyone have any experience with simple ways to do this. The crux of the matter seems to go right to the lowest level - in the django.contrib.auth.backends.ModelBackend class. The authenticate() method of this class, which takes the username and password as arguments, simply returns the User object, if authentication was successful, or None, if authentication failed. Given that this code is at the lowest level (well, lowest level that is above the database code), bypassing it seems like a lot of code is being thrown away.</p>
<p>Is the best way simply to implement a new authentication backend and add it to the AUTHENTICATION_BACKENDS setting? A backend could be implemented that returns a (User, Bool) tuple, where the User object is only None if the username did not exist and the Bool is only True if the password was correct. This, however, would break the contract that the backend has with the django.contrib.auth.authenticate() method (which is <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticate">documented</a> to return the User object on successful authentication and None otherwise).</p>
<p>Maybe, this is all a worry over nothing? Regardless of whether the username or password was incorrect, the user is probably going to have to head on over to the "Lost password" page anyway, so maybe this is all academic. I just can't help feeling, though...</p>
<p>EDIT:</p>
<p>A comment regarding the answer that I have selected:
The answer I have selected is the way to implement this feature. There is another answer, below, that discusses the potential security implications of doing this, which I also considered as the nominated answer. However, the answer I have nominated explains <em>how</em> this feature could be implemented. The security based answer discusses whether one <em>should</em> implement this feature which is, really, a different question.</p>
| 5 | 2009-10-11T00:11:56Z | 1,549,582 | <p>You really don't want to distinguish between these two cases. Otherwise, you are giving a potential hacker a clue as to whether or not a username is valid - a significant help towards gaining a fraudulent login.</p>
| 19 | 2009-10-11T01:29:45Z | [
"python",
"django",
"security",
"authentication"
] |
Separately validating username and password during Django authentication | 1,549,442 | <p>When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:</p>
<ul>
<li>Username was valid, password was invalid</li>
<li>Username was invalid</li>
</ul>
<p>I am thinking that I would like to display the appropriate messages to the user in these 2 cases, rather than a single "username or password was invalid...".</p>
<p>Anyone have any experience with simple ways to do this. The crux of the matter seems to go right to the lowest level - in the django.contrib.auth.backends.ModelBackend class. The authenticate() method of this class, which takes the username and password as arguments, simply returns the User object, if authentication was successful, or None, if authentication failed. Given that this code is at the lowest level (well, lowest level that is above the database code), bypassing it seems like a lot of code is being thrown away.</p>
<p>Is the best way simply to implement a new authentication backend and add it to the AUTHENTICATION_BACKENDS setting? A backend could be implemented that returns a (User, Bool) tuple, where the User object is only None if the username did not exist and the Bool is only True if the password was correct. This, however, would break the contract that the backend has with the django.contrib.auth.authenticate() method (which is <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticate">documented</a> to return the User object on successful authentication and None otherwise).</p>
<p>Maybe, this is all a worry over nothing? Regardless of whether the username or password was incorrect, the user is probably going to have to head on over to the "Lost password" page anyway, so maybe this is all academic. I just can't help feeling, though...</p>
<p>EDIT:</p>
<p>A comment regarding the answer that I have selected:
The answer I have selected is the way to implement this feature. There is another answer, below, that discusses the potential security implications of doing this, which I also considered as the nominated answer. However, the answer I have nominated explains <em>how</em> this feature could be implemented. The security based answer discusses whether one <em>should</em> implement this feature which is, really, a different question.</p>
| 5 | 2009-10-11T00:11:56Z | 1,552,067 | <p>This is not a function of the backend simply the authentication form. Just rewrite the form to display the errors you want for each field. Write a login view that use your new form and make that the default login url. (Actually I just saw in a recent commit of Django you can now pass a custom form to the login view, so this is even easier to accomplish). This should take about 5 minutes of effort. Everything you need is in django.contrib.auth.</p>
<p>To clarify here is the current form:</p>
<pre><code>class AuthenticationForm(forms.Form):
"""
Base class for authenticating users. Extend this to get a form that accepts
username/password logins.
"""
username = forms.CharField(label=_("Username"), max_length=30)
password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
def __init__(self, request=None, *args, **kwargs):
"""
If request is passed in, the form will validate that cookies are
enabled. Note that the request (a HttpRequest object) must have set a
cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
running this validation.
"""
self.request = request
self.user_cache = None
super(AuthenticationForm, self).__init__(*args, **kwargs)
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = authenticate(username=username, password=password)
if self.user_cache is None:
raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
elif not self.user_cache.is_active:
raise forms.ValidationError(_("This account is inactive."))
# TODO: determine whether this should move to its own method.
if self.request:
if not self.request.session.test_cookie_worked():
raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
return self.cleaned_data
def get_user_id(self):
if self.user_cache:
return self.user_cache.id
return None
def get_user(self):
return self.user_cache
</code></pre>
<p>Add:</p>
<pre><code>def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
raise forms.ValidationError("The username you have entered does not exist.")
return username
</code></pre>
| 2 | 2009-10-11T23:23:54Z | [
"python",
"django",
"security",
"authentication"
] |
Separately validating username and password during Django authentication | 1,549,442 | <p>When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:</p>
<ul>
<li>Username was valid, password was invalid</li>
<li>Username was invalid</li>
</ul>
<p>I am thinking that I would like to display the appropriate messages to the user in these 2 cases, rather than a single "username or password was invalid...".</p>
<p>Anyone have any experience with simple ways to do this. The crux of the matter seems to go right to the lowest level - in the django.contrib.auth.backends.ModelBackend class. The authenticate() method of this class, which takes the username and password as arguments, simply returns the User object, if authentication was successful, or None, if authentication failed. Given that this code is at the lowest level (well, lowest level that is above the database code), bypassing it seems like a lot of code is being thrown away.</p>
<p>Is the best way simply to implement a new authentication backend and add it to the AUTHENTICATION_BACKENDS setting? A backend could be implemented that returns a (User, Bool) tuple, where the User object is only None if the username did not exist and the Bool is only True if the password was correct. This, however, would break the contract that the backend has with the django.contrib.auth.authenticate() method (which is <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticate">documented</a> to return the User object on successful authentication and None otherwise).</p>
<p>Maybe, this is all a worry over nothing? Regardless of whether the username or password was incorrect, the user is probably going to have to head on over to the "Lost password" page anyway, so maybe this is all academic. I just can't help feeling, though...</p>
<p>EDIT:</p>
<p>A comment regarding the answer that I have selected:
The answer I have selected is the way to implement this feature. There is another answer, below, that discusses the potential security implications of doing this, which I also considered as the nominated answer. However, the answer I have nominated explains <em>how</em> this feature could be implemented. The security based answer discusses whether one <em>should</em> implement this feature which is, really, a different question.</p>
| 5 | 2009-10-11T00:11:56Z | 1,552,085 | <p>This answer is not specific to Django, but this is the pseudo-code I would use to accomplish this:</p>
<pre><code>//Query if user exists who's username=<username> and password=<password>
//If true
//successful login!
//If false
//Query if user exists who's username=<username>
//If true
//This means the user typed in the wrong password
//If false
//This means the user typed in the wrong username
</code></pre>
| 0 | 2009-10-11T23:33:09Z | [
"python",
"django",
"security",
"authentication"
] |
Separately validating username and password during Django authentication | 1,549,442 | <p>When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:</p>
<ul>
<li>Username was valid, password was invalid</li>
<li>Username was invalid</li>
</ul>
<p>I am thinking that I would like to display the appropriate messages to the user in these 2 cases, rather than a single "username or password was invalid...".</p>
<p>Anyone have any experience with simple ways to do this. The crux of the matter seems to go right to the lowest level - in the django.contrib.auth.backends.ModelBackend class. The authenticate() method of this class, which takes the username and password as arguments, simply returns the User object, if authentication was successful, or None, if authentication failed. Given that this code is at the lowest level (well, lowest level that is above the database code), bypassing it seems like a lot of code is being thrown away.</p>
<p>Is the best way simply to implement a new authentication backend and add it to the AUTHENTICATION_BACKENDS setting? A backend could be implemented that returns a (User, Bool) tuple, where the User object is only None if the username did not exist and the Bool is only True if the password was correct. This, however, would break the contract that the backend has with the django.contrib.auth.authenticate() method (which is <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticate">documented</a> to return the User object on successful authentication and None otherwise).</p>
<p>Maybe, this is all a worry over nothing? Regardless of whether the username or password was incorrect, the user is probably going to have to head on over to the "Lost password" page anyway, so maybe this is all academic. I just can't help feeling, though...</p>
<p>EDIT:</p>
<p>A comment regarding the answer that I have selected:
The answer I have selected is the way to implement this feature. There is another answer, below, that discusses the potential security implications of doing this, which I also considered as the nominated answer. However, the answer I have nominated explains <em>how</em> this feature could be implemented. The security based answer discusses whether one <em>should</em> implement this feature which is, really, a different question.</p>
| 5 | 2009-10-11T00:11:56Z | 3,743,636 | <pre><code>def clean_username(self):
"""
Verifies that the username is available.
"""
username = self.cleaned_data["username"]
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
return username
else:
raise forms.ValidationError(u"""\
This username is already registered,
please choose another one.\
""")
</code></pre>
| 0 | 2010-09-18T21:48:11Z | [
"python",
"django",
"security",
"authentication"
] |
How do do this list manipulation in Python? This is tricky | 1,549,445 | <p>Suppose I have this list:</p>
<pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
</code></pre>
<p>What is the MOST efficient way to turn it into this list?</p>
<pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
</code></pre>
<p>Notice, I grab the first from each. Then the 2nd element from each.
Of course, this function needs to be done with X elements.</p>
<p>I've tried it, but mine has many loops,and I think it's too long and complicated.</p>
<p>Thanks.</p>
| 2 | 2009-10-11T00:13:38Z | 1,549,455 | <pre><code>>>> L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
>>> L2 = []
>>> map(L2.extend, zip(*L1))
>>> L2
[5, 7, 1, 44, 21, 32, 73, 99, 100]
</code></pre>
| 10 | 2009-10-11T00:18:03Z | [
"python",
"list"
] |
How do do this list manipulation in Python? This is tricky | 1,549,445 | <p>Suppose I have this list:</p>
<pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
</code></pre>
<p>What is the MOST efficient way to turn it into this list?</p>
<pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
</code></pre>
<p>Notice, I grab the first from each. Then the 2nd element from each.
Of course, this function needs to be done with X elements.</p>
<p>I've tried it, but mine has many loops,and I think it's too long and complicated.</p>
<p>Thanks.</p>
| 2 | 2009-10-11T00:13:38Z | 1,549,459 | <p>As long as all sublists are the same length:</p>
<pre><code>def flattener(nestedlist):
if not nestedlist: return []
return [ x for i in range(len(nestedlist[0]))
for x in [sublist[i] for sublist in nestedlist]
]
</code></pre>
<p>For example,</p>
<pre><code>print flattener([ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ])
</code></pre>
<p>emits exactly the flat list you desire.</p>
<p>If not all sublist need be the same length, what do you want to happen when some are longer, some shorter...? A precise spec is needed if you need to take such inequality into account.</p>
| 2 | 2009-10-11T00:21:23Z | [
"python",
"list"
] |
How do do this list manipulation in Python? This is tricky | 1,549,445 | <p>Suppose I have this list:</p>
<pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
</code></pre>
<p>What is the MOST efficient way to turn it into this list?</p>
<pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
</code></pre>
<p>Notice, I grab the first from each. Then the 2nd element from each.
Of course, this function needs to be done with X elements.</p>
<p>I've tried it, but mine has many loops,and I think it's too long and complicated.</p>
<p>Thanks.</p>
| 2 | 2009-10-11T00:13:38Z | 1,549,463 | <p>Here is an O^2 solution, it assumes all the inner arrays are of the same length</p>
<pre><code>parent = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
final = []
for i in range(len(parent[0])):
for x in range(len(parent)):
final.append(parent[x][i])
print final # [5, 7, 1, 44, 21, 32, 73, 99, 100]
</code></pre>
| 0 | 2009-10-11T00:22:11Z | [
"python",
"list"
] |
How do do this list manipulation in Python? This is tricky | 1,549,445 | <p>Suppose I have this list:</p>
<pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
</code></pre>
<p>What is the MOST efficient way to turn it into this list?</p>
<pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
</code></pre>
<p>Notice, I grab the first from each. Then the 2nd element from each.
Of course, this function needs to be done with X elements.</p>
<p>I've tried it, but mine has many loops,and I think it's too long and complicated.</p>
<p>Thanks.</p>
| 2 | 2009-10-11T00:13:38Z | 1,549,468 | <p>As long as all the sublists are of the same length:</p>
<pre><code>lst = [[5, 44, 73] , [7, 21, 99], [1, 32, 100]]
list(reduce(lambda l, r: l + r, zip(*lst)))
</code></pre>
<p>Edit: This will work with sublists of different lengths:</p>
<pre><code>lst = [[5, 44, 73, 23] , [7, 21, 99], [1, 32, 100]]
list(filter(lambda p: p is not None, reduce(lambda x, y: x + y, map(None, *lst))))
</code></pre>
| -2 | 2009-10-11T00:25:35Z | [
"python",
"list"
] |
How do do this list manipulation in Python? This is tricky | 1,549,445 | <p>Suppose I have this list:</p>
<pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
</code></pre>
<p>What is the MOST efficient way to turn it into this list?</p>
<pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
</code></pre>
<p>Notice, I grab the first from each. Then the 2nd element from each.
Of course, this function needs to be done with X elements.</p>
<p>I've tried it, but mine has many loops,and I think it's too long and complicated.</p>
<p>Thanks.</p>
| 2 | 2009-10-11T00:13:38Z | 1,549,482 | <pre><code>import itertools
list(itertools.chain(*zip(*L1)))
</code></pre>
<p>If you need lists of varying length:</p>
<pre><code>import itertools
[x for x in itertools.chain(*itertools.izip_longest(*L1)) if x is not None]
</code></pre>
| 8 | 2009-10-11T00:33:01Z | [
"python",
"list"
] |
How do do this list manipulation in Python? This is tricky | 1,549,445 | <p>Suppose I have this list:</p>
<pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
</code></pre>
<p>What is the MOST efficient way to turn it into this list?</p>
<pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
</code></pre>
<p>Notice, I grab the first from each. Then the 2nd element from each.
Of course, this function needs to be done with X elements.</p>
<p>I've tried it, but mine has many loops,and I think it's too long and complicated.</p>
<p>Thanks.</p>
| 2 | 2009-10-11T00:13:38Z | 1,549,489 | <p>A simple list comprehension to the second depth:</p>
<pre><code>>>> L = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
>>> [x for li in zip(*L) for x in li]
[5, 7, 1, 44, 21, 32, 73, 99, 100]
</code></pre>
<p>pretty nice. If the sublists are of uneven length, it is not as elegant to express:</p>
<pre><code>>>> L = [ [5, 44, 73] , [7], [1, 32, 100, 101] ]
>>> [li[idx] for idx in xrange(max(map(len, L))) for li in L if idx < len(li)]
[5, 7, 1, 44, 32, 73, 100, 101]
</code></pre>
<p>These solutions are of complexity O(n), where n is the total number of elements.</p>
| 0 | 2009-10-11T00:37:36Z | [
"python",
"list"
] |
How do do this list manipulation in Python? This is tricky | 1,549,445 | <p>Suppose I have this list:</p>
<pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
</code></pre>
<p>What is the MOST efficient way to turn it into this list?</p>
<pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
</code></pre>
<p>Notice, I grab the first from each. Then the 2nd element from each.
Of course, this function needs to be done with X elements.</p>
<p>I've tried it, but mine has many loops,and I think it's too long and complicated.</p>
<p>Thanks.</p>
| 2 | 2009-10-11T00:13:38Z | 1,549,521 | <p>"One-liner" != "Pythonic"</p>
<p>It is <em>bad</em> form to use a list comprehension just to implement a for loop in one line. Save the list expressions or generator expressions for times when you want the results of the expression. The clearest and most Pythonic to my eye is (for sublists of equal length):</p>
<pre><code>L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
L2 = []
for nextitems in zip(*L1):
L2.extend(nextitems)
</code></pre>
<p>Sure you <em>could</em> write this as:</p>
<pre><code>[ L2.extend(nextitems) for nextitems in zip(*L1) ]
</code></pre>
<p>but this generates a list of <code>[None,None,...]</code> as long as the number of items in each sublist, since <code>extend()</code> returns None. And what are we doing with this list? Nothing, and so it gets discarded immediately. But the reader has to look at this for a bit before realizing that this list is "built" for the purpose of running <code>extend()</code> on each created sublist.</p>
<p>The Pythonicness is given by the use of zip and *L1 to pass the sublists of L as args to zip. List comprehensions are generally regarded as Pythonic too, but when they are used for the purpose of creating a list of things, not as a clever shortcut for a for loop.</p>
| 4 | 2009-10-11T00:56:17Z | [
"python",
"list"
] |
How do do this list manipulation in Python? This is tricky | 1,549,445 | <p>Suppose I have this list:</p>
<pre><code>[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
</code></pre>
<p>What is the MOST efficient way to turn it into this list?</p>
<pre><code>[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
</code></pre>
<p>Notice, I grab the first from each. Then the 2nd element from each.
Of course, this function needs to be done with X elements.</p>
<p>I've tried it, but mine has many loops,and I think it's too long and complicated.</p>
<p>Thanks.</p>
| 2 | 2009-10-11T00:13:38Z | 1,549,616 | <pre><code>>>> L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
>>> L2 = list(sum(zip(*L1), ()))
>>> L2
[5, 7, 1, 44, 21, 32, 73, 99, 100]
</code></pre>
| 1 | 2009-10-11T01:48:35Z | [
"python",
"list"
] |
Remove duplicates in a list while keeping its order (Python) | 1,549,509 | <p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python</a></p>
<pre><code>biglist =
[
{'title':'U2 Band','link':'u2.com'},
{'title':'Live Concert by U2','link':'u2.com'},
{'title':'ABC Station','link':'abc.com'}
]
</code></pre>
<p>In this case, the 2nd element should be removed because a previous "u2.com" element already exists. However, the order should be kept.</p>
| 19 | 2009-10-11T00:49:35Z | 1,549,520 | <p>A super easy way to do this is:</p>
<pre><code>def uniq(a):
if len(a) == 0:
return []
else:
return [a[0]] + uniq([x for x in a if x != a[0]])
</code></pre>
<p>This is not the most efficient way, because:</p>
<ul>
<li>it searches through the whole list for every element in the list, so it's O(n^2)</li>
<li>it's recursive so uses a stack depth equal to the length of the list</li>
</ul>
<p>However, for simple uses (no more than a few hundred items, not performance critical) it is sufficient.</p>
| 0 | 2009-10-11T00:55:38Z | [
"python",
"list"
] |
Remove duplicates in a list while keeping its order (Python) | 1,549,509 | <p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python</a></p>
<pre><code>biglist =
[
{'title':'U2 Band','link':'u2.com'},
{'title':'Live Concert by U2','link':'u2.com'},
{'title':'ABC Station','link':'abc.com'}
]
</code></pre>
<p>In this case, the 2nd element should be removed because a previous "u2.com" element already exists. However, the order should be kept.</p>
| 19 | 2009-10-11T00:49:35Z | 1,549,523 | <p>This page discusses different methods and their speeds:
<a href="http://www.peterbe.com/plog/uniqifiers-benchmark" rel="nofollow">http://www.peterbe.com/plog/uniqifiers-benchmark</a></p>
<p>The recommended* method:</p>
<pre><code>def f5(seq, idfun=None):
# order preserving
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result
f5(biglist,lambda x: x['link'])
</code></pre>
<p>*by that page</p>
| 3 | 2009-10-11T00:56:46Z | [
"python",
"list"
] |
Remove duplicates in a list while keeping its order (Python) | 1,549,509 | <p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python</a></p>
<pre><code>biglist =
[
{'title':'U2 Band','link':'u2.com'},
{'title':'Live Concert by U2','link':'u2.com'},
{'title':'ABC Station','link':'abc.com'}
]
</code></pre>
<p>In this case, the 2nd element should be removed because a previous "u2.com" element already exists. However, the order should be kept.</p>
| 19 | 2009-10-11T00:49:35Z | 1,549,527 | <pre><code>dups = {}
newlist = []
for x in biglist:
if x['link'] not in dups:
newlist.append(x)
dups[x['link']] = None
print newlist
</code></pre>
<p>produces</p>
<pre><code>[{'link': 'u2.com', 'title': 'U2 Band'}, {'link': 'abc.com', 'title': 'ABC Station'}]
</code></pre>
<p>Note that here I used a dictionary. This makes the test <code>not in dups</code> much more efficient than using a list.</p>
| 1 | 2009-10-11T00:59:11Z | [
"python",
"list"
] |
Remove duplicates in a list while keeping its order (Python) | 1,549,509 | <p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python</a></p>
<pre><code>biglist =
[
{'title':'U2 Band','link':'u2.com'},
{'title':'Live Concert by U2','link':'u2.com'},
{'title':'ABC Station','link':'abc.com'}
]
</code></pre>
<p>In this case, the 2nd element should be removed because a previous "u2.com" element already exists. However, the order should be kept.</p>
| 19 | 2009-10-11T00:49:35Z | 1,549,530 | <p>I think using a set should be pretty efficent.</p>
<pre><code>seen_links = set()
for index in len(biglist):
link = biglist[index]['link']
if link in seen_links:
del(biglist[index])
seen_links.add(link)
</code></pre>
<p>I think this should come in at O(nlog(n))</p>
| 0 | 2009-10-11T00:59:49Z | [
"python",
"list"
] |
Remove duplicates in a list while keeping its order (Python) | 1,549,509 | <p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python</a></p>
<pre><code>biglist =
[
{'title':'U2 Band','link':'u2.com'},
{'title':'Live Concert by U2','link':'u2.com'},
{'title':'ABC Station','link':'abc.com'}
]
</code></pre>
<p>In this case, the 2nd element should be removed because a previous "u2.com" element already exists. However, the order should be kept.</p>
| 19 | 2009-10-11T00:49:35Z | 1,549,549 | <p>My answer to your other question, which you completely ignored!, shows you're wrong in claiming that </p>
<blockquote>
<p>The answers of that question did not
keep the "order"</p>
</blockquote>
<ul>
<li>my answer <strong>did</strong> keep order, and it clearly <strong>said</strong> it did. Here it is again, with added emphasis to see if you can just keep ignoring it...:</li>
</ul>
<p>Probably the fastest approach, for a really big list, <strong>if you want to preserve the exact order of the items that remain</strong>, is the following...:</p>
<pre><code>biglist = [
{'title':'U2 Band','link':'u2.com'},
{'title':'ABC Station','link':'abc.com'},
{'title':'Live Concert by U2','link':'u2.com'}
]
known_links = set()
newlist = []
for d in biglist:
link = d['link']
if link in known_links: continue
newlist.append(d)
known_links.add(link)
biglist[:] = newlist
</code></pre>
| 20 | 2009-10-11T01:11:15Z | [
"python",
"list"
] |
Remove duplicates in a list while keeping its order (Python) | 1,549,509 | <p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python</a></p>
<pre><code>biglist =
[
{'title':'U2 Band','link':'u2.com'},
{'title':'Live Concert by U2','link':'u2.com'},
{'title':'ABC Station','link':'abc.com'}
]
</code></pre>
<p>In this case, the 2nd element should be removed because a previous "u2.com" element already exists. However, the order should be kept.</p>
| 19 | 2009-10-11T00:49:35Z | 1,549,550 | <p>Generators are great.</p>
<pre><code>def unique( seq ):
seen = set()
for item in seq:
if item not in seen:
seen.add( item )
yield item
biglist[:] = unique( biglist )
</code></pre>
| 6 | 2009-10-11T01:11:43Z | [
"python",
"list"
] |
Remove duplicates in a list while keeping its order (Python) | 1,549,509 | <p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python</a></p>
<pre><code>biglist =
[
{'title':'U2 Band','link':'u2.com'},
{'title':'Live Concert by U2','link':'u2.com'},
{'title':'ABC Station','link':'abc.com'}
]
</code></pre>
<p>In this case, the 2nd element should be removed because a previous "u2.com" element already exists. However, the order should be kept.</p>
| 19 | 2009-10-11T00:49:35Z | 9,572,193 | <pre><code>list = ['aaa','aba','aaa','aea','baa','aaa','aac','aaa',]
uniq = []
for i in list:
if i not in uniq:
uniq.append(i)
print list
print uniq
</code></pre>
<p>output will be:</p>
<p>['aaa', 'aba', 'aaa', 'aea', 'baa', 'aaa', 'aac', 'aaa']</p>
<p>['aaa', 'aba', 'aea', 'baa', 'aac']</p>
| 1 | 2012-03-05T18:50:55Z | [
"python",
"list"
] |
Remove duplicates in a list while keeping its order (Python) | 1,549,509 | <p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python</a></p>
<pre><code>biglist =
[
{'title':'U2 Band','link':'u2.com'},
{'title':'Live Concert by U2','link':'u2.com'},
{'title':'ABC Station','link':'abc.com'}
]
</code></pre>
<p>In this case, the 2nd element should be removed because a previous "u2.com" element already exists. However, the order should be kept.</p>
| 19 | 2009-10-11T00:49:35Z | 22,520,277 | <p>This is an elegant and compact way, with list comprehension (but not as efficient as with dictionary):</p>
<pre><code>mylist = ['aaa','aba','aaa','aea','baa','aaa','aac','aaa',]
[ v for (i,v) in enumerate(mylist) if v not in mylist[0:i] ]
</code></pre>
<p>And in the context of the answer:</p>
<pre><code>[ v for (i,v) in enumerate(biglist) if v['link'] not in map(lambda d: d['link'], biglist[0:i]) ]
</code></pre>
| 1 | 2014-03-19T23:20:46Z | [
"python",
"list"
] |
Remove duplicates in a list while keeping its order (Python) | 1,549,509 | <p>This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <a href="http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python">http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python</a></p>
<pre><code>biglist =
[
{'title':'U2 Band','link':'u2.com'},
{'title':'Live Concert by U2','link':'u2.com'},
{'title':'ABC Station','link':'abc.com'}
]
</code></pre>
<p>In this case, the 2nd element should be removed because a previous "u2.com" element already exists. However, the order should be kept.</p>
| 19 | 2009-10-11T00:49:35Z | 25,560,184 | <p>use set(), then re-sort using the index of the original list.</p>
<pre><code>>>> mylist = ['c','a','a','b','a','b','c']
>>> sorted(set(mylist), key=lambda x: mylist.index(x))
['c', 'a', 'b']
</code></pre>
| 11 | 2014-08-29T00:59:31Z | [
"python",
"list"
] |
Why does this happen in my template for Django? | 1,549,606 | <p>simple%20minds is displayed when do this:</p>
<p>{{ rec.artist_name }}</p>
<p>How do I remove the %20...and make it spaces?</p>
<p>When I put | safe as a fitler, the error is:</p>
<p>Could not parse the remainder: ' | safe' from 'active.artist_name | safe'</p>
<p>Thanks.</p>
| 0 | 2009-10-11T01:42:40Z | 1,549,618 | <p>I think you're being hit by Django's relatively-new autoescaping. What happens if you do </p>
<pre><code>{{ rec.artist_name | safe }}
</code></pre>
<p>to avid the value being autoescaped?</p>
| 2 | 2009-10-11T01:49:24Z | [
"python",
"django"
] |
Why does this happen in my template for Django? | 1,549,606 | <p>simple%20minds is displayed when do this:</p>
<p>{{ rec.artist_name }}</p>
<p>How do I remove the %20...and make it spaces?</p>
<p>When I put | safe as a fitler, the error is:</p>
<p>Could not parse the remainder: ' | safe' from 'active.artist_name | safe'</p>
<p>Thanks.</p>
| 0 | 2009-10-11T01:42:40Z | 1,549,656 | <p>Try removing the space between the rec.artist_name and the |. So you should have this: </p>
<p><code>{{ rec.artist_name|safe }}</code></p>
<p>That'll fix the autoescaping, but I think the other commentors are correct in saying that you're storing the %20 into the db. So you'll probably have to fix it on that end of things.</p>
| 1 | 2009-10-11T02:09:53Z | [
"python",
"django"
] |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | <pre><code>s = 'the brown fox'
</code></pre>
<p>...do something here...</p>
<p><code>s</code> should be :</p>
<pre><code>'The Brown Fox'
</code></pre>
<p>What's the easiest way to do this?</p>
| 267 | 2009-10-11T02:03:54Z | 1,549,644 | <p>The <a href="http://docs.python.org/library/stdtypes.html#str.title"><code>.title()</code></a> method of a string (either ASCII or Unicode is fine) does this:</p>
<pre><code>>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'
</code></pre>
<p>However, look out for strings with embedded apostrophes, as noted in the docs.</p>
<blockquote>
<p>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:</p>
<pre><code>>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
</code></pre>
</blockquote>
| 436 | 2009-10-11T02:04:35Z | [
"python",
"capitalization",
"capitalize"
] |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | <pre><code>s = 'the brown fox'
</code></pre>
<p>...do something here...</p>
<p><code>s</code> should be :</p>
<pre><code>'The Brown Fox'
</code></pre>
<p>What's the easiest way to do this?</p>
| 267 | 2009-10-11T02:03:54Z | 1,549,983 | <p>Just because this sort of thing is fun for me, here are two more solutions.</p>
<p>Split into words, initial-cap each word from the split groups, and rejoin. This will change the white space separating the words into a single white space, no matter what it was.</p>
<pre><code>s = 'the brown fox'
lst = [word[0].upper() + word[1:] for word in s.split()]
s = " ".join(lst)
</code></pre>
<hr>
<p>EDIT: I don't remember what I was thinking back when I wrote the above code, but there is no need to build an explicit list; we can use a generator expression to do it in lazy fashion. So here is a better solution:</p>
<pre><code>s = 'the brown fox'
s = ' '.join(word[0].upper() + word[1:] for word in s.split())
</code></pre>
<hr>
<p>Use a regular expression to match the beginning of the string, or white space separating words, plus a single non-whitespace character; use parentheses to mark "match groups". Write a function that takes a match object, and returns the white space match group unchanged and the non-whitespace character match group in upper case. Then use <code>re.sub()</code> to replace the patterns. This one does not have the punctuation problems of the first solution, nor does it redo the white space like my first solution. This one produces the best result.</p>
<pre><code>import re
s = 'the brown fox'
def repl_func(m):
"""process regular expression match groups for word upper-casing problem"""
return m.group(1) + m.group(2).upper()
s = re.sub("(^|\s)(\S)", repl_func, s)
>>> re.sub("(^|\s)(\S)", repl_func, s)
"They're Bill's Friends From The UK"
</code></pre>
<p>I'm glad I researched this answer. I had no idea that <code>re.sub()</code> could take a function! You can do nontrivial processing inside <code>re.sub()</code> to produce the final result!</p>
| 62 | 2009-10-11T06:04:11Z | [
"python",
"capitalization",
"capitalize"
] |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | <pre><code>s = 'the brown fox'
</code></pre>
<p>...do something here...</p>
<p><code>s</code> should be :</p>
<pre><code>'The Brown Fox'
</code></pre>
<p>What's the easiest way to do this?</p>
| 267 | 2009-10-11T02:03:54Z | 1,549,985 | <p>If str.title() doesn't work for you, do the capitalization yourself.</p>
<ol>
<li>Split the string into a list of words</li>
<li>Capitalize the first letter of each word</li>
<li>Join the words into a single string</li>
</ol>
<p>One-liner:</p>
<pre><code>>>> ' '.join([s[0].upper() + s[1:] for s in "they're bill's friends from the UK".split(' ')])
"They're Bill's Friends From The UK"
</code></pre>
<p>Clear example:</p>
<pre><code>input = "they're bill's friends from the UK"
words = input.split(' ')
capitalized_words = []
for word in words:
title_case_word = word[0].upper() + word[1:]
capitalized_words.append(title_case_word)
output = ' '.join(capitalized_words)
</code></pre>
| 6 | 2009-10-11T06:05:41Z | [
"python",
"capitalization",
"capitalize"
] |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | <pre><code>s = 'the brown fox'
</code></pre>
<p>...do something here...</p>
<p><code>s</code> should be :</p>
<pre><code>'The Brown Fox'
</code></pre>
<p>What's the easiest way to do this?</p>
| 267 | 2009-10-11T02:03:54Z | 10,013,565 | <p>Copy-paste-ready version of @jibberia anwser:</p>
<pre><code>def capitalize(line):
return ' '.join(s[0].upper() + s[1:] for s in line.split(' '))
</code></pre>
| 10 | 2012-04-04T14:47:11Z | [
"python",
"capitalization",
"capitalize"
] |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | <pre><code>s = 'the brown fox'
</code></pre>
<p>...do something here...</p>
<p><code>s</code> should be :</p>
<pre><code>'The Brown Fox'
</code></pre>
<p>What's the easiest way to do this?</p>
| 267 | 2009-10-11T02:03:54Z | 12,336,911 | <p>the 'title' method can't work well, </p>
<pre><code>>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
</code></pre>
<p>Try string.capwords, </p>
<pre><code>import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"
</code></pre>
<p>From the <a href="https://docs.python.org/2/library/string.html#string.capwords">python docs on capwords</a>:</p>
<blockquote>
<p>Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.</p>
</blockquote>
| 90 | 2012-09-09T06:03:36Z | [
"python",
"capitalization",
"capitalize"
] |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | <pre><code>s = 'the brown fox'
</code></pre>
<p>...do something here...</p>
<p><code>s</code> should be :</p>
<pre><code>'The Brown Fox'
</code></pre>
<p>What's the easiest way to do this?</p>
| 267 | 2009-10-11T02:03:54Z | 19,894,900 | <p>I really like this answer:</p>
<blockquote>
<p>Copy-paste-ready version of @jibberia anwser:</p>
<p>def capitalize(line):
return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])</p>
</blockquote>
<p>But some of the lines that I was sending split off some blank '' characters that caused errors when trying to do s[1:]. There is probably a better way to do this, but I had to add in a if len(s)>0, as in</p>
<pre><code>return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0])
</code></pre>
| -2 | 2013-11-10T20:39:10Z | [
"python",
"capitalization",
"capitalize"
] |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | <pre><code>s = 'the brown fox'
</code></pre>
<p>...do something here...</p>
<p><code>s</code> should be :</p>
<pre><code>'The Brown Fox'
</code></pre>
<p>What's the easiest way to do this?</p>
| 267 | 2009-10-11T02:03:54Z | 21,432,975 | <p>Capitalize words...</p>
<pre>
str = "this is string example.... wow!!!";
print "str.title() : ", str.title();
</pre>
| 1 | 2014-01-29T13:47:58Z | [
"python",
"capitalization",
"capitalize"
] |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | <pre><code>s = 'the brown fox'
</code></pre>
<p>...do something here...</p>
<p><code>s</code> should be :</p>
<pre><code>'The Brown Fox'
</code></pre>
<p>What's the easiest way to do this?</p>
| 267 | 2009-10-11T02:03:54Z | 22,437,210 | <p>As Mark pointed out you should use <a href="http://docs.python.org/2/library/stdtypes.html#str.title" rel="nofollow"><code>.title()</code></a>:</p>
<pre><code>"MyAwesomeString".title()
</code></pre>
<p>However, if would like to make the first letter uppercase <strong>inside a django template</strong>, you could use this:</p>
<pre><code>{{ "MyAwesomeString"|title }}
</code></pre>
<p>or using a variable:</p>
<pre><code>{{ myvar|title }}
</code></pre>
| -1 | 2014-03-16T13:04:49Z | [
"python",
"capitalization",
"capitalize"
] |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | <pre><code>s = 'the brown fox'
</code></pre>
<p>...do something here...</p>
<p><code>s</code> should be :</p>
<pre><code>'The Brown Fox'
</code></pre>
<p>What's the easiest way to do this?</p>
| 267 | 2009-10-11T02:03:54Z | 25,566,187 | <p>Why do you complicate your life with joins and for loops when the solution is simple and safe??</p>
<p>Just do this:</p>
<pre><code>string = "the brown fox"
string[0].upper()+string[1:]
</code></pre>
| 5 | 2014-08-29T10:13:46Z | [
"python",
"capitalization",
"capitalize"
] |
Regex From .NET to Python | 1,549,716 | <p>I have a regular expression which works perfectly well (although I am sure it is weak) in .NET/C#:</p>
<pre><code>((^|\s))(?<tag>\@(?<tagname>(\w|\+)+))(?($|\s|\.))
</code></pre>
<p>I am trying to move it over to Python, but I seem to be running into a formatting issue (invalid expression exception).</p>
<p>It is a lame question/request, but I have been staring at this for a while, but nothing obvious is jumping out at me.</p>
<p>Note: I am simply trying </p>
<pre><code>r = re.compile('((^|\s))(?<tag>\@(?<tagname>(\w|\+)+))(?($|\s|\.))')
</code></pre>
<p>Thanks,
Scott</p>
| 0 | 2009-10-11T02:58:35Z | 1,549,730 | <p>Is "(?" there to prevent creation of a separate group? In Python's re's, this is "(:?". Try this:</p>
<pre><code>r = re.compile(r'((^|\s))(:?<tag>\@(:?<tagname>(\w|\+)+))(:?($|\s|\.))')
</code></pre>
<p>Also, note the use of a raw string literal (the "r" character just before the quotes). Raw literals suppress <code>'\'</code> escaping, so that your <code>'\'</code> characters pass straight through to re (otherwise, you'd need <code>'\\'</code> for every <code>'\'</code>).</p>
| -1 | 2009-10-11T03:03:21Z | [
"python",
"regex"
] |
Regex From .NET to Python | 1,549,716 | <p>I have a regular expression which works perfectly well (although I am sure it is weak) in .NET/C#:</p>
<pre><code>((^|\s))(?<tag>\@(?<tagname>(\w|\+)+))(?($|\s|\.))
</code></pre>
<p>I am trying to move it over to Python, but I seem to be running into a formatting issue (invalid expression exception).</p>
<p>It is a lame question/request, but I have been staring at this for a while, but nothing obvious is jumping out at me.</p>
<p>Note: I am simply trying </p>
<pre><code>r = re.compile('((^|\s))(?<tag>\@(?<tagname>(\w|\+)+))(?($|\s|\.))')
</code></pre>
<p>Thanks,
Scott</p>
| 0 | 2009-10-11T02:58:35Z | 1,549,737 | <p>There are some syntax incompatibilities between .NET regexps and PCRE/Python regexps :</p>
<ul>
<li><code>(?<name>...)</code> is <code>(?P<name>...)</code></li>
<li><code>(?...)</code> does not exist, and as I don't know what it is used for in .NET I can't guess any equivalent. A Google codesearch do not give me any pointer to what it could be used for.</li>
</ul>
<p>Besides, you should use Python raw strings (<code>r"I am a raw string"</code>) instead of normal strings when expressing regexps : raw strings do not interpret escape sequences (like <code>\n</code>). But it is not the problem in your example as you're not using any known escape sequence which could be replaced (<code>\s</code> does not mean anything as an escape sequence, so it is not replaced).</p>
| 1 | 2009-10-11T03:06:55Z | [
"python",
"regex"
] |
Difference between defining a member in __init__ to defining it in the class body in python? | 1,549,722 | <p>What is the difference between doing</p>
<pre><code>class a:
def __init__(self):
self.val=1
</code></pre>
<p>to doing</p>
<pre><code>class a:
val=1
def __init__(self):
pass
</code></pre>
| 6 | 2009-10-11T03:00:40Z | 1,549,749 | <pre><code>class a:
def __init__(self):
self.val=1
</code></pre>
<p>this creates a class (in Py2, a cruddy, legacy, old-style, <strong>don't do that!</strong> class; in Py3, the nasty old legacy classes have finally gone away so this would be a class of the one and only kind -- the *<em>good</em> kind, which requires <code>class a(object):</code> in Py2) such that each instance starts out with its own reference to the integer object <code>1</code>.</p>
<pre><code>class a:
val=1
def __init__(self):
pass
</code></pre>
<p>this creates a class (of the same kind) which itself has a reference to the integer object <code>1</code> (its instances start out with no per-instance reference).</p>
<p>For immutables like <code>int</code> values, it's hard to see a practical difference. For example, in either case, if you later do <code>self.val = 2</code> on one instance of <code>a</code>, this will make an <em>instance</em> reference (the existing answer is badly wrong in this respect).</p>
<p>The distinction is important for <em>mutable</em> objects, because they have mutator methods, so it's pretty crucial to know if a certain list is unique per-instance or shared among all instances. But for <em>immutable</em> objects, since you can never change the object itself but only assign (e.g. to <code>self.val</code>, which will always make a per-instance reference), it's pretty minor.</p>
<p>Just about the only relevant difference for immutables: if you later assign <code>a.val = 3</code>, in the first case this will affect what's seen as <code>self.val</code> by each instance (except for instances that had their own <code>self.val</code> <em>assigned</em> to, or equivalent actions); in the second case, it will not affect what's seen as <code>self.val</code> by any instance (except for instances for which you had performed <code>del self.val</code> or equivalent actions).</p>
| 9 | 2009-10-11T03:15:07Z | [
"python",
"class",
"init"
] |
Difference between defining a member in __init__ to defining it in the class body in python? | 1,549,722 | <p>What is the difference between doing</p>
<pre><code>class a:
def __init__(self):
self.val=1
</code></pre>
<p>to doing</p>
<pre><code>class a:
val=1
def __init__(self):
pass
</code></pre>
| 6 | 2009-10-11T03:00:40Z | 1,550,046 | <p>As mentioned by others, in one case it's an attribute on the class on the other an attribute on the instance. Does this matter? Yes, in one case it does. As Alex said, if the value is mutable. The best explanation is code, so I'll add some code to show it (that's all this answer does, really):</p>
<p>First a class defining two instance attributes.</p>
<pre><code>>>> class A(object):
... def __init__(self):
... self.number = 45
... self.letters = ['a', 'b', 'c']
...
</code></pre>
<p>And then a class defining two class attributes.</p>
<pre><code>>>> class B(object):
... number = 45
... letters = ['a', 'b', 'c']
...
</code></pre>
<p>Now we use them:</p>
<pre><code>>>> a1 = A()
>>> a2 = A()
>>> a2.number = 15
>>> a2.letters.append('z')
</code></pre>
<p>And all is well:</p>
<pre><code>>>> a1.number
45
>>> a1.letters
['a', 'b', 'c']
</code></pre>
<p>Now use the class attribute variation:</p>
<pre><code>>>> b1 = B()
>>> b2 = B()
>>> b2.number = 15
>>> b2.letters.append('z')
</code></pre>
<p>And all is...well...</p>
<pre><code>>>> b1.number
45
>>> b1.letters
['a', 'b', 'c', 'z']
</code></pre>
<p>Yeah, notice that when you changed, the mutable class attribute it changed for all classes. That's usually not what you want.</p>
<p>If you are using the ZODB, you use a lot of class attributes because it's a handy way of upgrading existing objects with new attributes, or adding information on a class level that doesn't get persisted. Otherwise you can pretty much ignore them.</p>
| 5 | 2009-10-11T06:47:02Z | [
"python",
"class",
"init"
] |
Difference between defining a member in __init__ to defining it in the class body in python? | 1,549,722 | <p>What is the difference between doing</p>
<pre><code>class a:
def __init__(self):
self.val=1
</code></pre>
<p>to doing</p>
<pre><code>class a:
val=1
def __init__(self):
pass
</code></pre>
| 6 | 2009-10-11T03:00:40Z | 1,550,873 | <p>Others have explained the technical differences. I'll try to explain why you might want to use class variables.</p>
<p>If you're only instantiating the class once, then class variables effectively <em>are</em> instance variables. However, if you're making many copies, or want to share state among a few instances, then class variables are very handy. For example:</p>
<pre><code>class Foo(object):
def __init__(self):
self.bar = expensivefunction()
myobjs = [Foo() for _ in range(1000000)]
</code></pre>
<p>will cause expensivefunction() to be called a million times. If it's going to return the same value each time, say fetching a configuration parameter from a database, then you should consider moving it into the class definition so that it's only called once and then shared across all instances.</p>
<p>I also use class variables a lot when memoizing results. Example:</p>
<pre><code>class Foo(object):
bazcache = {}
@classmethod
def baz(cls, key):
try:
result = cls.bazcache[key]
except KeyError:
result = expensivefunction(key)
cls.bazcache[key] = result
return result
</code></pre>
<p>In this case, baz is a class method; its result doesn't depend on any instance variables. That means we can keep one copy of the results cache in the class variable, so that 1) you don't store the same results multiple times, and 2) each instance can benefit from results that were cached from other instances.</p>
<p>To illustrate, suppose that you have a million instances, each operating on the results of a Google search. You'd probably much prefer that all those objects share those results than to have each one execute the search and wait for the answer.</p>
<p>So I'd disagree with Lennart here. Class variables are <em>very</em> convenient in certain cases. When they're the right tool for the job, don't hesitate to use them.</p>
| 5 | 2009-10-11T14:52:22Z | [
"python",
"class",
"init"
] |
Unexpected result on a simple example | 1,549,795 | <pre><code># Barn yard example: counting heads and legs
def solve(numLegs, numHeads):
for numChicks in range(0, numHeads + 1):
numPigs = numHeads - numChicks
totLegs = 4*numPigs + 2*numChicks
if totLegs == numLegs:
return [numPigs, numChicks]
return [None, None]
def barnYard(heads, legs):
pigs, chickens = solve(legs, heads)
if pigs == None:
print "There is no solution."
else:
print 'Number of pigs: ', pigs
print 'Number of Chickens: ', chickens
barnYard(20,56)
</code></pre>
<p>Expected result is 8 and 12 I think, but it returns 'There is no solution'. What am I doing wrong?</p>
<p>I'm just starting with programming, so please be nice ... :)</p>
| 0 | 2009-10-11T03:47:05Z | 1,549,799 | <p>look at your indentation. <code>return [None, None]</code> is inside the loop. it returns <code>[None, None]</code> after the first iteration</p>
| 3 | 2009-10-11T03:48:49Z | [
"python"
] |
Unexpected result on a simple example | 1,549,795 | <pre><code># Barn yard example: counting heads and legs
def solve(numLegs, numHeads):
for numChicks in range(0, numHeads + 1):
numPigs = numHeads - numChicks
totLegs = 4*numPigs + 2*numChicks
if totLegs == numLegs:
return [numPigs, numChicks]
return [None, None]
def barnYard(heads, legs):
pigs, chickens = solve(legs, heads)
if pigs == None:
print "There is no solution."
else:
print 'Number of pigs: ', pigs
print 'Number of Chickens: ', chickens
barnYard(20,56)
</code></pre>
<p>Expected result is 8 and 12 I think, but it returns 'There is no solution'. What am I doing wrong?</p>
<p>I'm just starting with programming, so please be nice ... :)</p>
| 0 | 2009-10-11T03:47:05Z | 1,549,805 | <p>In <code>solve()</code>, your return statement is indented to be inside of the for loop. Back it out one level, and it should work just fine.</p>
<pre><code>def solve(numLegs, numHeads):
for numChicks in range(0, numHeads + 1):
numPigs = numHeads - numChicks
totLegs = 4*numPigs + 2*numChicks
if totLegs == numLegs:
return [numPigs, numChicks]
return [None, None]
</code></pre>
| 3 | 2009-10-11T03:52:29Z | [
"python"
] |
Differences between isinstance() and type() in python | 1,549,801 | <p>What are the differences between these two code fragments? Which way is considered to be more pythonic?</p>
<p>Using <code>type()</code>:</p>
<pre><code>import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
</code></pre>
<p>Using <code>isinstance()</code>:</p>
<pre><code>if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
</code></pre>
<p><strong>Edit:</strong> This seems to be discussed already: <a href="http://stackoverflow.com/questions/378927/what-is-the-best-idiomatic-way-to-check-the-type-of-a-python-variable">link</a>.</p>
| 588 | 2009-10-11T03:50:54Z | 1,549,809 | <p>The latter is preferred, because it will handle subclasses properly. In fact, your example can be written even more easily because <code>isinstance()</code>'s second parameter may be a tuple:</p>
<pre><code>if isinstance(b, (str, unicode)):
do_something_else()
</code></pre>
<p>or, using the <code>basestring</code> abstract class:</p>
<pre><code>if isinstance(b, basestring):
do_something_else()
</code></pre>
| 41 | 2009-10-11T03:54:17Z | [
"python",
"oop",
"inheritance",
"types"
] |
Differences between isinstance() and type() in python | 1,549,801 | <p>What are the differences between these two code fragments? Which way is considered to be more pythonic?</p>
<p>Using <code>type()</code>:</p>
<pre><code>import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
</code></pre>
<p>Using <code>isinstance()</code>:</p>
<pre><code>if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
</code></pre>
<p><strong>Edit:</strong> This seems to be discussed already: <a href="http://stackoverflow.com/questions/378927/what-is-the-best-idiomatic-way-to-check-the-type-of-a-python-variable">link</a>.</p>
| 588 | 2009-10-11T03:50:54Z | 1,549,814 | <p>Here's why <code>isinstance</code> is better than <code>type</code>:</p>
<pre><code>class Vehicle:
pass
class Truck(Vehicle):
pass
</code></pre>
<p>in this case, a truck object is a Vehicle, but you'll get this:</p>
<pre><code>isinstance(Vehicle(), Vehicle) # returns True
type(Vehicle()) == Vehicle # returns True
isinstance(Truck(), Vehicle) # returns True
type(Truck()) == Vehicle # returns False, and this probably won't be what you want.
</code></pre>
<p>In other words, <code>isinstance</code> is true for subclasses, too.</p>
<p>Also see: <a href="http://stackoverflow.com/q/707674/1341006">How to compare type of an object in Python?</a></p>
| 149 | 2009-10-11T03:58:54Z | [
"python",
"oop",
"inheritance",
"types"
] |
Differences between isinstance() and type() in python | 1,549,801 | <p>What are the differences between these two code fragments? Which way is considered to be more pythonic?</p>
<p>Using <code>type()</code>:</p>
<pre><code>import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
</code></pre>
<p>Using <code>isinstance()</code>:</p>
<pre><code>if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
</code></pre>
<p><strong>Edit:</strong> This seems to be discussed already: <a href="http://stackoverflow.com/questions/378927/what-is-the-best-idiomatic-way-to-check-the-type-of-a-python-variable">link</a>.</p>
| 588 | 2009-10-11T03:50:54Z | 1,549,815 | <p>According to python documentation here is a statement:</p>
<blockquote>
<h3><a href="http://docs.python.org/library/types.html" rel="nofollow">8.15. types â Names for built-in types</a></h3>
<p>Starting in Python 2.2, built-in
factory functions such as <code>int()</code> and
<code>str()</code> are also names for the
corresponding types.</p>
</blockquote>
<p>So <a href="http://docs.python.org/2/library/functions.html#isinstance" rel="nofollow"><code>isinstance()</code></a> should be preferred over <a href="http://docs.python.org/2/library/functions.html#type" rel="nofollow"><code>type()</code></a>. </p>
| 7 | 2009-10-11T03:59:14Z | [
"python",
"oop",
"inheritance",
"types"
] |
Differences between isinstance() and type() in python | 1,549,801 | <p>What are the differences between these two code fragments? Which way is considered to be more pythonic?</p>
<p>Using <code>type()</code>:</p>
<pre><code>import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
</code></pre>
<p>Using <code>isinstance()</code>:</p>
<pre><code>if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
</code></pre>
<p><strong>Edit:</strong> This seems to be discussed already: <a href="http://stackoverflow.com/questions/378927/what-is-the-best-idiomatic-way-to-check-the-type-of-a-python-variable">link</a>.</p>
| 588 | 2009-10-11T03:50:54Z | 1,549,854 | <p>To summarize the contents of other (already good!) answers, <code>isinstance</code> caters for inheritance (an instance of a derived class <em>is an</em> instance of a base class, too), while checking for equality of <code>type</code> does not (it demands identity of types and rejects instances of subtypes, AKA subclasses).</p>
<p>Normally, in Python, you want your code to support inheritance, of course (since inheritance is so handy, it would be bad to stop code using yours from using it!), so <code>isinstance</code> is less bad than checking identity of <code>type</code>s because it seamlessly supports inheritance.</p>
<p>It's not that <code>isinstance</code> is <em>good</em>, mind youâit's just <em>less bad</em> than checking equality of types. The normal, Pythonic, preferred solution is almost invariably "duck typing": try using the argument <em>as if</em> it was of a certain desired type, do it in a <code>try</code>/<code>except</code> statement catching all exceptions that could arise if the argument was not in fact of that type (or any other type nicely duck-mimicking it;-), and in the <code>except</code> clause, try something else (using the argument "as if" it was of some other type).</p>
<p><code>basestring</code> <strong>is</strong>, however, quite a special caseâa builtin type that exists <strong>only</strong> to let you use <code>isinstance</code> (both <code>str</code> and <code>Unicode</code> subclass <code>basestring</code>). Strings are sequences (you could loop over them, index them, slice them, ...), but you generally want to treat them as "scalar" typesâit's somewhat incovenient (but a reasonably frequent use case) to treat all kinds of strings (and maybe other scalar types, i.e., ones you can't loop on) one way, all containers (lists, sets, dicts, ...) in another way, and <code>basestring</code> plus <code>isinstance</code> helps you do thatâthe overall structure of this idiom is something like:</p>
<pre><code>if isinstance(x, basestring)
return treatasscalar(x)
try:
return treatasiter(iter(x))
except TypeError:
return treatasscalar(x)
</code></pre>
<p>You could say that <code>basestring</code> is an <em>Abstract Base Class</em> ("ABC")âit offers no concrete functionality to subclasses, but rather exists as a "marker", mainly for use with <code>isinstance</code>. The concept is obviously a growing one in Python, since <a href="http://www.python.org/dev/peps/pep-3119/">PEP 3119</a>, which introduces a generalization of it, was accepted and has been implemented starting with Python 2.6 and 3.0.</p>
<p>The PEP makes it clear that, while ABCs can often substitute for duck typing, there is generally no big pressure to do that (see <a href="http://www.python.org/dev/peps/pep-3119/#abcs-vs-duck-typing">here</a>). ABCs as implemented in recent Python versions do however offer extra goodies: <code>isinstance</code> (and <code>issubclass</code>) can now mean more than just "[an instance of] a derived class" (in particular, any class can be "registered" with an ABC so that it will show as a subclass, and its instances as instances of the ABC); and ABCs can also offer extra convenience to actual subclasses in a very natural way via Template Method design pattern applications (see <a href="http://en.wikipedia.org/wiki/Template_method_pattern">here</a> and <a href="http://www.catonmat.net/blog/learning-python-design-patterns-through-video-lectures/">here</a> [[part II]] for more on the TM DP, in general and specifically in Python, independent of ABCs).</p>
<p>For the underlying mechanics of ABC support as offered in Python 2.6, see <a href="http://docs.python.org/library/abc.html">here</a>; for their 3.1 version, very similar, see <a href="http://docs.python.org/3.1/library/abc.html">here</a>. In both versions, standard library module <a href="http://docs.python.org/3.1/library/collections.html#module-collections">collections</a> (that's the 3.1 versionâfor the very similar 2.6 version, see <a href="http://docs.python.org/library/collections.html#module-collections">here</a>) offers several useful ABCs.</p>
<p>For the purpose of this answer, the key thing to retain about ABCs (beyond an arguably more natural placement for TM DP functionality, compared to the classic Python alternative of mixin classes such as <a href="http://docs.python.org/library/userdict.html?highlight=userdict#UserDict.DictMixin">UserDict.DictMixin</a>) is that they make <code>isinstance</code> (and <code>issubclass</code>) much more attractive and pervasive (in Python 2.6 and going forward) than they used to be (in 2.5 and before), and therefore, by contrast, make checking type equality an even worse practice in recent Python versions than it already used to be.</p>
| 654 | 2009-10-11T04:31:57Z | [
"python",
"oop",
"inheritance",
"types"
] |
Differences between isinstance() and type() in python | 1,549,801 | <p>What are the differences between these two code fragments? Which way is considered to be more pythonic?</p>
<p>Using <code>type()</code>:</p>
<pre><code>import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
</code></pre>
<p>Using <code>isinstance()</code>:</p>
<pre><code>if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
</code></pre>
<p><strong>Edit:</strong> This seems to be discussed already: <a href="http://stackoverflow.com/questions/378927/what-is-the-best-idiomatic-way-to-check-the-type-of-a-python-variable">link</a>.</p>
| 588 | 2009-10-11T03:50:54Z | 28,358,473 | <blockquote>
<h1>Differences between <code>isinstance()</code> and <code>type()</code> in Python?</h1>
</blockquote>
<p>Type-checking with </p>
<pre><code>isinstance(obj, Base)
</code></pre>
<p>allows for instances of subclasses and multiple possible bases: </p>
<pre><code>isinstance(obj, (Base1, Base2))
</code></pre>
<p>whereas type-checking with </p>
<pre><code>type(obj) == Base
</code></pre>
<p>only supports the type referenced.</p>
<h2>Usually avoid type-checking - use duck-typing</h2>
<p>In Python, usually you want to allow any type for your arguments, treat it as expected, and if the object doesn't behave as expected, it will raise an appropriate error. This is known as duck-typing.</p>
<pre><code>def function_of_duck(duck):
duck.quack()
duck.swim()
</code></pre>
<p>If the code above works, we can presume our argument is a duck. Thus we can pass in other things are types of duck:</p>
<pre><code>function_of_duck(mallard)
</code></pre>
<p>or that work like a duck:</p>
<pre><code>function_of_duck(object_that_quacks_and_swims_like_a_duck)
</code></pre>
<p>and our code still works.</p>
<p>However, there are some cases where it is desirable to explicitly type-check.
Perhaps you have sensible things to do with several very different object types. For example, the Pandas Dataframe object can be constructed from dicts <em>or</em> records. In such a case, your code needs to know what type of argument it is getting so that it can properly handle it. </p>
<p>So, to answer the question:</p>
<h2>Differences between <code>isinstance()</code> and <code>type()</code> in Python?</h2>
<p>Allow me to demonstrate the difference:</p>
<h3><code>type</code></h3>
<p>Say you need to ensure certain behavior if your function gets a certain kind of argument (a common use-case for constructors). If you check for type like this:</p>
<pre><code>def foo(data):
'''accepts a dict to construct something, string support in future'''
if type(data) != dict:
# we're only going to test for dicts for now
raise ValueError('only dicts are supported for now')
</code></pre>
<p>If we try to pass in a dict that is a subclass of <code>dict</code> (as we should be able to, if we're expecting our code to follow the principle of <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow">Liskov Substitution</a>, that subtypes can be substituted for types) our code breaks!:</p>
<pre><code>from collections import OrderedDict
foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))
</code></pre>
<p>raises an error!</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in foo
ValueError: argument must be a dict
</code></pre>
<h3><code>isinstance</code></h3>
<p>But if we use <code>isinstance</code>, we can support Liskov Substitution!:</p>
<pre><code>def foo(a_dict):
if not isinstance(a_dict, dict):
raise ValueError('argument must be a dict')
return a_dict
foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))
</code></pre>
<p>returns <code>OrderedDict([('foo', 'bar'), ('fizz', 'buzz')])</code></p>
<h2>Abstract Base Classes</h2>
<p>In fact, we can do even better. <code>collections</code> provides Abstract Base Classes that enforce minimal protocols for various types. In our case, if we only expect the <code>Mapping</code> protocol, we can do the following, and our code becomes even more flexible:</p>
<pre><code>from collections import Mapping
def foo(a_dict):
if not isinstance(a_dict, Mapping):
raise ValueError('argument must be a dict')
return a_dict
</code></pre>
<h2>Conclusion</h2>
<p>So since we want to support substituting subclasses, in most cases, we want to avoid type-checking with <code>type</code> and prefer type-checking with <code>isinstance</code> - unless you really need to know the precise class of the instance. </p>
| 24 | 2015-02-06T04:13:45Z | [
"python",
"oop",
"inheritance",
"types"
] |
"Cloning" row or column vectors | 1,550,130 | <p>Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as</p>
<pre><code>[1,2,3]
</code></pre>
<p>Into a matrix</p>
<pre><code>[[1,2,3]
[1,2,3]
[1,2,3]
]
</code></pre>
<p>or a column vector such as</p>
<pre><code>[1
2
3
]
</code></pre>
<p>into</p>
<pre><code>[[1,1,1]
[2,2,2]
[3,3,3]
]
</code></pre>
<p>In matlab or octave this is done pretty easily:</p>
<pre><code> x = [1,2,3]
a = ones(3,1) * x
a =
1 2 3
1 2 3
1 2 3
b = (x') * ones(1,3)
b =
1 1 1
2 2 2
3 3 3
</code></pre>
<p>I want to repeat this in numpy, but unsuccessfully</p>
<pre><code>In [14]: x = array([1,2,3])
In [14]: ones((3,1)) * x
Out[14]:
array([[ 1., 2., 3.],
[ 1., 2., 3.],
[ 1., 2., 3.]])
# so far so good
In [16]: x.transpose() * ones((1,3))
Out[16]: array([[ 1., 2., 3.]])
# DAMN
# I end up with
In [17]: (ones((3,1)) * x).transpose()
Out[17]:
array([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
</code></pre>
<p>Why wasn't the first method (In[16]) working? Is there a way to achieve this task in python in a more elegant way?</p>
| 55 | 2009-10-11T07:54:05Z | 1,550,137 | <p>Here's an elegant, Pythonic way to do it:</p>
<pre><code>>>> array([[1,2,3],]*3)
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
>>> array([[1,2,3],]*3).transpose()
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
</code></pre>
<p>the problem with <code>[16]</code> seems to be that the transpose has no effect for an array. you're probably wanting a matrix instead:</p>
<pre><code>>>> x = array([1,2,3])
>>> x
array([1, 2, 3])
>>> x.transpose()
array([1, 2, 3])
>>> matrix([1,2,3])
matrix([[1, 2, 3]])
>>> matrix([1,2,3]).transpose()
matrix([[1],
[2],
[3]])
</code></pre>
| 25 | 2009-10-11T07:59:23Z | [
"python",
"matlab",
"numpy",
"octave",
"linear-algebra"
] |
"Cloning" row or column vectors | 1,550,130 | <p>Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as</p>
<pre><code>[1,2,3]
</code></pre>
<p>Into a matrix</p>
<pre><code>[[1,2,3]
[1,2,3]
[1,2,3]
]
</code></pre>
<p>or a column vector such as</p>
<pre><code>[1
2
3
]
</code></pre>
<p>into</p>
<pre><code>[[1,1,1]
[2,2,2]
[3,3,3]
]
</code></pre>
<p>In matlab or octave this is done pretty easily:</p>
<pre><code> x = [1,2,3]
a = ones(3,1) * x
a =
1 2 3
1 2 3
1 2 3
b = (x') * ones(1,3)
b =
1 1 1
2 2 2
3 3 3
</code></pre>
<p>I want to repeat this in numpy, but unsuccessfully</p>
<pre><code>In [14]: x = array([1,2,3])
In [14]: ones((3,1)) * x
Out[14]:
array([[ 1., 2., 3.],
[ 1., 2., 3.],
[ 1., 2., 3.]])
# so far so good
In [16]: x.transpose() * ones((1,3))
Out[16]: array([[ 1., 2., 3.]])
# DAMN
# I end up with
In [17]: (ones((3,1)) * x).transpose()
Out[17]:
array([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
</code></pre>
<p>Why wasn't the first method (In[16]) working? Is there a way to achieve this task in python in a more elegant way?</p>
| 55 | 2009-10-11T07:54:05Z | 1,552,016 | <p>First note that with numpy's <em>broadcasting</em> operations it's usually not necessary to duplicate rows and columns. See <a href="http://www.scipy.org/EricsBroadcastingDoc">this</a> and <a href="http://www.oreillynet.com/pub/a/python/2000/09/27/numerically.html?page=1">this</a> for descriptions.</p>
<p>But to do this, <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html#numpy.repeat"><strong>repeat</strong></a> and <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html"><strong>newaxis</strong></a> are probably the best way</p>
<pre><code>In [12]: x = array([1,2,3])
In [13]: repeat(x[:,newaxis], 3, 1)
Out[13]:
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
In [14]: repeat(x[newaxis,:], 3, 0)
Out[14]:
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
</code></pre>
<p>This example is for a row vector, but applying this to a column vector is hopefully obvious. repeat seems to spell this well, but you can also do it via multiplication as in your example</p>
<pre><code>In [15]: x = array([[1, 2, 3]]) # note the double brackets
In [16]: (ones((3,1))*x).transpose()
Out[16]:
array([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
</code></pre>
| 18 | 2009-10-11T22:56:20Z | [
"python",
"matlab",
"numpy",
"octave",
"linear-algebra"
] |
"Cloning" row or column vectors | 1,550,130 | <p>Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as</p>
<pre><code>[1,2,3]
</code></pre>
<p>Into a matrix</p>
<pre><code>[[1,2,3]
[1,2,3]
[1,2,3]
]
</code></pre>
<p>or a column vector such as</p>
<pre><code>[1
2
3
]
</code></pre>
<p>into</p>
<pre><code>[[1,1,1]
[2,2,2]
[3,3,3]
]
</code></pre>
<p>In matlab or octave this is done pretty easily:</p>
<pre><code> x = [1,2,3]
a = ones(3,1) * x
a =
1 2 3
1 2 3
1 2 3
b = (x') * ones(1,3)
b =
1 1 1
2 2 2
3 3 3
</code></pre>
<p>I want to repeat this in numpy, but unsuccessfully</p>
<pre><code>In [14]: x = array([1,2,3])
In [14]: ones((3,1)) * x
Out[14]:
array([[ 1., 2., 3.],
[ 1., 2., 3.],
[ 1., 2., 3.]])
# so far so good
In [16]: x.transpose() * ones((1,3))
Out[16]: array([[ 1., 2., 3.]])
# DAMN
# I end up with
In [17]: (ones((3,1)) * x).transpose()
Out[17]:
array([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
</code></pre>
<p>Why wasn't the first method (In[16]) working? Is there a way to achieve this task in python in a more elegant way?</p>
| 55 | 2009-10-11T07:54:05Z | 1,582,742 | <p>Use <code>numpy.tile</code>:</p>
<pre><code>>>> tile(array([1,2,3]), (3, 1))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
</code></pre>
<p>or for repeating columns:</p>
<pre><code>>>> tile(array([[1,2,3]]).transpose(), (1, 3))
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
</code></pre>
| 130 | 2009-10-17T17:33:21Z | [
"python",
"matlab",
"numpy",
"octave",
"linear-algebra"
] |
"Cloning" row or column vectors | 1,550,130 | <p>Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as</p>
<pre><code>[1,2,3]
</code></pre>
<p>Into a matrix</p>
<pre><code>[[1,2,3]
[1,2,3]
[1,2,3]
]
</code></pre>
<p>or a column vector such as</p>
<pre><code>[1
2
3
]
</code></pre>
<p>into</p>
<pre><code>[[1,1,1]
[2,2,2]
[3,3,3]
]
</code></pre>
<p>In matlab or octave this is done pretty easily:</p>
<pre><code> x = [1,2,3]
a = ones(3,1) * x
a =
1 2 3
1 2 3
1 2 3
b = (x') * ones(1,3)
b =
1 1 1
2 2 2
3 3 3
</code></pre>
<p>I want to repeat this in numpy, but unsuccessfully</p>
<pre><code>In [14]: x = array([1,2,3])
In [14]: ones((3,1)) * x
Out[14]:
array([[ 1., 2., 3.],
[ 1., 2., 3.],
[ 1., 2., 3.]])
# so far so good
In [16]: x.transpose() * ones((1,3))
Out[16]: array([[ 1., 2., 3.]])
# DAMN
# I end up with
In [17]: (ones((3,1)) * x).transpose()
Out[17]:
array([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
</code></pre>
<p>Why wasn't the first method (In[16]) working? Is there a way to achieve this task in python in a more elegant way?</p>
| 55 | 2009-10-11T07:54:05Z | 21,146,167 | <p>I think using the broadcast in numpy is the best, and faster</p>
<p>I did a compare as following</p>
<pre><code>import numpy as np
b = np.random.randn(1000)
In [105]: %timeit c = np.tile(b[:, newaxis], (1,100))
1000 loops, best of 3: 354 µs per loop
In [106]: %timeit c = np.repeat(b[:, newaxis], 100, axis=1)
1000 loops, best of 3: 347 µs per loop
In [107]: %timeit c = np.array([b,]*100).transpose()
100 loops, best of 3: 5.56 ms per loop
</code></pre>
<p>about 15 times faster using broadcast</p>
| 4 | 2014-01-15T19:10:59Z | [
"python",
"matlab",
"numpy",
"octave",
"linear-algebra"
] |
Problem about python writing files | 1,550,132 | <p>I've got a weird problem with python programming. I used the statement'writelines()' to write a series of lists into a new file.During the process I could see the context in the file icon via preview, however once after the program finished running the output file comes out to be a blank file.</p>
<p>In short, my problem is that the program doesn't have any output but a blank file.</p>
<p>Here's the code:</p>
<pre><code>infile=open('/Users/Jim/Desktop/py/result.txt','r')
outfile=open('/Users/Jim/Desktop/py/output.txt','a')
line=infile.readline()
i=1
while(line):
check=str(i)+':'
if line.startswith(check):
i+=1
block=[infile.readline() for j in range(1,7)]
judge=block[1].split()
for j in judge:
if j=='stem' or j=='differetiation' or j=='differetiating':
outfile.write(str(i)+':\n')
outfile.writelines(block) #check if the paragraph has the given key words, if true then write the paragraph into the output file.
break
line=infile.readline()
outfile.close()
infile.close()
</code></pre>
<p>Some additional information if helpful:
The python version is 2.6.3, and the os is Mac OS 10.6.</p>
| 0 | 2009-10-11T07:54:44Z | 1,550,166 | <p>I guess it's caused by incorrect indentation. The <code>break</code> statement should be inside the <code>if</code> block. The loop as it is written will only try the first option from <code>judge</code>. Check if you don't have mixed spaces and tabs in the file.</p>
| 2 | 2009-10-11T08:14:54Z | [
"python",
"file"
] |
How to assign a variable in IF, and then return it. (Python) | 1,550,134 | <pre><code>def isBig(x):
if x > 4:
return 'apple'
else:
return 'orange'
</code></pre>
<p>This works:</p>
<pre><code>if isBig(y): return isBig(y)
</code></pre>
<p>This does NOT work:</p>
<pre><code>if fruit = isBig(y): return fruit
</code></pre>
<p>Why doesn't the 2nd one work!? I want a 1-liner. Except, the 1st one will call the function TWICE.</p>
<p><em>How to make it 1 liner, without calling the function twice?</em></p>
| 7 | 2009-10-11T07:57:29Z | 1,550,142 | <p>This doesn't work due to intentional language design, but you can use <a href="http://code.activestate.com/recipes/66061/" rel="nofollow">this trick</a> to get around this decision</p>
| 0 | 2009-10-11T08:01:39Z | [
"python"
] |
How to assign a variable in IF, and then return it. (Python) | 1,550,134 | <pre><code>def isBig(x):
if x > 4:
return 'apple'
else:
return 'orange'
</code></pre>
<p>This works:</p>
<pre><code>if isBig(y): return isBig(y)
</code></pre>
<p>This does NOT work:</p>
<pre><code>if fruit = isBig(y): return fruit
</code></pre>
<p>Why doesn't the 2nd one work!? I want a 1-liner. Except, the 1st one will call the function TWICE.</p>
<p><em>How to make it 1 liner, without calling the function twice?</em></p>
| 7 | 2009-10-11T07:57:29Z | 1,550,145 | <p>The problem is that the assignment operation cannot be evaluated as having a boolean value. The <code>if</code> statement relies on being able to evaluate a boolean. For example,</p>
<pre><code>>>> fruit = 'apple'
>>> bool(fruit = 'apple')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/jem/<ipython console> in <module>()
TypeError: 'fruit' is an invalid keyword argument for this function
>>> bool('a')
True
</code></pre>
| 0 | 2009-10-11T08:02:37Z | [
"python"
] |
How to assign a variable in IF, and then return it. (Python) | 1,550,134 | <pre><code>def isBig(x):
if x > 4:
return 'apple'
else:
return 'orange'
</code></pre>
<p>This works:</p>
<pre><code>if isBig(y): return isBig(y)
</code></pre>
<p>This does NOT work:</p>
<pre><code>if fruit = isBig(y): return fruit
</code></pre>
<p>Why doesn't the 2nd one work!? I want a 1-liner. Except, the 1st one will call the function TWICE.</p>
<p><em>How to make it 1 liner, without calling the function twice?</em></p>
| 7 | 2009-10-11T07:57:29Z | 1,550,147 | <p>If you want to code in PHP (or C), code in it. Don't try to force its methods onto another language.</p>
<p>One of the basic tenets behind Python (in my opinion) is its readability. You should be using:</p>
<pre><code>fruit = isBig(y)
if fruit: return fruit
</code></pre>
<p>I should also mention that your use of <code>isXXX()</code> is very strange; it's usually used to return boolean values. Especially in this case where you're using it in an <code>IF</code> statement.</p>
| 3 | 2009-10-11T08:03:19Z | [
"python"
] |
How to assign a variable in IF, and then return it. (Python) | 1,550,134 | <pre><code>def isBig(x):
if x > 4:
return 'apple'
else:
return 'orange'
</code></pre>
<p>This works:</p>
<pre><code>if isBig(y): return isBig(y)
</code></pre>
<p>This does NOT work:</p>
<pre><code>if fruit = isBig(y): return fruit
</code></pre>
<p>Why doesn't the 2nd one work!? I want a 1-liner. Except, the 1st one will call the function TWICE.</p>
<p><em>How to make it 1 liner, without calling the function twice?</em></p>
| 7 | 2009-10-11T07:57:29Z | 1,550,148 | <p>The one liner doesn't work because, in Python, assignment (<code>fruit = isBig(y)</code>) is a statement, not an expression. In C, C++, Perl, and countless other languages it is an expression, and you can put it in an <code>if</code> or a <code>while</code> or whatever you like, but not in Python, because the creators of Python thought that this was too easily misused (or abused) to write "clever" code (like you're trying to).</p>
<p>Also, your example is rather silly. <code>isBig()</code> will always evaluate to <code>true</code>, since the only string that's false is the empty string (<code>""</code>), so your <code>if</code> statement is useless in this case. I assume that's just a simplification of what you're trying to do. Just do this:</p>
<pre><code>tmp = isBig(y)
if tmp: return tmp
</code></pre>
<p>Is it really that much worse?</p>
| 8 | 2009-10-11T08:03:25Z | [
"python"
] |
How to assign a variable in IF, and then return it. (Python) | 1,550,134 | <pre><code>def isBig(x):
if x > 4:
return 'apple'
else:
return 'orange'
</code></pre>
<p>This works:</p>
<pre><code>if isBig(y): return isBig(y)
</code></pre>
<p>This does NOT work:</p>
<pre><code>if fruit = isBig(y): return fruit
</code></pre>
<p>Why doesn't the 2nd one work!? I want a 1-liner. Except, the 1st one will call the function TWICE.</p>
<p><em>How to make it 1 liner, without calling the function twice?</em></p>
| 7 | 2009-10-11T07:57:29Z | 1,551,223 | <p>I see somebody else has already pointed to my old "assign and set" Cookbook recipe, which boils down in its simplest version to:</p>
<pre><code>class Holder(object):
def set(self, value):
self.value = value
return value
def get(self):
return self.value
h = Holder()
...
if h.set(isBig(y)): return h.get()
</code></pre>
<p>However, this was intended mostly to ease transliteration between Python and languages where assignment is directly supported in <code>if</code> or <code>while</code>. If you have "hundreds" of such check-and-return in a cascade, it's <em>much</em> better to do something completely different:</p>
<pre><code>hundreds = isBig, isSmall, isJuicy, isBlah, ...
for predicate in hundreds:
result = predicate(y)
if result: return result
</code></pre>
<p>or even something like</p>
<pre><code>return next(x for x in (f(y) for f in hundreds) if x)
</code></pre>
<p>if it's OK to get a StopIteration exception if no predicate is satisfied, or</p>
<pre><code>return next((x for x in (f(y) for f in hundreds) if x)), None)
</code></pre>
<p>if <code>None</code> is the proper return value when no predicate is satisfied, etc.</p>
<p>Almost invariably, using (or even wishing for;-) the <code>Holder</code> trick/non-idiom is a "design smell" which suggests looking for a different and more Pythonic approach -- the one case where <code>Holder</code> is justified is exactly the special case for which I designed it, i.e., the case where you want to keep close correspondence between the Python code and some non-Python (you're transliterating a reference algorithm in Python and want it working first before refactoring it into a more Pythonic form, or you're writing Python as a prototype that will be transliterated into C++, C#, Java, etc, once it's working effectively).</p>
| 14 | 2009-10-11T17:31:16Z | [
"python"
] |
How to assign a variable in IF, and then return it. (Python) | 1,550,134 | <pre><code>def isBig(x):
if x > 4:
return 'apple'
else:
return 'orange'
</code></pre>
<p>This works:</p>
<pre><code>if isBig(y): return isBig(y)
</code></pre>
<p>This does NOT work:</p>
<pre><code>if fruit = isBig(y): return fruit
</code></pre>
<p>Why doesn't the 2nd one work!? I want a 1-liner. Except, the 1st one will call the function TWICE.</p>
<p><em>How to make it 1 liner, without calling the function twice?</em></p>
| 7 | 2009-10-11T07:57:29Z | 19,688,351 | <pre><code>print "apple" if x > 4 else "orange"
</code></pre>
| 0 | 2013-10-30T16:22:20Z | [
"python"
] |
Why doesn't memcache work in my Django? | 1,550,180 | <pre><code>from django.core.cache import cache
def testcache():
cache.set('test','I am putting this message in',3333)
print cache.get('test')
</code></pre>
<p>It just prints "<strong>None</strong>"</p>
<p>This is in "ps aux":</p>
<pre><code>dovr 2241 0.0 0.8 57824 2144 ? Ssl 04:20 0:00 memcached -d -u root -m 3900 -p 11211
dovr 2247 0.0 3.7 83696 9800 pts/2 S+ 04:20 0:00 python manage.py runserver 0.0.0.0:8000
</code></pre>
<p>And this is in my settings.py:</p>
<pre><code>CACHE_BACKEND = 'memcached://MYIPADRESS:11211/'
</code></pre>
<p>By the way, it worked before, but not anymore! I don't know why. So weird.</p>
| 1 | 2009-10-11T08:25:24Z | 1,550,488 | <p>You can insure that you can reach memcached from your code by logging value returned from <code>set()</code> method. Probably memcached listens on 127.0.0.1 while you are trying to connect to external interface.</p>
| 2 | 2009-10-11T11:33:00Z | [
"python",
"django",
"memcached"
] |
Why doesn't memcache work in my Django? | 1,550,180 | <pre><code>from django.core.cache import cache
def testcache():
cache.set('test','I am putting this message in',3333)
print cache.get('test')
</code></pre>
<p>It just prints "<strong>None</strong>"</p>
<p>This is in "ps aux":</p>
<pre><code>dovr 2241 0.0 0.8 57824 2144 ? Ssl 04:20 0:00 memcached -d -u root -m 3900 -p 11211
dovr 2247 0.0 3.7 83696 9800 pts/2 S+ 04:20 0:00 python manage.py runserver 0.0.0.0:8000
</code></pre>
<p>And this is in my settings.py:</p>
<pre><code>CACHE_BACKEND = 'memcached://MYIPADRESS:11211/'
</code></pre>
<p>By the way, it worked before, but not anymore! I don't know why. So weird.</p>
| 1 | 2009-10-11T08:25:24Z | 1,552,188 | <p>Solved.</p>
<p>Django was talking to the server.
I did "nc IPADRESS 11211" .
And typed "stats"</p>
<p>Then, I looked that cmd_get and cmd_set were changing, so that means it's talking.</p>
<p>Then, I realized that I had problem with code in my views.
You can't have "space" in the key. It has to be non-spaceless (and encoded)</p>
| 0 | 2009-10-12T00:20:41Z | [
"python",
"django",
"memcached"
] |
python setup.py uninstall | 1,550,226 | <p>I have installed a python package with <code>python setup.py install</code>.</p>
<p>How do I uninstall it?</p>
| 489 | 2009-10-11T09:06:56Z | 1,550,235 | <p>You need to remove all files manually, and also undo any other stuff that installation did manually.</p>
<p>If you don't know the list of all files, you can reinstall it with the <code>--record</code> option, and take a look at the list this produces.</p>
<p>To record list of installed files, you can use:</p>
<pre><code>python setup.py install --record files.txt
</code></pre>
<p>Once you want to uninstall you can use xargs to do the removal:</p>
<pre><code>cat files.txt | xargs rm -rf
</code></pre>
| 621 | 2009-10-11T09:12:27Z | [
"python",
"setup.py",
"pypi"
] |
python setup.py uninstall | 1,550,226 | <p>I have installed a python package with <code>python setup.py install</code>.</p>
<p>How do I uninstall it?</p>
| 489 | 2009-10-11T09:06:56Z | 1,550,237 | <p>Go to your python package directory and remove your .egg file,
e.g.:
In python 2.5(ubuntu): /usr/lib/python2.5/site-packages/</p>
<p>In python 2.6(ubuntu): /usr/local/lib/python2.6/dist-packages/</p>
| 4 | 2009-10-11T09:13:35Z | [
"python",
"setup.py",
"pypi"
] |
python setup.py uninstall | 1,550,226 | <p>I have installed a python package with <code>python setup.py install</code>.</p>
<p>How do I uninstall it?</p>
| 489 | 2009-10-11T09:06:56Z | 1,550,238 | <p>The lazy way: simply uninstall from the Windows installation menu (if you're using Windows), or from the rpm command, provided you first re-install it after creating a distribution package.</p>
<p>For example,</p>
<pre><code>python setup.py bdist_wininst
dist/foo-1.0.win32.exe
</code></pre>
<p>("foo" being an example of course).</p>
| 7 | 2009-10-11T09:13:42Z | [
"python",
"setup.py",
"pypi"
] |
python setup.py uninstall | 1,550,226 | <p>I have installed a python package with <code>python setup.py install</code>.</p>
<p>How do I uninstall it?</p>
| 489 | 2009-10-11T09:06:56Z | 1,868,741 | <p>Extending on what Martin said, recording the install output and a little bash scripting does the trick quite nicely. Here's what I do...</p>
<pre><code>for i in $(less install.record);
sudo rm $i;
done;
</code></pre>
<p>And presto. Uninstalled.</p>
| 1 | 2009-12-08T18:00:04Z | [
"python",
"setup.py",
"pypi"
] |
python setup.py uninstall | 1,550,226 | <p>I have installed a python package with <code>python setup.py install</code>.</p>
<p>How do I uninstall it?</p>
| 489 | 2009-10-11T09:06:56Z | 4,042,668 | <p>Or more simply you could just do;</p>
<pre><code>sudo rm $(cat install.record)
</code></pre>
<p>This works because the rm command takes a whitespace-seperated list of files to delete and your installation record is just such a list. Also, using "less" for this type of command could get you in big trouble depending on the local configuration.</p>
| 21 | 2010-10-28T12:00:21Z | [
"python",
"setup.py",
"pypi"
] |
python setup.py uninstall | 1,550,226 | <p>I have installed a python package with <code>python setup.py install</code>.</p>
<p>How do I uninstall it?</p>
| 489 | 2009-10-11T09:06:56Z | 12,797,865 | <p>For me, the following mostly works:</p>
<p>have pip installed, e.g.:</p>
<pre><code>$ easy_install pip
</code></pre>
<p>Check, how is your installed package named from pip point of view:</p>
<pre><code>$ pip freeze
</code></pre>
<p>This shall list names of all packages, you have installed (and which were detected by pip).
The name can be sometime long, then use just the name of the package being shown at the and after <code>#egg=</code>. You can also in most cases ignore the version part (whatever follows <code>==</code> or <code>-</code>).</p>
<p>Then uninstall the package:</p>
<pre><code>$ pip uninstall package.name.you.have.found
</code></pre>
<p>If it asks for confirmation about removing the package, then you are lucky guy and it will be removed.</p>
<p>pip shall detect all packages, which were installed by pip. It shall also detect most of the packages installed via easy_install or setup.py, but this may in some rare cases fail.</p>
<p>Here is real sample from my local test with package named <code>ttr.rdstmc</code> on MS Windows.</p>
<pre><code>$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev
$ python setup.py develop
.....
.....
Finished processing dependencies for ttr.rdstmc==0.0.1dev
$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
-e hg+https://vlcinsky@bitbucket.org/vlcinsky/ttr.rdstmc@d61a9922920c508862602f7f39e496f7b99315f0#egg=ttr.rdstmc-dev
ttr.utcutils==0.1.1dev
$ pip uninstall ttr.rdstmc
Uninstalling ttr.rdstmc:
c:\python27\lib\site-packages\ttr.rdstmc.egg-link
Proceed (y/n)? y
Successfully uninstalled ttr.rdstmc
$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev
</code></pre>
<h2>Edit 2015-05-20</h2>
<p>All what is written above still applies, anyway, there are small modifications available now.</p>
<h3>Install pip in python 2.7.9 and python 3.4</h3>
<p>Recent python versions come with a package <code>ensurepip</code> allowing to install pip even when being offline:</p>
<p>$ python -m ensurepip --upgrade</p>
<p>On some systems (like Debian Jessie) this is not available (to prevent breaking system python installation).</p>
<h3>Using <code>grep</code> or <code>find</code></h3>
<p>Examples above assume, you have <code>grep</code> installed. I had (at the time I had MS Windows on my machine) installed set of linux utilities (incl. grep). Alternatively, use native MS Windows <code>find</code> or simply ignore that filtering and find the name in a bit longer list of detected python packages.</p>
| 164 | 2012-10-09T10:19:27Z | [
"python",
"setup.py",
"pypi"
] |
python setup.py uninstall | 1,550,226 | <p>I have installed a python package with <code>python setup.py install</code>.</p>
<p>How do I uninstall it?</p>
| 489 | 2009-10-11T09:06:56Z | 20,719,865 | <p>It might be better to remove related files by using bash to read commands, like the following:</p>
<pre><code>sudo python setup.py install --record files.txt
sudo bash -c "cat files.txt | xargs rm -rf"
</code></pre>
| 0 | 2013-12-21T14:13:28Z | [
"python",
"setup.py",
"pypi"
] |
python setup.py uninstall | 1,550,226 | <p>I have installed a python package with <code>python setup.py install</code>.</p>
<p>How do I uninstall it?</p>
| 489 | 2009-10-11T09:06:56Z | 20,780,379 | <p>Probably you can do this as an alternative :-</p>
<p>1) Get the python version -</p>
<pre><code>[linux machine]# python
Python 2.4.3 (#1, Jun 18 2012, 14:38:55)
</code></pre>
<p>-> The above command gives you the current python Version which is <strong>2.4.3</strong></p>
<p>2) Get the installation directory of python -</p>
<pre><code>[linux machine]# whereis python
python: /usr/bin/python /usr/bin/python2.4 /usr/lib/python2.4 /usr/local/bin/python2.5 /usr/include/python2.4 /usr/share/man/man1/python.1.gz
</code></pre>
<p>-> From above command you can get the installation directory which is - <strong>/usr/lib/python2.4/site-packages</strong></p>
<p>3) From here you can remove the packages and python egg files</p>
<pre><code>[linux machine]# cd /usr/lib/python2.4/site-packages
[linux machine]# rm -rf paramiko-1.12.0-py2.4.egg paramiko-1.7.7.1-py2.4.egg paramiko-1.9.0-py2.4.egg
</code></pre>
<p>This worked for me.. And i was able to uninstall package which was troubling me :)</p>
| 3 | 2013-12-26T06:44:14Z | [
"python",
"setup.py",
"pypi"
] |
python setup.py uninstall | 1,550,226 | <p>I have installed a python package with <code>python setup.py install</code>.</p>
<p>How do I uninstall it?</p>
| 489 | 2009-10-11T09:06:56Z | 25,209,129 | <p>The #1 answer has problems:</p>
<ul>
<li>Won't work on mac.</li>
<li>If a file is installed which includes spaces or other special
characters, the xargs command will fail, and delete any
files/directories which matched the individual words.</li>
<li>the -r in rm -rf is unnecessary and at worst could delete things you
don't want to.</li>
</ul>
<p>Instead, for unix-like:</p>
<pre><code>sudo python setup.py install --record files.txt
# inspect files.txt to make sure it looks ok. Then:
tr '\n' '\0' < files.txt | xargs -0 sudo rm -f --
</code></pre>
<p>And for windows:</p>
<pre><code>python setup.py bdist_wininst
dist/foo-1.0.win32.exe
</code></pre>
<p>There are also unsolvable problems with uninstalling setup.py install which won't bother you in a typical case. For a more complete answer, see this wiki page:</p>
<p><a href="https://ofswiki.org/wiki/Uninstalling_setup.py_install">https://ofswiki.org/wiki/Uninstalling_setup.py_install</a></p>
| 50 | 2014-08-08T17:34:59Z | [
"python",
"setup.py",
"pypi"
] |
python setup.py uninstall | 1,550,226 | <p>I have installed a python package with <code>python setup.py install</code>.</p>
<p>How do I uninstall it?</p>
| 489 | 2009-10-11T09:06:56Z | 32,382,242 | <p>Now python gives you the choice to install <code>pip</code> during the installation (I am on Windows, and at least python does so for Windows!). Considering you had chosen to install <code>pip</code> during installation of python (you don't actually have to choose because it is default), <code>pip</code> is already installed for you. Then, type in <code>pip</code> in command prompt, you should see a help come up. You can find necessary usage instructions there. E.g. <code>pip list</code> shows you the list of installed packages. You can use</p>
<pre><code>pip uninstall package_name
</code></pre>
<p>to uninstall any package that you don't want anymore. Read more <a href="https://pip.pypa.io/" rel="nofollow">here (pip documentation)</a>.</p>
| 4 | 2015-09-03T17:44:44Z | [
"python",
"setup.py",
"pypi"
] |
python setup.py uninstall | 1,550,226 | <p>I have installed a python package with <code>python setup.py install</code>.</p>
<p>How do I uninstall it?</p>
| 489 | 2009-10-11T09:06:56Z | 33,326,037 | <p>I think you can open the setup.py, locate the package name, and then ask pip to uninstall it.</p>
<p>Assuming the name is available in a 'METADATA' variable:</p>
<pre><code>pip uninstall $(python -c "from setup import METADATA; print METADATA['name']")
</code></pre>
| 3 | 2015-10-25T03:57:02Z | [
"python",
"setup.py",
"pypi"
] |
Counting all the keys pressed and what they are (python) | 1,550,273 | <p>I'd like to create a map of the number of presses for every key for a project I'm working on.</p>
<p>I'd like to do this with a Python module. Is it possible to do this in any way?</p>
| 0 | 2009-10-11T09:34:38Z | 1,550,298 | <p>On Windows, a possible solution is to install <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">Python for Windows extensions</a> and use the <a href="http://docs.activestate.com/activepython/2.4/pywin32/PyCWnd%5F%5FHookAllKeyStrokes%5Fmeth.html" rel="nofollow">PyCWnd.HookAllKeyStrokes</a></p>
| 1 | 2009-10-11T09:50:21Z | [
"python",
"key",
"counting"
] |
Counting all the keys pressed and what they are (python) | 1,550,273 | <p>I'd like to create a map of the number of presses for every key for a project I'm working on.</p>
<p>I'd like to do this with a Python module. Is it possible to do this in any way?</p>
| 0 | 2009-10-11T09:34:38Z | 1,550,656 | <p>As Nick D <a href="http://stackoverflow.com/questions/1550273/counting-all-the-keys-pressed-and-what-they-are-python/1550298#1550298">points out</a>, on Windows, the <a href="http://pypi.python.org/pypi/pyHook/1.4/" rel="nofollow">PyHook library</a> would work.</p>
<p>On Linux, the <a href="http://python-xlib.sourceforge.net/" rel="nofollow">Python X Library</a> gives you access to key-presses on the X-server.</p>
<p>A good example of the use of both libraries is <a href="http://pykeylogger.wiki.sourceforge.net/" rel="nofollow">pykeylogger</a>. It's open source; see <a href="http://www.koders.com/python/fidC2A13EA85A1B5C971E93300F93766F58F52A766D.aspx?s=timer" rel="nofollow"><code>pyxhook.py</code></a> for example for the relevant X library calls.</p>
<p>A lower level option in Linux is to read directly from <code>/dev/input/*</code>. The <a href="http://svn.navi.cx/misc/trunk/python/evdev/evdev.py" rel="nofollow">evdev (ctypes)</a> and <a href="http://packages.python.org/evdev/" rel="nofollow">evdev (c-api)</a> modules may help you here; I don't know much about them though.</p>
| 1 | 2009-10-11T13:10:37Z | [
"python",
"key",
"counting"
] |
web2py - how to inject html | 1,550,368 | <p>i used rows.xml() to generate html output. i want to know how to add html codes to this generated html page e.g: "add logo, link css file,.. etc"</p>
<p><code>rows=db(db.member.membership_id==request.args[0]).select(db.member.membership_id
,db.member.first_name,db.member.middle_name
,db.member.last_name)
return rows.xml()
</code></p>
| 2 | 2009-10-11T10:32:08Z | 1,550,391 | <p>Just prepend/append it to the string that <code>rows.xml()</code> returns:</p>
<pre><code>html = '<html><head>...</head><body>' + rows.xml() + '</body></html>'
</code></pre>
| 0 | 2009-10-11T10:44:45Z | [
"python",
"web2py"
] |
web2py - how to inject html | 1,550,368 | <p>i used rows.xml() to generate html output. i want to know how to add html codes to this generated html page e.g: "add logo, link css file,.. etc"</p>
<p><code>rows=db(db.member.membership_id==request.args[0]).select(db.member.membership_id
,db.member.first_name,db.member.middle_name
,db.member.last_name)
return rows.xml()
</code></p>
| 2 | 2009-10-11T10:32:08Z | 1,550,413 | <p>There are many HTML helpers you can use, for example:</p>
<pre><code>html_code = A('<click>', rows.xml(), _href='http://mylink')
html_code = B('Results:', rows.xml(), _class='results', _id=1)
html_page = HTML(BODY(B('Results:', rows.xml(), _class='results', _id=1)))
</code></pre>
<p>and so on.</p>
<p>You can even create a whole table automatically:</p>
<pre><code>table = SQLTABLE(rows, orderby=True, _width="100%")
</code></pre>
<p>and then pick it apart to insert links or modify its elements.</p>
<p>It is very powerful and normally you don't have to bother writing the actual HTML yourself. <a href="http://www.web2py.com/examples/static/web2py%5Fcheatsheet.pdf" rel="nofollow">Here is the cheatsheet</a>, or you can check directly on the <a href="http://www.web2py.com/examples/default/docs" rel="nofollow">website documentation</a>.</p>
<p><hr /></p>
<p>Edit: Just to make sure, you don't actually need to generate the whole HTML page, it is easier to let web2py insert your response in a template that has the same name as your controller (or force a particular template with <code>response.view = 'template.html'</code>. The documentation tutorial will explain that better and in further details.</p>
<p>In a few words, if you are implementing the function <code>index</code>, you could either return a string (the whole page HTML, which seems to be what you are heading for), or a dictionary to use templates.</p>
<p>In the first case, just code your function like this:</p>
<pre><code>def index():
# ... code to extract the rows
return HTML(BODY(B('Results:', rows.xml(), _class='results', _id=1))).xml()
</code></pre>
<p>Otherwise, write an html template in views/<em>controller</em>/index.html (or another file if you insert the <code>response.view=...</code> in your function, to re-use the same template), which could be like this:</p>
<pre><code><html><head></head>
<body>
{{=message}}
</body>
</html>
</code></pre>
<p>and return a dictionary:</p>
<pre><code>def index():
# ... code to extract the rows
html = B('Results:', rows.xml(), _class='results', _id=1)
return dict(message=html)
</code></pre>
| 2 | 2009-10-11T10:56:26Z | [
"python",
"web2py"
] |
I do urllib2 and I download the htmlSource of the webpage. How do I make this all on 1 line? | 1,550,406 | <pre><code>urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
</code></pre>
<p>How do I make htmlSource in 1 line, instead of many lines?</p>
| -5 | 2009-10-11T10:50:04Z | 1,550,414 | <p>You can't really do that, the only possible thing is put the response and the source on the same line. Or you could use <code>;</code> between statements, but that's ugly.</p>
<p>But more importantly, why would you do that? Why is it better to have it all in on line?</p>
<pre><code>>>> import this
The Zen of Python, by Tim Peters
...
Readability counts.
...
</code></pre>
| 9 | 2009-10-11T10:56:59Z | [
"python"
] |
I do urllib2 and I download the htmlSource of the webpage. How do I make this all on 1 line? | 1,550,406 | <pre><code>urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
</code></pre>
<p>How do I make htmlSource in 1 line, instead of many lines?</p>
| -5 | 2009-10-11T10:50:04Z | 1,550,436 | <p>How to do that in one line? That's what functions are for. Like this:</p>
<pre><code>def getsource(url):
urlReq = urllib2.Request(url)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
return urlResponse.read()
</code></pre>
<p>Now you can do it in one line:</p>
<pre><code>htmlSource = getsource(theurl)
</code></pre>
<p>Done!</p>
<p>Update:</p>
<p>Filtering the htmlSource to be one linebreak (as you now claim you want) is done something like this:</p>
<pre><code>htmlSource = htmlSource.replace('\n', '')
</code></pre>
<p>And you might need</p>
<pre><code>htmlSource = htmlSource.replace('\r', '')
</code></pre>
<p>as well. I sincerely doubt it will speed anything up.</p>
| 6 | 2009-10-11T11:06:50Z | [
"python"
] |
Python: is using "..%(var)s.." % locals() a good practice? | 1,550,479 | <p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p>
<p>I feel it is very agile:</p>
<pre><code>def example():
age = ...
name = ...
print "hello %(name)s you are %(age)s years old" % locals()
</code></pre>
<p>Sometimes I use its cousin:</p>
<pre><code>def example2(obj):
print "The file at %(path)s has %(length)s bytes" % obj.__dict__
</code></pre>
<p>I don't need to create an artificial tuple and count parameters and keep the %s matching positions inside the tuple.</p>
<p>Do you like it? Do/Would you use it? Yes/No, please explain.</p>
| 65 | 2009-10-11T11:27:38Z | 1,550,483 | <p>I think it is a great pattern because you are leveraging built-in functionality to reduce the code you need to write. I personally find it quite Pythonic.</p>
<p>I never write code that I don't need to write - less code is better than more code and this practice of using <code>locals()</code> for example allows me to write less code and is also very easy to read and understand.</p>
| 8 | 2009-10-11T11:28:56Z | [
"python",
"string",
"design-patterns",
"anti-patterns"
] |
Python: is using "..%(var)s.." % locals() a good practice? | 1,550,479 | <p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p>
<p>I feel it is very agile:</p>
<pre><code>def example():
age = ...
name = ...
print "hello %(name)s you are %(age)s years old" % locals()
</code></pre>
<p>Sometimes I use its cousin:</p>
<pre><code>def example2(obj):
print "The file at %(path)s has %(length)s bytes" % obj.__dict__
</code></pre>
<p>I don't need to create an artificial tuple and count parameters and keep the %s matching positions inside the tuple.</p>
<p>Do you like it? Do/Would you use it? Yes/No, please explain.</p>
| 65 | 2009-10-11T11:27:38Z | 1,550,527 | <p>The <code>"%(name)s" % <dictionary></code> or even better, the <code>"{name}".format(<parameters>)</code> have the merit of </p>
<ul>
<li>being more readable than "%0s"</li>
<li>being independent from the argument order</li>
<li>not compelling to use all the arguments in the string</li>
</ul>
<p>I would tend to favour the str.format(), since it should be the way to do that in Python 3 (as per <a href="http://www.python.org/dev/peps/pep-3101/">PEP 3101</a>), and is already available from 2.6. With <code>locals()</code> though, you would have to do this:</p>
<pre><code>print("hello {name} you are {age} years old".format(**locals()))
</code></pre>
| 8 | 2009-10-11T11:54:55Z | [
"python",
"string",
"design-patterns",
"anti-patterns"
] |
Python: is using "..%(var)s.." % locals() a good practice? | 1,550,479 | <p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p>
<p>I feel it is very agile:</p>
<pre><code>def example():
age = ...
name = ...
print "hello %(name)s you are %(age)s years old" % locals()
</code></pre>
<p>Sometimes I use its cousin:</p>
<pre><code>def example2(obj):
print "The file at %(path)s has %(length)s bytes" % obj.__dict__
</code></pre>
<p>I don't need to create an artificial tuple and count parameters and keep the %s matching positions inside the tuple.</p>
<p>Do you like it? Do/Would you use it? Yes/No, please explain.</p>
| 65 | 2009-10-11T11:27:38Z | 1,550,665 | <p>Using the built-in <code>vars([object])</code> (<a href="http://docs.python.org/3.1/library/functions.html#vars">documentation</a>) might make the second look better to you:</p>
<pre><code>def example2(obj):
print "The file at %(path)s has %(length)s bytes" % vars(obj)
</code></pre>
<p>The effect is of course just the same.</p>
| 6 | 2009-10-11T13:15:38Z | [
"python",
"string",
"design-patterns",
"anti-patterns"
] |
Python: is using "..%(var)s.." % locals() a good practice? | 1,550,479 | <p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p>
<p>I feel it is very agile:</p>
<pre><code>def example():
age = ...
name = ...
print "hello %(name)s you are %(age)s years old" % locals()
</code></pre>
<p>Sometimes I use its cousin:</p>
<pre><code>def example2(obj):
print "The file at %(path)s has %(length)s bytes" % obj.__dict__
</code></pre>
<p>I don't need to create an artificial tuple and count parameters and keep the %s matching positions inside the tuple.</p>
<p>Do you like it? Do/Would you use it? Yes/No, please explain.</p>
| 65 | 2009-10-11T11:27:38Z | 1,550,684 | <p>Never in a million years. It's unclear what the context for formatting is: <code>locals</code> could include almost any variable. <code>self.__dict__</code> is not as vague. Perfectly awful to leave future developers scratching their heads over what's local and what's not local.</p>
<p>It's an intentional mystery. Why saddle your organization with future maintenance headaches like that?</p>
| 11 | 2009-10-11T13:22:53Z | [
"python",
"string",
"design-patterns",
"anti-patterns"
] |
Python: is using "..%(var)s.." % locals() a good practice? | 1,550,479 | <p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p>
<p>I feel it is very agile:</p>
<pre><code>def example():
age = ...
name = ...
print "hello %(name)s you are %(age)s years old" % locals()
</code></pre>
<p>Sometimes I use its cousin:</p>
<pre><code>def example2(obj):
print "The file at %(path)s has %(length)s bytes" % obj.__dict__
</code></pre>
<p>I don't need to create an artificial tuple and count parameters and keep the %s matching positions inside the tuple.</p>
<p>Do you like it? Do/Would you use it? Yes/No, please explain.</p>
| 65 | 2009-10-11T11:27:38Z | 1,551,187 | <p>It's OK for small applications and allegedly "one-off" scripts, especially with the <code>vars</code> enhancement mentioned by @kaizer.se and the <code>.format</code> version mentioned by @RedGlyph. </p>
<p>However, for large applications with a long maintenance life and many maintainers this practice can lead to maintenance headaches, and I think that's where @S.Lott's answer is coming from. Let me explain some of the issues involved, as they may not be obvious to anybody who doesn't have the scars from developing and maintaining large applications (or reusable components for such beasts).</p>
<p>In a "serious" application, you would not have your format string hard-coded -- or, if you had, it would be in some form such as <code>_('Hello {name}.')</code>, where the <code>_</code> comes from <a href="http://docs.python.org/library/gettext.html">gettext</a> or similar i18n / L10n frameworks. The point is that such an application (or reusable modules that can happen to be used in such applications) must support internationalization (AKA i18n) and locatization (AKA L10n): you want your application to be able to emit "Hello Paul" in certain countries and cultures, "Hola Paul" in some others, "Ciao Paul" in others yet, and so forth. So, the format string gets more or less automatically substituted with another at runtime, depending on the current localization settings; instead of being hardcoded, it lives in some sort of database. For all intents and purposes, imagine that format string always being a variable, not a string literal.</p>
<p>So, what you have is essentially</p>
<pre><code>formatstring.format(**locals())
</code></pre>
<p>and you can't trivially check exactly <em>what</em> local names the formatting is going to be using. You'd have to open and peruse the L10N database, identify the format strings that are going to be used here in different settings, verify all of them.</p>
<p>So in practice you don't <em>know</em> what local names are going to get used -- which horribly crimps the maintenance of the function. You dare not rename or remove any local variable, as it might horribly break the user experience for users with some (to you) obscure combinaton of language, locale and preferences</p>
<p>If you have superb integration / regression testing, the breakage will be caught before the beta release -- but QA will scream at you and the release will be delayed... and, let's be honest, while aiming for 100% coverage with <em>unit</em> tests is reasonable, it really isn't with <em>integration</em> tests, once you consider the combinatorial explosion of settings [[for L10N and for many more reasons]] and supported versions of all dependencies. So, you just don't blithely go around risking breakages because "they'll be caught in QA" (if you do, you may not last long in an environment that develops large apps or reusable components;-).</p>
<p>So, in practice, you'll never remove the "name" local variable even though the User Experience folks have long switched that greeting to a more appropriate "Welcome, Dread Overlord!" (and suitably L10n'ed versions thereof). All because you went for <code>locals()</code>...</p>
<p>So you're accumulating cruft because of the way you've crimped your ability to maintain and edit your code -- and maybe that "name" local variable only exists because it's been fetched from a DB or the like, so keeping it (or some other local) around is not just cruft, it's reducing your performance too. Is the surface convenience of <code>locals()</code> worth <strong>that</strong>?-)</p>
<p>But wait, there's worse! Among the many useful services a <code>lint</code>-like program (like, for example, <a href="http://www.logilab.org/857">pylint</a>) can do for you, is to warn you about unused local variables (wish it could do it for unused globals as well, but, for reusable components, that's just a tad too hard;-). This way you'll catch most occasional misspellings such as <code>if ...: nmae = ...</code> very rapidly and cheaply, rather than by seeing a unit-test break and doing sleuth work to find out <em>why</em> it broke (you <em>do</em> have obsessive, pervasive unit tests that <strong>would</strong> catch this eventually, right?-) -- lint will tell you about an unused local variable <code>nmae</code> and you will immediately fix it.</p>
<p>But if you have in your code a <code>blah.format(**locals())</code>, or equivalently a <code>blah % locals()</code>... you're SOL, pal!-) How is poor lint going to know whether <code>nmae</code> is in fact an unused variable, or actually it does get used by whatever external function or method you're passing <code>locals()</code> to? It can't -- either it's going to warn anyway (causing a "cry wolf" effect that eventually leads you to ignore or disable such warnings), or it's never going to warn (with the same final effect: no warnings;-).</p>
<p>Compare this to the "explicit is better than implicit" alternative...:</p>
<pre><code>blah.format(name=name)
</code></pre>
<p>There -- none of the maintenance, performance, and am-I-hampering-lint worries, applies any more; bliss! You make it immediately clear to everybody concerned (lint included;-) exactly <em>what</em> local variables are being used, and exactly for what purposes.</p>
<p>I could go on, but I think this post is already pretty long;-).</p>
<p>So, summarizing: "<strong>γνῶθι ÏεαÏ
ÏÏν</strong>!" Hmm, I mean, "know thyself!". And by "thyself" I actually mean "the purpose and scope of your code". If it's a 1-off-or-thereabouts thingy, never going to be i18n'd and L10n'd, will hardly need future maintenance, will never be reused in a broader context, etc, etc, then go ahead and use <code>locals()</code> for its small but neat convenience; if you know otherwise, or even if you're not entirely certain, err on the side of caution, and make things more explicit -- suffer the small inconvenience of spelling out exactly what you're going, and enjoy all the resulting advantages.</p>
<p>BTW, this is just one of the examples where Python is striving to support both "small, one-off, exploratory, maybe interactive" programming (by allowing and supporting risky conveniences that extend well beyond <code>locals()</code> -- think of <code>import *</code>, <code>eval</code>, <code>exec</code>, and several other ways you can mush up namespaces and risk maintenance impacts for the sake of convenience), as well as "large, reusable, enterprise-y" apps and components. It can do a pretty good job at both, but only if you "know thyself" and avoid using the "convenience" parts except when you're absolutely certain you can in fact afford them. More often than not, the key consideration is, "what does this do to my namespaces, and awareness of their formation and use by the compiler, lint &c, human readers and maintainers, and so on?". </p>
<p>Remember, "Namespaces are one honking great idea -- let's do more of those!" is how the Zen of Python concludes... but Python, as a "language for consenting adults", lets <strong>you</strong> define the boundaries of what that implies, as a consequence of your development environment, targets, and practices. Use this power responsibly!-)</p>
| 80 | 2009-10-11T17:14:09Z | [
"python",
"string",
"design-patterns",
"anti-patterns"
] |
Python: is using "..%(var)s.." % locals() a good practice? | 1,550,479 | <p>I discovered this pattern (or anti-pattern) and I am very happy with it.</p>
<p>I feel it is very agile:</p>
<pre><code>def example():
age = ...
name = ...
print "hello %(name)s you are %(age)s years old" % locals()
</code></pre>
<p>Sometimes I use its cousin:</p>
<pre><code>def example2(obj):
print "The file at %(path)s has %(length)s bytes" % obj.__dict__
</code></pre>
<p>I don't need to create an artificial tuple and count parameters and keep the %s matching positions inside the tuple.</p>
<p>Do you like it? Do/Would you use it? Yes/No, please explain.</p>
| 65 | 2009-10-11T11:27:38Z | 6,106,580 | <p>Regarding the "cousin", instead of <code>obj.__dict__</code>, it looks a lot better with new string formatting:</p>
<pre><code>def example2(obj):
print "The file at {o.path} has {o.length} bytes".format(o=obj)
</code></pre>
<p>I use this a lot for <strong>repr</strong> methods, e.g.</p>
<pre><code>def __repr__(self):
return "{s.time}/{s.place}/{s.warning}".format(s=self)
</code></pre>
| 8 | 2011-05-24T06:32:44Z | [
"python",
"string",
"design-patterns",
"anti-patterns"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.