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
list
Converting a String to Dictionary?
988,228
<p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p> <pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" </code></pre> <p>I prefer not to use <code>eval</code>. What else can I use?</p> <p>The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.</p>
327
2009-06-12T18:25:02Z
25,326,140
<p>using <code>json.loads</code></p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; h = '{"foo":"bar", "foo2":"bar2"}' &gt;&gt;&gt; type(h) &lt;type 'str'&gt; &gt;&gt;&gt; d = json.loads(h) &gt;&gt;&gt; d {u'foo': u'bar', u'foo2': u'bar2'} &gt;&gt;&gt; type(d) &lt;type 'dict'&gt; </code></pre>
29
2014-08-15T12:07:45Z
[ "python", "string", "dictionary" ]
Converting a String to Dictionary?
988,228
<p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p> <pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" </code></pre> <p>I prefer not to use <code>eval</code>. What else can I use?</p> <p>The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.</p>
327
2009-06-12T18:25:02Z
25,527,687
<p>Use Json. the ast library consumes a lot of memory and and slower. I have a process that needs to read a text file of 156Mb. Ast with 5 minutes delay for the conversion dictionary Json and 1 minutes using 60% less memory!</p>
11
2014-08-27T12:50:13Z
[ "python", "string", "dictionary" ]
Converting a String to Dictionary?
988,228
<p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p> <pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" </code></pre> <p>I prefer not to use <code>eval</code>. What else can I use?</p> <p>The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.</p>
327
2009-06-12T18:25:02Z
38,066,510
<p>To OP's example:</p> <pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" </code></pre> <p>We can use <a href="https://pypi.python.org/pypi/PyYAML" rel="nofollow">Yaml</a> to deal with this kind of non-standard json in string:</p> <pre><code>&gt;&gt;&gt; import yaml &gt;&gt;&gt; s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" &gt;&gt;&gt; s "{'muffin' : 'lolz', 'foo' : 'kitty'}" &gt;&gt;&gt; yaml.load(s) {'muffin': 'lolz', 'foo': 'kitty'} </code></pre>
0
2016-06-28T03:20:03Z
[ "python", "string", "dictionary" ]
Converting a String to Dictionary?
988,228
<p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p> <pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" </code></pre> <p>I prefer not to use <code>eval</code>. What else can I use?</p> <p>The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.</p>
327
2009-06-12T18:25:02Z
38,671,887
<pre><code>string = "{'server1':'value','server2':'value'}" #Now removing { and } s = string.replace("{" ,""); finalstring = s.replace("}" , ""); #Splitting the string based on , we get key value pairs list = finalstring.split(",") dict ={} for i in list: #Get Key Value pairs separately to store in dictionary keyvalue = i.split(":") #Replacing the single quotes in the leading. m= keyvalue[0].strip('\'') m = m.replace("\"", "") dict[m] = keyvalue[1].strip('"\'') print dict </code></pre>
0
2016-07-30T08:19:39Z
[ "python", "string", "dictionary" ]
Efficient Tuple List Comparisons
988,346
<p>I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.</p> <p>I have a large list of four element tuples in the format:</p> <p>(ID number, Type, Start Index, End Index) </p> <p>Previously in the code, I have searched through thousands of blocks of text for two specific types of substrings. These tuples store in which large chunk of text the substring was found, which of the two types of substrings it is, and the start and end index of this substring.</p> <p>The final goal is to look through this list to find all instances where a type 1 substring occurs before a type 2 substring in a block of text with the same ID. Then I would like to store these objects in the format (ID, Type 1, Start, End, Type2, Start, End).</p> <p>I've tried to mess around with a bunch of stuff that was super inefficient. I have the list sorted by ID then Start Index, and if been trying varying ways of popping the items off the list for comparisons. I have to imagine there is a more elegant solution. Any brilliant people out there wish to assist my tired brain???</p> <p>Thanks in advance</p>
2
2009-06-12T18:47:07Z
988,455
<p><strong>Solution:</strong></p> <pre><code>result = [(l1 + l2[1:]) for l1 in list1 for l2 in list2 if (l1[0] == l2[0] and l1[3] &lt; l2[2]) ] </code></pre> <p>... with test code:</p> <pre><code>list1 = [(1, 'Type1', 20, 30,), (2, 'Type1', 20, 30,), (3, 'Type1', 20, 30,), (4, 'Type1', 20, 30,), (5, 'Type1', 20, 30,), (6, 'Type1', 20, 30,), # does not have Type2 (8, 'Type1', 20, 30,), # multiple (8, 'Type1', 25, 35,), # multiple (8, 'Type1', 50, 55,), # multiple ] list2 = [(1, 'Type2', 40, 50,), # after (2, 'Type2', 10, 15,), # before (3, 'Type2', 25, 28,), # inside (4, 'Type2', 25, 35,), # inside-after (4, 'Type2', 15, 25,), # inside-before (7, 'Type2', 20, 30,), # does not have Type1 (8, 'Type2', 40, 50,), # multiple (8, 'Type2', 60, 70,), # multiple (8, 'Type2', 80, 90,), # multiple ] result = [(l1 + l2[1:]) for l1 in list1 for l2 in list2 if (l1[0] == l2[0] and l1[3] &lt; l2[2]) ] print '\n'.join(str(r) for r in result) </code></pre> <p>It is not clear what result would you like if there is more then one occurrence of both Type1 and Type2 within the same text ID. Please specify. </p>
1
2009-06-12T19:04:22Z
[ "python", "algorithm", "list", "tuples" ]
Efficient Tuple List Comparisons
988,346
<p>I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.</p> <p>I have a large list of four element tuples in the format:</p> <p>(ID number, Type, Start Index, End Index) </p> <p>Previously in the code, I have searched through thousands of blocks of text for two specific types of substrings. These tuples store in which large chunk of text the substring was found, which of the two types of substrings it is, and the start and end index of this substring.</p> <p>The final goal is to look through this list to find all instances where a type 1 substring occurs before a type 2 substring in a block of text with the same ID. Then I would like to store these objects in the format (ID, Type 1, Start, End, Type2, Start, End).</p> <p>I've tried to mess around with a bunch of stuff that was super inefficient. I have the list sorted by ID then Start Index, and if been trying varying ways of popping the items off the list for comparisons. I have to imagine there is a more elegant solution. Any brilliant people out there wish to assist my tired brain???</p> <p>Thanks in advance</p>
2
2009-06-12T18:47:07Z
988,462
<p>I don't know how many types you have. But If we assume you have only type 1 and type 2, then it sounds like a problem similar to a merge sort. Doing it with a merge sort, you make a single pass through the list. </p> <p>Take two indexes, one for type 1 and one for type 2 (I1, I2). Sort the list by id, start1. Start I1 as the first instance of type1, and I2 as zero. If I1.id &lt; I2.Id then increment I1. If I2.id &lt; I1.id then increment I2. If I1.id = I2.id then check iStart. </p> <p>I1 can only stop on a type one record and I2 can only stop on a type 2 record. Keep incrementing the index till it lands on an appropriate record.</p> <p>You can make some assumptions to make this faster. When you find an block that succeeds, you can move I1 to the next block. Whenever I2 &lt; I1, you can start I2 at I1 + 1 (WOOPS MAKE SURE YOU DONT DO THIS, BECAUSE YOU WOULD MISS THE FAILURE CASE!) Whenever you detect an obvious failure case, move I1 and I2 to the next block (on appropriate recs of course).</p>
1
2009-06-12T19:05:42Z
[ "python", "algorithm", "list", "tuples" ]
Efficient Tuple List Comparisons
988,346
<p>I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.</p> <p>I have a large list of four element tuples in the format:</p> <p>(ID number, Type, Start Index, End Index) </p> <p>Previously in the code, I have searched through thousands of blocks of text for two specific types of substrings. These tuples store in which large chunk of text the substring was found, which of the two types of substrings it is, and the start and end index of this substring.</p> <p>The final goal is to look through this list to find all instances where a type 1 substring occurs before a type 2 substring in a block of text with the same ID. Then I would like to store these objects in the format (ID, Type 1, Start, End, Type2, Start, End).</p> <p>I've tried to mess around with a bunch of stuff that was super inefficient. I have the list sorted by ID then Start Index, and if been trying varying ways of popping the items off the list for comparisons. I have to imagine there is a more elegant solution. Any brilliant people out there wish to assist my tired brain???</p> <p>Thanks in advance</p>
2
2009-06-12T18:47:07Z
988,509
<p>I recently did something like this. I might not be understanding your problem but here goes.</p> <p>I would use a dictionary:</p> <pre><code>from collections import defaultdict: masterdictType1=defaultDict(dict) masterdictType2=defaultdict(dict) for item in myList: if item[1]=Type1 if item[0] not in masterdictType1: masterdictType1[item[0]]['begin']=item[2] # start index masterdictType1[item[0]]['end']=item[-1] # end index if item[1]=Type2 if item[0] not in masterdictType2: masterdictType2[item[0]]['begin']=item[2] # start index masterdictType2[item[0]]['end']=item[-1] # end index joinedDict=defaultdict(dict) for id in masterdictType1: if id in masterdictType2: if masterdictType1[id]['begin']&lt;masterdictType2[id]['begin']: joinedDict[id]['Type1Begin']=masterdictType1[id]['begin'] joinedDict[id]['Type1End']=masterdictType1[id]['end'] joinedDict[id]['Type2Begin']=masterdictType2[id]['begin'] joinedDict[id]['Type2End']=masterdictType2[id]['end'] </code></pre> <p>This gives you explicitness and gives you something that is durable since you can pickle the dictionary easily.</p>
1
2009-06-12T19:14:35Z
[ "python", "algorithm", "list", "tuples" ]
Efficient Tuple List Comparisons
988,346
<p>I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.</p> <p>I have a large list of four element tuples in the format:</p> <p>(ID number, Type, Start Index, End Index) </p> <p>Previously in the code, I have searched through thousands of blocks of text for two specific types of substrings. These tuples store in which large chunk of text the substring was found, which of the two types of substrings it is, and the start and end index of this substring.</p> <p>The final goal is to look through this list to find all instances where a type 1 substring occurs before a type 2 substring in a block of text with the same ID. Then I would like to store these objects in the format (ID, Type 1, Start, End, Type2, Start, End).</p> <p>I've tried to mess around with a bunch of stuff that was super inefficient. I have the list sorted by ID then Start Index, and if been trying varying ways of popping the items off the list for comparisons. I have to imagine there is a more elegant solution. Any brilliant people out there wish to assist my tired brain???</p> <p>Thanks in advance</p>
2
2009-06-12T18:47:07Z
988,650
<p>Assuming there are lots of entries for each ID, I would (pseudo-code)</p> <pre> for each ID: for each type2 substring of that ID: store it in an ordered list, sorted by start point for each type1 substring of that ID: calculate the end point (or whatever) look it up in the ordered list if there's anything to the right, you have a hit </pre> <p>So, if you have control of the initial sort, then instead of (ID, start), you want them sorted by ID, then by type (2 before 1). Then within the type, sort by start point for type2, and the offset you're going to compare for type1. I'm not sure whether by "A before B" you mean "A starts before B starts" or "A ends before B starts", but do whatever's appropriate. </p> <p>Then you can do the whole operation by running over the list once. You don't need to actually construct an index of type2s, because they're already in order. Since the type1s are sorted too, you can do each lookup with a linear or binary search starting from the result of the previous search. Use a linear search if there are lots of type1s compared with type2s (so results are close together), and a binary search if there are lots of type2s compared with type1s (so results are sparse). Or just stick with the linear search as it's simpler - this lookup is the inner loop, but its performance might not be critical.</p> <p>If you don't have control of the sort, then I don't know whether it's faster to build the list of type2 substrings for each ID as you go; or to sort the entire list before you start into the required order; or just to work with what you've got, by writing a "lookup" that ignores the type1 entries when searching through the type2s (which are already sorted as required). Test it, or just do whatever results in clearer code. Even without re-sorting, you can still use the merge-style optimisation unless "sorted by start index" is the wrong thing for the type1s.</p>
0
2009-06-12T19:38:37Z
[ "python", "algorithm", "list", "tuples" ]
Efficient Tuple List Comparisons
988,346
<p>I am kind of hitting a wall on this problem and I was wondering if some fresh brains could help me out.</p> <p>I have a large list of four element tuples in the format:</p> <p>(ID number, Type, Start Index, End Index) </p> <p>Previously in the code, I have searched through thousands of blocks of text for two specific types of substrings. These tuples store in which large chunk of text the substring was found, which of the two types of substrings it is, and the start and end index of this substring.</p> <p>The final goal is to look through this list to find all instances where a type 1 substring occurs before a type 2 substring in a block of text with the same ID. Then I would like to store these objects in the format (ID, Type 1, Start, End, Type2, Start, End).</p> <p>I've tried to mess around with a bunch of stuff that was super inefficient. I have the list sorted by ID then Start Index, and if been trying varying ways of popping the items off the list for comparisons. I have to imagine there is a more elegant solution. Any brilliant people out there wish to assist my tired brain???</p> <p>Thanks in advance</p>
2
2009-06-12T18:47:07Z
988,992
<p>Could I check, by <em>before</em>, do you mean <em>immediately</em> before (ie. <code>t1_a, t2_b, t2_c, t2_d</code> should just give the pair <code>(t1_a, t2_b)</code>, or do you want all pairs where a type1 value occurs <em>anywhere</em> before a type2 one within the same block. (ie <code>(t1_a, t2_b), (t1_a, t2_c), (t1_a, t2_d)</code> for the previous example).</p> <p>In either case, you should be able to do this with a single pass over your list (assuming sorted by id, then start index).</p> <p>Here's a solution assuming the second option (every pair):</p> <pre><code>import itertools, operator def find_t1_t2(seq): """Find every pair of type1, type2 values where the type1 occurs before the type2 within a block with the same id. Assumes sequence is ordered by id, then start location. Generates a sequence of tuples of the type1,type2 entries. """ for group, items in itertools.groupby(seq, operator.itemgetter(0)): type1s=[] for item in items: if item[1] == TYPE1: type1s.append(item) elif item[1] == TYPE2: for t1 in type1s: yield t1 + item[1:] </code></pre> <p>If it's just immediately before, it's even simpler: just keep track of the previous item and yield the tuple whenever it is type1 and the current one is type2.</p> <p>Here's an example of usage, and the results returned:</p> <pre><code>l=[[1, TYPE1, 10, 15], [1, TYPE2, 20, 25], # match with first [1, TYPE2, 30, 35], # match with first (2 total matches) [2, TYPE2, 10, 15], # No match [2, TYPE1, 20, 25], [2, TYPE1, 30, 35], [2, TYPE2, 40, 45], # Match with previous 2 type1s. [2, TYPE1, 50, 55], [2, TYPE2, 60, 65], # Match with 3 previous type1 entries (5 total) ] for x in find_t1_t2(l): print x </code></pre> <p>This returns:</p> <pre><code>[1, 'type1', 10, 15, 'type2', 20, 25] [1, 'type1', 10, 15, 'type2', 30, 35] [2, 'type1', 20, 25, 'type2', 40, 45] [2, 'type1', 30, 35, 'type2', 40, 45] [2, 'type1', 20, 25, 'type2', 60, 65] [2, 'type1', 30, 35, 'type2', 60, 65] [2, 'type1', 50, 55, 'type2', 60, 65] </code></pre>
0
2009-06-12T20:53:47Z
[ "python", "algorithm", "list", "tuples" ]
Python string find
989,170
<p>I want to find a certain substring inside a string. The string is stored in a list of strings. How can i do it? </p>
2
2009-06-12T21:34:52Z
989,179
<p>So you're searching for all the strings in a list of strings that contain a certain substring? This will do it:</p> <pre><code>DATA = ['Hello', 'Python', 'World'] SEARCH_STRING = 'n' print [s for s in DATA if SEARCH_STRING in s] # Prints ['Python'] </code></pre> <p><strong>Edit</strong> at Andrew's suggestion: You should read that <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> as "Make a list of all the strings in the list <code>DATA</code> where <code>SEARCH_STRING</code> appears somewhere in the string."</p>
4
2009-06-12T21:37:07Z
[ "python" ]
Python string find
989,170
<p>I want to find a certain substring inside a string. The string is stored in a list of strings. How can i do it? </p>
2
2009-06-12T21:34:52Z
989,184
<p>have you looked <a href="http://docs.python.org/library/string.html" rel="nofollow">here</a> it is very simple to do, just do a search in the python documentation</p>
0
2009-06-12T21:38:37Z
[ "python" ]
What's the point of os.error?
989,259
<p>Why does Python's <code>os</code> module contain <a href="http://docs.python.org/library/os.html#os.error"><code>error</code>, an alias for <code>OSError</code></a>?</p> <p>Is there a reason to ever spell it <code>os.error</code>? <code>OSError</code> certainly seems more consistent with all the other built-in exceptions.</p> <p>I hoped <code>os.py</code> would shed some light, but it uses <code>error</code> sometimes and <code>OSError</code> others.</p> <p>It seems goofy to have an extra name for one of the exceptions, yet it survives into Python 3.0. What am I missing?</p>
7
2009-06-12T21:58:41Z
989,266
<p>The documentation for <a href="http://docs.python.org/library/exceptions.html#exceptions.OSError"><code>OSError</code></a> says that it was added in version 1.5.2. My guess is that <code>error</code> predates this a little and in an effort to remain backwards-compatible to code written for Python before 1.5.2 <code>error</code> was made an alias for <code>OSError</code>.</p>
6
2009-06-12T22:02:24Z
[ "python" ]
python string input problem with whitespace!
989,276
<p>my input is something like this </p> <p>23 + 45 = astart</p> <p>for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this </p> <p>SyntaxError: invalid syntax</p> <p>the code is this </p> <pre><code>k=raw_input() a,b=(str(i) for i in k.split(' + ')) b,c=(str(i) for i in b.split(' = ')) </code></pre> <p>its always number + number = astar</p> <p>its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error </p>
1
2009-06-12T22:05:41Z
989,293
<p>Edit: as pointed out by Triptych, the generator object isn't the problem. The partition solution is still good and holds even for invalid inputs</p> <p><strike>calling <code>(... for ...)</code> only returns a generator object, not a tuple</p> <p>try one of the following:</p> <pre><code>a,b=[str(i) for i in k.split(' + ')] a,b=list(str(i) for i in k.split(' + ')) </code></pre> <p>they return a list which can be unpacked (assuming one split) </strike></p> <p>or use str.partition assuming 2.5 or greater:</p> <pre><code>a, serperator, b = k.partition('+') </code></pre> <p>which will always return a 3 tuple even if the string isn't found</p> <p>Edit: and if you don't want the spaces in your input use the <a href="http://docs.python.org/library/stdtypes.html#str.strip" rel="nofollow">strip</a> function</p> <pre><code>a = a.strip() b = b.strip() </code></pre> <p>Edit: fixed str.partition method, had wrong function name for some reason</p>
1
2009-06-12T22:10:04Z
[ "python" ]
python string input problem with whitespace!
989,276
<p>my input is something like this </p> <p>23 + 45 = astart</p> <p>for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this </p> <p>SyntaxError: invalid syntax</p> <p>the code is this </p> <pre><code>k=raw_input() a,b=(str(i) for i in k.split(' + ')) b,c=(str(i) for i in b.split(' = ')) </code></pre> <p>its always number + number = astar</p> <p>its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error </p>
1
2009-06-12T22:05:41Z
989,405
<p>Testing with Python 2.5.2, your code ran OK as long as I only had the same spacing on either side of the + and = in the code and input.</p> <p>You appear to have two spaces on either side of them in the code, but only one on either side in the input. Also - you do not have to use the str(i) in a generator. You can do it like a,b=k.split(' + ')</p> <pre><code>My cut and pastes: My test script: print 'Enter input #1:' k=raw_input() a,b=(str(i) for i in k.split(' + ')) b,c=(str(i) for i in b.split(' = ')) print 'Here are the resulting values:' print a print b print c print 'Enter input #2:' k=raw_input() a,b=k.split(' + ') b,c=b.split(' = ') print 'Here are the resulting values:' print a print b print c From the interpreter: &gt;&gt;&gt; Enter input #1: 23 + 45 = astart Here are the resulting values: 23 45 astart Enter input #2: 23 + 45 = astart Here are the resulting values: 23 45 astart &gt;&gt;&gt; </code></pre>
2
2009-06-12T22:46:53Z
[ "python" ]
python string input problem with whitespace!
989,276
<p>my input is something like this </p> <p>23 + 45 = astart</p> <p>for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this </p> <p>SyntaxError: invalid syntax</p> <p>the code is this </p> <pre><code>k=raw_input() a,b=(str(i) for i in k.split(' + ')) b,c=(str(i) for i in b.split(' = ')) </code></pre> <p>its always number + number = astar</p> <p>its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error </p>
1
2009-06-12T22:05:41Z
989,566
<p>I think I'd just use a simple regular expression:</p> <pre><code># Set up a few regular expressions parser = re.compile("(\d+)\+(\d+)=(.+)") spaces = re.compile("\s+") # Grab input input = raw_input() # Remove all whitespace input = spaces.sub('',input) # Parse away num1, num2, result = m.match(input) </code></pre>
1
2009-06-13T00:05:54Z
[ "python" ]
python string input problem with whitespace!
989,276
<p>my input is something like this </p> <p>23 + 45 = astart</p> <p>for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this </p> <p>SyntaxError: invalid syntax</p> <p>the code is this </p> <pre><code>k=raw_input() a,b=(str(i) for i in k.split(' + ')) b,c=(str(i) for i in b.split(' = ')) </code></pre> <p>its always number + number = astar</p> <p>its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error </p>
1
2009-06-12T22:05:41Z
989,621
<p>You could just use:</p> <pre><code>a, b, c = raw_input().replace('+',' ').replace('=', ' ').split() </code></pre> <p>Or [Edited to add] - here's another one that avoids creating the extra intermediate strings:</p> <pre><code>a, b, c = raw_input().split()[::2] </code></pre> <p>Hrm - just realized that second one requires spaces, though, so not as good.</p>
1
2009-06-13T00:36:49Z
[ "python" ]
python string input problem with whitespace!
989,276
<p>my input is something like this </p> <p>23 + 45 = astart</p> <p>for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this </p> <p>SyntaxError: invalid syntax</p> <p>the code is this </p> <pre><code>k=raw_input() a,b=(str(i) for i in k.split(' + ')) b,c=(str(i) for i in b.split(' = ')) </code></pre> <p>its always number + number = astar</p> <p>its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error </p>
1
2009-06-12T22:05:41Z
989,823
<p>Rather than trying to solve your problem, I thought I'd point out a basic step you could take to try to understand why you're getting a syntax error: print your intermediate products. </p> <pre><code>k=raw_input() print k.split(' + ') a,b=(str(i) for i in k.split(' + ')) print b.split(' = ') b,c=(str(i) for i in b.split(' = ')) </code></pre> <p>This will show you the actual list elements produced by the split, which might shed some light on the problem you're having.</p> <p>I'm not normally a fan of debugging by print statement, but one of the advantages that Python has is that it's so easy to fire up the interpreter and just mess around interactively, one statement at a time, to see what's going on. </p>
0
2009-06-13T03:01:07Z
[ "python" ]
Getting the first and last item in a python for loop
989,665
<p>Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?</p> <pre><code>from calendar import Calendar cal = Calendar(6) month_dates = cal.itermonthdates(year, month) for date in month_dates: if (is first item): # this is fake month_start = date if (is last item): # so is this month_end = date </code></pre> <p>This code is attempting to get the first day of the week the month ends on, and the last day of the week the month ends on. Example: for June, month-start should evaluate to 5/31/09. Even though it's technically a day in May, it's the first day of the week that June begins on.</p> <p>Month-dates is a generator so i can't do the [:-1] thing. What's a better way to handle this?</p>
6
2009-06-13T00:57:36Z
989,673
<p>How about this?</p> <pre><code>for i, date in enumerate(month_dates): if i == 0: month_start = date month_end = date </code></pre> <p><code>enumerate()</code> lets you find the first one, and the <code>date</code> variable falls out of the loop to give you the last one.</p>
10
2009-06-13T01:02:34Z
[ "python", "for-loop" ]
Getting the first and last item in a python for loop
989,665
<p>Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?</p> <pre><code>from calendar import Calendar cal = Calendar(6) month_dates = cal.itermonthdates(year, month) for date in month_dates: if (is first item): # this is fake month_start = date if (is last item): # so is this month_end = date </code></pre> <p>This code is attempting to get the first day of the week the month ends on, and the last day of the week the month ends on. Example: for June, month-start should evaluate to 5/31/09. Even though it's technically a day in May, it's the first day of the week that June begins on.</p> <p>Month-dates is a generator so i can't do the [:-1] thing. What's a better way to handle this?</p>
6
2009-06-13T00:57:36Z
989,674
<p>I would just force it into a list at the beginning:</p> <pre><code>from calendar import Calendar, SUNDAY cal = Calendar(SUNDAY) month_dates = list(cal.itermonthdates(year, month)) month_start = month_dates[0] month_end = month_dates[-1] </code></pre> <p>Since there can only be 42 days (counting leading and tailing context), this has negligible performance impact.</p> <p>Also, using SUNDAY is better than a magic number.</p>
10
2009-06-13T01:02:49Z
[ "python", "for-loop" ]
Getting the first and last item in a python for loop
989,665
<p>Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?</p> <pre><code>from calendar import Calendar cal = Calendar(6) month_dates = cal.itermonthdates(year, month) for date in month_dates: if (is first item): # this is fake month_start = date if (is last item): # so is this month_end = date </code></pre> <p>This code is attempting to get the first day of the week the month ends on, and the last day of the week the month ends on. Example: for June, month-start should evaluate to 5/31/09. Even though it's technically a day in May, it's the first day of the week that June begins on.</p> <p>Month-dates is a generator so i can't do the [:-1] thing. What's a better way to handle this?</p>
6
2009-06-13T00:57:36Z
989,752
<p>For this specific problem, I think I would go with Matthew Flaschen's solution. It seems the most straightforward to me.</p> <p>If your question is meant to be taken more generally, though, for any generator (with an unknown and possibly large number of elements), then something more like RichieHindle's approach may be better. My slight modification on his solution is not to enumerate and test for element 0, but rather just grab the first element explicitly:</p> <pre><code>month_dates = cal.itermonthdates(year, month) month_start = month_dates.next() for date in month_dates: pass month_end = date </code></pre>
2
2009-06-13T01:58:39Z
[ "python", "for-loop" ]
Getting the first and last item in a python for loop
989,665
<p>Is there an elegant and pythonic way to trap the first and last item in a for loop which is iterating over a generator?</p> <pre><code>from calendar import Calendar cal = Calendar(6) month_dates = cal.itermonthdates(year, month) for date in month_dates: if (is first item): # this is fake month_start = date if (is last item): # so is this month_end = date </code></pre> <p>This code is attempting to get the first day of the week the month ends on, and the last day of the week the month ends on. Example: for June, month-start should evaluate to 5/31/09. Even though it's technically a day in May, it's the first day of the week that June begins on.</p> <p>Month-dates is a generator so i can't do the [:-1] thing. What's a better way to handle this?</p>
6
2009-06-13T00:57:36Z
989,772
<p>Richie's got the right idea. Simpler:</p> <pre><code>month_dates = cal.itermonthdates(year, month) month_start = month_dates.next() for month_end in month_dates: pass # bletcherous </code></pre>
11
2009-06-13T02:20:45Z
[ "python", "for-loop" ]
Python and psycopg2 - raw sql select from table with integer criteria
989,833
<p>It should be simple, bit I've spent the last hour searching for the answer. This is using psycopg2 on python 2.6. </p> <p>I need something like this:</p> <pre><code> special_id = 5 sql = """ select count(*) as ct, from some_table tbl where tbl.id = %(the_id) """ cursor = connection.cursor() cursor.execute(sql, {"the_id" : special_id}) </code></pre> <p>I cannot get this to work. Were <code>special_id</code> a string, I could replace <code>%(the_id)</code> with <code>%(the_id)s</code> and things work well. However, I want it to use the integer so that it hits my indexes correctly. </p> <p>There is a surprising lack of specific information on psycopg2 on the internet. I hope someone has an answer to this seemingly simple question. </p>
0
2009-06-13T03:11:52Z
989,843
<p>Per <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">PEP 249</a>, since in psycopg2 <code>paramstyle</code> is <code>pyformat</code>, you need to use <code>%(the_id)s</code> even for non-strings -- trust it to do the right thing.</p> <p>BTW, internet searches will work better if you use the correct spelling (no <code>h</code> there), but even if you mis-spelled, I'm surprised you didn't get a "did you mean" hint (I did when I deliberately tried!).</p>
2
2009-06-13T03:18:53Z
[ "python" ]
How do I draw out specific data from an opened url in Python using urllib2?
989,872
<p>I'm new to Python and am playing around with making a very basic web crawler. For instance, I have made a simple function to load a page that shows the high scores for an online game. So I am able to get the source code of the html page, but I need to draw specific numbers from that page. For instance, the webpage looks like this:</p> <p><a href="http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13" rel="nofollow">http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13</a></p> <p>where 'bigdrizzle13' is the unique part of the link. The numbers on that page need to be drawn out and returned. Essentially, I want to build a program that all I would have to do is type in 'bigdrizzle13' and it could output those numbers. </p>
3
2009-06-13T03:38:04Z
989,886
<p>You can use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> to parse the HTML.</p>
3
2009-06-13T03:41:54Z
[ "python", "urllib2" ]
How do I draw out specific data from an opened url in Python using urllib2?
989,872
<p>I'm new to Python and am playing around with making a very basic web crawler. For instance, I have made a simple function to load a page that shows the high scores for an online game. So I am able to get the source code of the html page, but I need to draw specific numbers from that page. For instance, the webpage looks like this:</p> <p><a href="http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13" rel="nofollow">http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13</a></p> <p>where 'bigdrizzle13' is the unique part of the link. The numbers on that page need to be drawn out and returned. Essentially, I want to build a program that all I would have to do is type in 'bigdrizzle13' and it could output those numbers. </p>
3
2009-06-13T03:38:04Z
989,920
<p>As another poster mentioned, <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> is a wonderful tool for this job. </p> <p>Here's the entire, ostentatiously-commented program. It could use a lot of error tolerance, but as long as you enter a valid username, it will pull all the scores from the corresponding web page. </p> <p>I tried to comment as well as I could. If you're fresh to BeautifulSoup, I highly recommend working through my example with the <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html">BeautifulSoup documentation</a> handy. </p> <p><strong>The whole program...</strong></p> <pre><code>from urllib2 import urlopen from BeautifulSoup import BeautifulSoup import sys URL = "http://hiscore.runescape.com/hiscorepersonal.ws?user1=" + sys.argv[1] # Grab page html, create BeatifulSoup object html = urlopen(URL).read() soup = BeautifulSoup(html) # Grab the &lt;table id="mini_player"&gt; element scores = soup.find('table', {'id':'mini_player'}) # Get a list of all the &lt;tr&gt;s in the table, skip the header row rows = scores.findAll('tr')[1:] # Helper function to return concatenation of all character data in an element def parse_string(el): text = ''.join(el.findAll(text=True)) return text.strip() for row in rows: # Get all the text from the &lt;td&gt;s data = map(parse_string, row.findAll('td')) # Skip the first td, which is an image data = data[1:] # Do something with the data... print data </code></pre> <p><strong>And here's a test run.</strong></p> <pre><code>&gt; test.py bigdrizzle13 [u'Overall', u'87,417', u'1,784', u'78,772,017'] [u'Attack', u'140,903', u'88', u'4,509,031'] [u'Defence', u'123,057', u'85', u'3,449,751'] [u'Strength', u'325,883', u'84', u'3,057,628'] [u'Hitpoints', u'245,982', u'85', u'3,571,420'] [u'Ranged', u'583,645', u'71', u'856,428'] [u'Prayer', u'227,853', u'62', u'357,847'] [u'Magic', u'368,201', u'75', u'1,264,042'] [u'Cooking', u'34,754', u'99', u'13,192,745'] [u'Woodcutting', u'50,080', u'93', u'7,751,265'] [u'Fletching', u'53,269', u'99', u'13,051,939'] [u'Fishing', u'5,195', u'99', u'14,512,569'] [u'Firemaking', u'46,398', u'88', u'4,677,933'] [u'Crafting', u'328,268', u'62', u'343,143'] [u'Smithing', u'39,898', u'77', u'1,561,493'] [u'Mining', u'31,584', u'85', u'3,331,051'] [u'Herblore', u'247,149', u'52', u'135,215'] [u'Agility', u'225,869', u'60', u'276,753'] [u'Thieving', u'292,638', u'56', u'193,037'] [u'Slayer', u'113,245', u'73', u'998,607'] [u'Farming', u'204,608', u'51', u'115,507'] [u'Runecraft', u'38,369', u'71', u'880,789'] [u'Hunter', u'384,920', u'53', u'139,030'] [u'Construction', u'232,379', u'52', u'125,708'] [u'Summoning', u'87,236', u'64', u'419,086'] </code></pre> <p>Voila :)</p>
11
2009-06-13T03:55:17Z
[ "python", "urllib2" ]
How to find out the arity of a method in Python
990,016
<p>I'd like to find out the arity of a method in Python (the number of parameters that it receives). Right now I'm doing this:</p> <pre><code>def arity(obj, method): return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self class Foo: def bar(self, bla): pass arity(Foo(), "bar") # =&gt; 1 </code></pre> <p>I'd like to be able to achieve this:</p> <pre><code>Foo().bar.arity() # =&gt; 1 </code></pre> <p><strong>Update</strong>: Right now the above function fails with built-in types, any help on this would also be appreciated:</p> <pre><code> # Traceback (most recent call last): # File "bla.py", line 10, in &lt;module&gt; # print arity('foo', 'split') # =&gt; # File "bla.py", line 3, in arity # return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self # AttributeError: 'method_descriptor' object has no attribute 'func_co </code></pre>
25
2009-06-13T05:07:17Z
990,022
<p>Module <code>inspect</code> from Python's standard library is your friend -- see <a href="http://docs.python.org/library/inspect.html">the online docs</a>! <code>inspect.getargspec(func)</code> returns a tuple with four items, <code>args, varargs, varkw, defaults</code>: <code>len(args)</code> is the "primary arity", but arity can be anything from that to infinity if you have <code>varargs</code> and/or <code>varkw</code> not <code>None</code>, and some arguments may be omitted (and defaulted) if <code>defaults</code> is not <code>None</code>. How you turn that into a single number, beats me, but presumably you have your ideas in the matter!-)</p> <p>This applies to Python-coded functions, but not to C-coded ones. Nothing in the Python C API lets C-coded functions (including built-ins) expose their signature for introspection, except via their docstring (or optionally via <strong>annotations</strong> in Python 3); so, you <em>will</em> need to fall back to docstring parsing as a last ditch if other approaches fail (of course, the docstring might be missing too, in which case the function will remain a mystery).</p>
38
2009-06-13T05:13:14Z
[ "python", "metaprogramming" ]
How to find out the arity of a method in Python
990,016
<p>I'd like to find out the arity of a method in Python (the number of parameters that it receives). Right now I'm doing this:</p> <pre><code>def arity(obj, method): return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self class Foo: def bar(self, bla): pass arity(Foo(), "bar") # =&gt; 1 </code></pre> <p>I'd like to be able to achieve this:</p> <pre><code>Foo().bar.arity() # =&gt; 1 </code></pre> <p><strong>Update</strong>: Right now the above function fails with built-in types, any help on this would also be appreciated:</p> <pre><code> # Traceback (most recent call last): # File "bla.py", line 10, in &lt;module&gt; # print arity('foo', 'split') # =&gt; # File "bla.py", line 3, in arity # return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self # AttributeError: 'method_descriptor' object has no attribute 'func_co </code></pre>
25
2009-06-13T05:07:17Z
990,034
<p>you can use a decorator to decorate methods e.g.</p> <pre><code>def arity(method): def _arity(): return method.func_code.co_argcount - 1 # remove self method.arity = _arity return method class Foo: @arity def bar(self, bla): pass print Foo().bar.arity() </code></pre> <p>As alex said now its upto you how you code _arity function to calculate arg count based on your needs</p>
4
2009-06-13T05:21:57Z
[ "python", "metaprogramming" ]
How to find out the arity of a method in Python
990,016
<p>I'd like to find out the arity of a method in Python (the number of parameters that it receives). Right now I'm doing this:</p> <pre><code>def arity(obj, method): return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self class Foo: def bar(self, bla): pass arity(Foo(), "bar") # =&gt; 1 </code></pre> <p>I'd like to be able to achieve this:</p> <pre><code>Foo().bar.arity() # =&gt; 1 </code></pre> <p><strong>Update</strong>: Right now the above function fails with built-in types, any help on this would also be appreciated:</p> <pre><code> # Traceback (most recent call last): # File "bla.py", line 10, in &lt;module&gt; # print arity('foo', 'split') # =&gt; # File "bla.py", line 3, in arity # return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self # AttributeError: 'method_descriptor' object has no attribute 'func_co </code></pre>
25
2009-06-13T05:07:17Z
990,039
<p>Ideally, you'd want to monkey-patch the arity function as a method on Python functors. Here's how:</p> <pre><code>def arity(self, method): return getattr(self.__class__, method).func_code.co_argcount - 1 functor = arity.__class__ functor.arity = arity arity.__class__.arity = arity </code></pre> <p>But, CPython implements functors in C, you can't actually modify them. This may work in PyPy, though.</p> <p>That's all assuming your arity() function is correct. What about variadic functions? Do you even want an answer then?</p>
2
2009-06-13T05:23:51Z
[ "python", "metaprogramming" ]
How to find out the arity of a method in Python
990,016
<p>I'd like to find out the arity of a method in Python (the number of parameters that it receives). Right now I'm doing this:</p> <pre><code>def arity(obj, method): return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self class Foo: def bar(self, bla): pass arity(Foo(), "bar") # =&gt; 1 </code></pre> <p>I'd like to be able to achieve this:</p> <pre><code>Foo().bar.arity() # =&gt; 1 </code></pre> <p><strong>Update</strong>: Right now the above function fails with built-in types, any help on this would also be appreciated:</p> <pre><code> # Traceback (most recent call last): # File "bla.py", line 10, in &lt;module&gt; # print arity('foo', 'split') # =&gt; # File "bla.py", line 3, in arity # return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self # AttributeError: 'method_descriptor' object has no attribute 'func_co </code></pre>
25
2009-06-13T05:07:17Z
990,060
<p>here is another attempt using metaclass, as i use python 2.5, but with 2.6 you could easily decorate the class</p> <p>metaclass can also be defined at module level, so it works for all classes</p> <pre><code>from types import FunctionType def arity(unboundmethod): def _arity(): return unboundmethod.func_code.co_argcount - 1 # remove self unboundmethod.arity = _arity return unboundmethod class AirtyMetaclass(type): def __new__(meta, name, bases, attrs): newAttrs = {} for attributeName, attribute in attrs.items(): if type(attribute) == FunctionType: attribute = arity(attribute) newAttrs[attributeName] = attribute klass = type.__new__(meta, name, bases, newAttrs) return klass class Foo: __metaclass__ = AirtyMetaclass def bar(self, bla): pass print Foo().bar.arity() </code></pre>
0
2009-06-13T05:39:34Z
[ "python", "metaprogramming" ]
How to find out the arity of a method in Python
990,016
<p>I'd like to find out the arity of a method in Python (the number of parameters that it receives). Right now I'm doing this:</p> <pre><code>def arity(obj, method): return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self class Foo: def bar(self, bla): pass arity(Foo(), "bar") # =&gt; 1 </code></pre> <p>I'd like to be able to achieve this:</p> <pre><code>Foo().bar.arity() # =&gt; 1 </code></pre> <p><strong>Update</strong>: Right now the above function fails with built-in types, any help on this would also be appreciated:</p> <pre><code> # Traceback (most recent call last): # File "bla.py", line 10, in &lt;module&gt; # print arity('foo', 'split') # =&gt; # File "bla.py", line 3, in arity # return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self # AttributeError: 'method_descriptor' object has no attribute 'func_co </code></pre>
25
2009-06-13T05:07:17Z
990,942
<p>This is the only way that I can think of that should be 100% effective (at least with regard to whether the function is user-defined or written in C) at determining a function's (minimum) arity. However, you should be sure that this function won't cause any side-effects and that it won't throw a TypeError:</p> <pre><code>from functools import partial def arity(func): pfunc = func i = 0 while True: try: pfunc() except TypeError: pfunc = partial(pfunc, '') i += 1 else: return i def foo(x, y, z): pass def varfoo(*args): pass class klass(object): def klassfoo(self): pass print arity(foo) print arity(varfoo) x = klass() print arity(x.klassfoo) # output # 3 # 0 # 0 </code></pre> <p>As you can see, this will determine the <em>minimum</em> arity if a function takes a variable amount of arguments. It also won't take into account the self or cls argument of a class or instance method.</p> <p>To be totally honest though, I wouldn't use this function in a production environment unless I knew exactly which functions would be called though as there is a lot of room for stupid errors. This may defeat the purpose.</p>
2
2009-06-13T16:08:13Z
[ "python", "metaprogramming" ]
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux?
990,102
<p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p> <p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating system). But that this can seriously backfire on multi-core systems and you end up with IO intensive threads being heavily blocked by CPU intensive threads, the expense of context switching, the ctrl-C problem[*] and so on.</p> <p>So since the GIL limits us to basically executing a Python program on one CPU my thought is why not accept this and simply use taskset on Linux to set the affinity of the program to a certain core/cpu on the system (especially in a situation with multiple Python apps running on a multi-core system)?</p> <p>So ultimately my question is this: has anyone tried using taskset on Linux with Python applications (especially when running multiple applications on a Linux system so that multiple cores can be used with one or two Python applications bound to a specific core) and if so what were the results? is it worth doing? Does it make things worse for certain workloads? I plan to do this and test it out (basically see if the program takes more or less time to run) but would love to hear from others as to your experiences.</p> <p>Addition: David Beazley (the guy giving the talk in the linked video) pointed out that some C/C++ extensions manually release the GIL lock and if these extensions are optimized for multi-core (i.e. scientific or numeric data analysis/etc.) then rather than getting the benefits of multi-core for number crunching the extension would be effectively crippled in that it is limited to a single core (thus potentially slowing your program down significantly). On the other hand if you aren't using extensions such as this</p> <p>The reason I am not using the multiprocessing module is that (in this case) part of the program is heavily network I/O bound (HTTP requests) so having a pool of worker threads is a GREAT way to squeeze performance out of a box since a thread fires off an HTTP request and then since it's waiting on I/O gives up the GIL and another thread can do it's thing, so that part of the program can easily run 100+ threads without hurting the CPU much and let me actually use the network bandwidth that is available. As for stackless Python/etc I'm not overly interested in rewriting the program or replacing my Python stack (availability would also be a concern). </p> <p>[*] Only the main thread can receive signals so if you send a ctrl-C the Python interpreter basically tries to get the main thread to run so it can handle the signal, but since it doesn't directly control which thread is run (this is left to the operating system) it basically tells the OS to keep switching threads until it eventually hits the main thread (which if you are unlucky may take a while). </p>
15
2009-06-13T06:14:47Z
990,154
<p>Another solution is: <a href="http://docs.python.org/library/multiprocessing.html">http://docs.python.org/library/multiprocessing.html</a></p> <p>Note 1: This is <strong>not</strong> a limitation of the Python language, but of CPython implementation.</p> <p>Note 2: With regard to affinity, your OS shouldn't have a problem doing that itself.</p>
8
2009-06-13T06:49:25Z
[ "python", "multithreading", "multicore", "gil", "python-stackless" ]
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux?
990,102
<p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p> <p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating system). But that this can seriously backfire on multi-core systems and you end up with IO intensive threads being heavily blocked by CPU intensive threads, the expense of context switching, the ctrl-C problem[*] and so on.</p> <p>So since the GIL limits us to basically executing a Python program on one CPU my thought is why not accept this and simply use taskset on Linux to set the affinity of the program to a certain core/cpu on the system (especially in a situation with multiple Python apps running on a multi-core system)?</p> <p>So ultimately my question is this: has anyone tried using taskset on Linux with Python applications (especially when running multiple applications on a Linux system so that multiple cores can be used with one or two Python applications bound to a specific core) and if so what were the results? is it worth doing? Does it make things worse for certain workloads? I plan to do this and test it out (basically see if the program takes more or less time to run) but would love to hear from others as to your experiences.</p> <p>Addition: David Beazley (the guy giving the talk in the linked video) pointed out that some C/C++ extensions manually release the GIL lock and if these extensions are optimized for multi-core (i.e. scientific or numeric data analysis/etc.) then rather than getting the benefits of multi-core for number crunching the extension would be effectively crippled in that it is limited to a single core (thus potentially slowing your program down significantly). On the other hand if you aren't using extensions such as this</p> <p>The reason I am not using the multiprocessing module is that (in this case) part of the program is heavily network I/O bound (HTTP requests) so having a pool of worker threads is a GREAT way to squeeze performance out of a box since a thread fires off an HTTP request and then since it's waiting on I/O gives up the GIL and another thread can do it's thing, so that part of the program can easily run 100+ threads without hurting the CPU much and let me actually use the network bandwidth that is available. As for stackless Python/etc I'm not overly interested in rewriting the program or replacing my Python stack (availability would also be a concern). </p> <p>[*] Only the main thread can receive signals so if you send a ctrl-C the Python interpreter basically tries to get the main thread to run so it can handle the signal, but since it doesn't directly control which thread is run (this is left to the operating system) it basically tells the OS to keep switching threads until it eventually hits the main thread (which if you are unlucky may take a while). </p>
15
2009-06-13T06:14:47Z
990,323
<p>I've found the following rule of thumb sufficient over the years: If the workers are dependent on some shared state, I use one multiprocessing process per core (CPU bound), and per core a fix pool of worker threads (I/O bound). The OS will take care of assigining the different Python processes to the cores.</p>
1
2009-06-13T08:37:38Z
[ "python", "multithreading", "multicore", "gil", "python-stackless" ]
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux?
990,102
<p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p> <p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating system). But that this can seriously backfire on multi-core systems and you end up with IO intensive threads being heavily blocked by CPU intensive threads, the expense of context switching, the ctrl-C problem[*] and so on.</p> <p>So since the GIL limits us to basically executing a Python program on one CPU my thought is why not accept this and simply use taskset on Linux to set the affinity of the program to a certain core/cpu on the system (especially in a situation with multiple Python apps running on a multi-core system)?</p> <p>So ultimately my question is this: has anyone tried using taskset on Linux with Python applications (especially when running multiple applications on a Linux system so that multiple cores can be used with one or two Python applications bound to a specific core) and if so what were the results? is it worth doing? Does it make things worse for certain workloads? I plan to do this and test it out (basically see if the program takes more or less time to run) but would love to hear from others as to your experiences.</p> <p>Addition: David Beazley (the guy giving the talk in the linked video) pointed out that some C/C++ extensions manually release the GIL lock and if these extensions are optimized for multi-core (i.e. scientific or numeric data analysis/etc.) then rather than getting the benefits of multi-core for number crunching the extension would be effectively crippled in that it is limited to a single core (thus potentially slowing your program down significantly). On the other hand if you aren't using extensions such as this</p> <p>The reason I am not using the multiprocessing module is that (in this case) part of the program is heavily network I/O bound (HTTP requests) so having a pool of worker threads is a GREAT way to squeeze performance out of a box since a thread fires off an HTTP request and then since it's waiting on I/O gives up the GIL and another thread can do it's thing, so that part of the program can easily run 100+ threads without hurting the CPU much and let me actually use the network bandwidth that is available. As for stackless Python/etc I'm not overly interested in rewriting the program or replacing my Python stack (availability would also be a concern). </p> <p>[*] Only the main thread can receive signals so if you send a ctrl-C the Python interpreter basically tries to get the main thread to run so it can handle the signal, but since it doesn't directly control which thread is run (this is left to the operating system) it basically tells the OS to keep switching threads until it eventually hits the main thread (which if you are unlucky may take a while). </p>
15
2009-06-13T06:14:47Z
990,436
<p>I have never heard of anyone using taskset for a performance gain with Python. Doesn't mean it can't happen in your case, but definitely publish your results so others can critique your benchmarking methods and provide validation.</p> <p>Personally though, I would decouple your I/O threads from the CPU bound threads using a message queue. That way your front end is now completely network I/O bound (some with HTTP interface, some with message queue interface) and ideal for your threading situation. Then the CPU intense processes can either use multiprocessing or just be individual processes waiting for work to arrive on the message queue.</p> <p>In the longer term you might also want to consider replacing your threaded I/O front-end with Twisted or some thing like <a href="http://wiki.secondlife.com/wiki/Eventlet">eventlets</a> because, even if they won't help performance they should improve scalability. Your back-end is now already scalable because you can run your message queue over any number of machines+cpus as needed.</p>
5
2009-06-13T09:51:55Z
[ "python", "multithreading", "multicore", "gil", "python-stackless" ]
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux?
990,102
<p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p> <p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating system). But that this can seriously backfire on multi-core systems and you end up with IO intensive threads being heavily blocked by CPU intensive threads, the expense of context switching, the ctrl-C problem[*] and so on.</p> <p>So since the GIL limits us to basically executing a Python program on one CPU my thought is why not accept this and simply use taskset on Linux to set the affinity of the program to a certain core/cpu on the system (especially in a situation with multiple Python apps running on a multi-core system)?</p> <p>So ultimately my question is this: has anyone tried using taskset on Linux with Python applications (especially when running multiple applications on a Linux system so that multiple cores can be used with one or two Python applications bound to a specific core) and if so what were the results? is it worth doing? Does it make things worse for certain workloads? I plan to do this and test it out (basically see if the program takes more or less time to run) but would love to hear from others as to your experiences.</p> <p>Addition: David Beazley (the guy giving the talk in the linked video) pointed out that some C/C++ extensions manually release the GIL lock and if these extensions are optimized for multi-core (i.e. scientific or numeric data analysis/etc.) then rather than getting the benefits of multi-core for number crunching the extension would be effectively crippled in that it is limited to a single core (thus potentially slowing your program down significantly). On the other hand if you aren't using extensions such as this</p> <p>The reason I am not using the multiprocessing module is that (in this case) part of the program is heavily network I/O bound (HTTP requests) so having a pool of worker threads is a GREAT way to squeeze performance out of a box since a thread fires off an HTTP request and then since it's waiting on I/O gives up the GIL and another thread can do it's thing, so that part of the program can easily run 100+ threads without hurting the CPU much and let me actually use the network bandwidth that is available. As for stackless Python/etc I'm not overly interested in rewriting the program or replacing my Python stack (availability would also be a concern). </p> <p>[*] Only the main thread can receive signals so if you send a ctrl-C the Python interpreter basically tries to get the main thread to run so it can handle the signal, but since it doesn't directly control which thread is run (this is left to the operating system) it basically tells the OS to keep switching threads until it eventually hits the main thread (which if you are unlucky may take a while). </p>
15
2009-06-13T06:14:47Z
991,325
<p>The Python GIL is per Python interpreter. That means the only to avoid problems with it while doing multiprocessing is simply starting multiple interpreters (i.e. using seperate processes instead of threads for concurrency) and then using some other IPC primitive for communication between the processes (such as sockets). That being said, the GIL is not a problem when using threads with blocking I/O calls.</p> <p>The main problem of the GIL as mentioned earlier is that you can't execute 2 different python code threads at the same time. A thread blocking on a blocking I/O call is blocked and hence not executin python code. This means it is not blocking the GIL. If you have two CPU intensive tasks in seperate python threads, that's where the GIL kills multi-processing in Python (only the CPython implementation, as pointed out earlier). Because the GIL stops CPU #1 from executing a python thread while CPU #0 is busy executing the other python thread.</p>
1
2009-06-13T19:21:22Z
[ "python", "multithreading", "multicore", "gil", "python-stackless" ]
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux?
990,102
<p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p> <p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating system). But that this can seriously backfire on multi-core systems and you end up with IO intensive threads being heavily blocked by CPU intensive threads, the expense of context switching, the ctrl-C problem[*] and so on.</p> <p>So since the GIL limits us to basically executing a Python program on one CPU my thought is why not accept this and simply use taskset on Linux to set the affinity of the program to a certain core/cpu on the system (especially in a situation with multiple Python apps running on a multi-core system)?</p> <p>So ultimately my question is this: has anyone tried using taskset on Linux with Python applications (especially when running multiple applications on a Linux system so that multiple cores can be used with one or two Python applications bound to a specific core) and if so what were the results? is it worth doing? Does it make things worse for certain workloads? I plan to do this and test it out (basically see if the program takes more or less time to run) but would love to hear from others as to your experiences.</p> <p>Addition: David Beazley (the guy giving the talk in the linked video) pointed out that some C/C++ extensions manually release the GIL lock and if these extensions are optimized for multi-core (i.e. scientific or numeric data analysis/etc.) then rather than getting the benefits of multi-core for number crunching the extension would be effectively crippled in that it is limited to a single core (thus potentially slowing your program down significantly). On the other hand if you aren't using extensions such as this</p> <p>The reason I am not using the multiprocessing module is that (in this case) part of the program is heavily network I/O bound (HTTP requests) so having a pool of worker threads is a GREAT way to squeeze performance out of a box since a thread fires off an HTTP request and then since it's waiting on I/O gives up the GIL and another thread can do it's thing, so that part of the program can easily run 100+ threads without hurting the CPU much and let me actually use the network bandwidth that is available. As for stackless Python/etc I'm not overly interested in rewriting the program or replacing my Python stack (availability would also be a concern). </p> <p>[*] Only the main thread can receive signals so if you send a ctrl-C the Python interpreter basically tries to get the main thread to run so it can handle the signal, but since it doesn't directly control which thread is run (this is left to the operating system) it basically tells the OS to keep switching threads until it eventually hits the main thread (which if you are unlucky may take a while). </p>
15
2009-06-13T06:14:47Z
1,005,639
<p>Until such time as the GIL is removed from Python, co-routines may be used in place of threads. I have it on good authority that this strategy has been implemented by two successful start-ups, using greenlets in at least one case.</p>
1
2009-06-17T07:43:33Z
[ "python", "multithreading", "multicore", "gil", "python-stackless" ]
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux?
990,102
<p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p> <p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating system). But that this can seriously backfire on multi-core systems and you end up with IO intensive threads being heavily blocked by CPU intensive threads, the expense of context switching, the ctrl-C problem[*] and so on.</p> <p>So since the GIL limits us to basically executing a Python program on one CPU my thought is why not accept this and simply use taskset on Linux to set the affinity of the program to a certain core/cpu on the system (especially in a situation with multiple Python apps running on a multi-core system)?</p> <p>So ultimately my question is this: has anyone tried using taskset on Linux with Python applications (especially when running multiple applications on a Linux system so that multiple cores can be used with one or two Python applications bound to a specific core) and if so what were the results? is it worth doing? Does it make things worse for certain workloads? I plan to do this and test it out (basically see if the program takes more or less time to run) but would love to hear from others as to your experiences.</p> <p>Addition: David Beazley (the guy giving the talk in the linked video) pointed out that some C/C++ extensions manually release the GIL lock and if these extensions are optimized for multi-core (i.e. scientific or numeric data analysis/etc.) then rather than getting the benefits of multi-core for number crunching the extension would be effectively crippled in that it is limited to a single core (thus potentially slowing your program down significantly). On the other hand if you aren't using extensions such as this</p> <p>The reason I am not using the multiprocessing module is that (in this case) part of the program is heavily network I/O bound (HTTP requests) so having a pool of worker threads is a GREAT way to squeeze performance out of a box since a thread fires off an HTTP request and then since it's waiting on I/O gives up the GIL and another thread can do it's thing, so that part of the program can easily run 100+ threads without hurting the CPU much and let me actually use the network bandwidth that is available. As for stackless Python/etc I'm not overly interested in rewriting the program or replacing my Python stack (availability would also be a concern). </p> <p>[*] Only the main thread can receive signals so if you send a ctrl-C the Python interpreter basically tries to get the main thread to run so it can handle the signal, but since it doesn't directly control which thread is run (this is left to the operating system) it basically tells the OS to keep switching threads until it eventually hits the main thread (which if you are unlucky may take a while). </p>
15
2009-06-13T06:14:47Z
8,204,625
<p>An interesting solution is the experiment reported by Ryan Kelly on his blog: <a href="http://www.rfk.id.au/blog/entry/a-gil-adventure-threading2/" rel="nofollow">http://www.rfk.id.au/blog/entry/a-gil-adventure-threading2/</a></p> The results seems very satisfactory.</p>
3
2011-11-20T20:51:04Z
[ "python", "multithreading", "multicore", "gil", "python-stackless" ]
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux?
990,102
<p>So I just finished watching this talk on the Python Global Interpreter Lock (GIL) <a href="http://blip.tv/file/2232410">http://blip.tv/file/2232410</a>.</p> <p>The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating system). But that this can seriously backfire on multi-core systems and you end up with IO intensive threads being heavily blocked by CPU intensive threads, the expense of context switching, the ctrl-C problem[*] and so on.</p> <p>So since the GIL limits us to basically executing a Python program on one CPU my thought is why not accept this and simply use taskset on Linux to set the affinity of the program to a certain core/cpu on the system (especially in a situation with multiple Python apps running on a multi-core system)?</p> <p>So ultimately my question is this: has anyone tried using taskset on Linux with Python applications (especially when running multiple applications on a Linux system so that multiple cores can be used with one or two Python applications bound to a specific core) and if so what were the results? is it worth doing? Does it make things worse for certain workloads? I plan to do this and test it out (basically see if the program takes more or less time to run) but would love to hear from others as to your experiences.</p> <p>Addition: David Beazley (the guy giving the talk in the linked video) pointed out that some C/C++ extensions manually release the GIL lock and if these extensions are optimized for multi-core (i.e. scientific or numeric data analysis/etc.) then rather than getting the benefits of multi-core for number crunching the extension would be effectively crippled in that it is limited to a single core (thus potentially slowing your program down significantly). On the other hand if you aren't using extensions such as this</p> <p>The reason I am not using the multiprocessing module is that (in this case) part of the program is heavily network I/O bound (HTTP requests) so having a pool of worker threads is a GREAT way to squeeze performance out of a box since a thread fires off an HTTP request and then since it's waiting on I/O gives up the GIL and another thread can do it's thing, so that part of the program can easily run 100+ threads without hurting the CPU much and let me actually use the network bandwidth that is available. As for stackless Python/etc I'm not overly interested in rewriting the program or replacing my Python stack (availability would also be a concern). </p> <p>[*] Only the main thread can receive signals so if you send a ctrl-C the Python interpreter basically tries to get the main thread to run so it can handle the signal, but since it doesn't directly control which thread is run (this is left to the operating system) it basically tells the OS to keep switching threads until it eventually hits the main thread (which if you are unlucky may take a while). </p>
15
2009-06-13T06:14:47Z
8,926,548
<p>This is a pretty old question but since everytime I search about information related to python and performance on multi-core systems this post is always on the result list, I would not let this past before me an do not share my thoughts.</p> <p>You can use the multiprocessing module that rather than create threads for each task, it creates another process of cpython compier interpreting your code. It would make your application to take advantage of multicore systems. The only problem that I see on this approach is that you will have a considerable overhead by creating an entire new process stack on memory. (<a href="http://en.wikipedia.org/wiki/Thread_%28computing%29#How_threads_differ_from_processes" rel="nofollow">http://en.wikipedia.org/wiki/Thread_(computing)#How_threads_differ_from_processes</a>)</p> <p>Python Multiprocessing module: <a href="http://docs.python.org/dev/library/multiprocessing.html" rel="nofollow">http://docs.python.org/dev/library/multiprocessing.html</a></p> <p><em>"The reason I am not using the multiprocessing module is that (in this case) part of the program is heavily network I/O bound (HTTP requests) so having a pool of worker threads is a GREAT way to squeeze performance out of a box..."</em></p> <p>About this, I guess that you can have also a pool of process too: <a href="http://docs.python.org/dev/library/multiprocessing.html#using-a-pool-of-workers" rel="nofollow">http://docs.python.org/dev/library/multiprocessing.html#using-a-pool-of-workers</a></p> <p>Att, Leo</p>
0
2012-01-19T13:10:17Z
[ "python", "multithreading", "multicore", "gil", "python-stackless" ]
How do convert unicode escape sequences to unicode characters in a python string
990,169
<p>When I tried to get the content of a tag using "unicode(head.contents[3])" i get the output similar to this: "Christensen Sk\xf6ld". I want the escape sequence to be returned as string. How to do it in python?</p>
20
2009-06-13T06:56:27Z
990,183
<p>I suspect that it's acutally working correctly. By default, Python displays strings in ASCII encoding, since not all terminals support unicode. If you actually print the string, though, it should work. See the following example:</p> <pre><code>&gt;&gt;&gt; u'\xcfa' u'\xcfa' &gt;&gt;&gt; print u'\xcfa' Ïa </code></pre>
4
2009-06-13T07:02:20Z
[ "python", "unicode" ]
How do convert unicode escape sequences to unicode characters in a python string
990,169
<p>When I tried to get the content of a tag using "unicode(head.contents[3])" i get the output similar to this: "Christensen Sk\xf6ld". I want the escape sequence to be returned as string. How to do it in python?</p>
20
2009-06-13T06:56:27Z
992,314
<p>Assuming Python sees the name as a normal string, you'll first have to decode it to unicode:</p> <pre><code>&gt;&gt;&gt; name 'Christensen Sk\xf6ld' &gt;&gt;&gt; unicode(name, 'latin-1') u'Christensen Sk\xf6ld' </code></pre> <p>Another way of achieving this:</p> <pre><code>&gt;&gt;&gt; name.decode('latin-1') u'Christensen Sk\xf6ld' </code></pre> <p>Note the "u" in front of the string, signalling it is uncode. If you print this, the accented letter is shown properly:</p> <pre><code>&gt;&gt;&gt; print name.decode('latin-1') Christensen Sköld </code></pre> <p>BTW: when necessary, you can use de "encode" method to turn the unicode into e.g. a UTF-8 string:</p> <pre><code>&gt;&gt;&gt; name.decode('latin-1').encode('utf-8') 'Christensen Sk\xc3\xb6ld' </code></pre>
24
2009-06-14T06:46:22Z
[ "python", "unicode" ]
How do convert unicode escape sequences to unicode characters in a python string
990,169
<p>When I tried to get the content of a tag using "unicode(head.contents[3])" i get the output similar to this: "Christensen Sk\xf6ld". I want the escape sequence to be returned as string. How to do it in python?</p>
20
2009-06-13T06:56:27Z
12,083,259
<p>Given a byte string with Unicode escapes <code>b"\N{SNOWMAN}"</code>, <code>b"\N{SNOWMAN}".decode('unicode-escape)</code> will produce the expected Unicode string <code>u'\u2603'</code>.</p>
5
2012-08-23T00:36:28Z
[ "python", "unicode" ]
How to get a reference to current module's attributes in Python
990,422
<p>What I'm trying to do would look like this in the command line:</p> <pre><code>&gt;&gt;&gt; import mymodule &gt;&gt;&gt; names = dir(mymodule) </code></pre> <p>How can I get a reference to all the names defined in <code>mymodule</code> from within <code>mymodule</code> itself?</p> <p>Something like this:</p> <pre><code># mymodule.py names = dir(__thismodule__) </code></pre>
78
2009-06-13T09:45:03Z
990,450
<p>Just use globals()</p> <blockquote> <p>globals() — Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).</p> </blockquote> <p><a href="http://docs.python.org/library/functions.html#globals">http://docs.python.org/library/functions.html#globals</a></p>
87
2009-06-13T10:01:56Z
[ "python" ]
How to get a reference to current module's attributes in Python
990,422
<p>What I'm trying to do would look like this in the command line:</p> <pre><code>&gt;&gt;&gt; import mymodule &gt;&gt;&gt; names = dir(mymodule) </code></pre> <p>How can I get a reference to all the names defined in <code>mymodule</code> from within <code>mymodule</code> itself?</p> <p>Something like this:</p> <pre><code># mymodule.py names = dir(__thismodule__) </code></pre>
78
2009-06-13T09:45:03Z
991,115
<p>Also check out the built-in <a href="http://docs.python.org/2/library/inspect.html" rel="nofollow">inspect</a> module. It can be very handy.</p>
9
2009-06-13T17:32:18Z
[ "python" ]
How to get a reference to current module's attributes in Python
990,422
<p>What I'm trying to do would look like this in the command line:</p> <pre><code>&gt;&gt;&gt; import mymodule &gt;&gt;&gt; names = dir(mymodule) </code></pre> <p>How can I get a reference to all the names defined in <code>mymodule</code> from within <code>mymodule</code> itself?</p> <p>Something like this:</p> <pre><code># mymodule.py names = dir(__thismodule__) </code></pre>
78
2009-06-13T09:45:03Z
991,158
<p>As previously mentioned, globals gives you a dictionary as opposed to dir() which gives you a list of the names defined in the module. The way I typically see this done is like this:</p> <pre><code>import sys dir(sys.modules[__name__]) </code></pre>
102
2009-06-13T17:53:16Z
[ "python" ]
Python LDAP Authentication from remote web server
990,459
<p>I have a django application hosted on webfaction which now has a static/private ip.</p> <p>Our network in the office is obviously behind a firewall and the AD server is running behind this firewall. From inside the network i can authenticate using python-ldap with the AD's internal IP address and the port 389 and all works well.</p> <p>When i move this to the hosted webserver i change the ip address and port that has been openend up on our firewall. For simplicity the port we opened up is 389 however the requests to authenticate always timeout. When logged into webfaction and running python from the shell and querying the ipaddress i get webfactional's general ip address rather than my static ip.</p> <p>Is this whats happening when i try and auth in django? the request comes from the underlying ip address that python is running on rather than the static ip that my firewall is expecting?</p> <p>Im fairly clueless to all this networking and port mapping so any help would be much appreciated! </p> <p>Hope that makes sense?</p>
0
2009-06-13T10:09:05Z
991,550
<p>There are quite a few components between your hosted django application and your internal AD. You will need to test each to see if everything in the pathways between them is correct.</p> <p>So your AD server is sitting behind your firewall. Your firewall has ip "a.b.c.d" and all traffic to the firewall ip on port 389 is forwarded to the AD server. I would recommend that you change this to a higher more random port on your firewall, btw. Less scans there.</p> <p>With the shell access you can test to see if you can reach your network. Have your firewall admin check the firewall logs while you try one of the following (or something similar with python) :</p> <ul> <li><p>check the route to your firewall (this might not work if webfaction blocks this, otherwise you will see a list of hosts along which your traffic will pass - if there is a firewall on the route somewhere you will see that your connection is lost there as this is dropped by default on most firewalls): </p> <p>tracert a.b.c.d</p></li> <li><p>do a telnet to your firewall ip on port 389 (the telnet test will allow your firewall admin to see the connection attempts coming in on port 389 in his log. If those do arrive, that means that external comm should work fine):</p> <p>telnet a.b.c.d 389 </p></li> </ul> <p>Similarly, you need to check that your AD server receives these requests (check your logs) and as well can respond to them. Perhaps your AD server is not set up to talk to the firewall ?</p>
0
2009-06-13T21:29:41Z
[ "python", "active-directory", "ldap", "webserver" ]
Python LDAP Authentication from remote web server
990,459
<p>I have a django application hosted on webfaction which now has a static/private ip.</p> <p>Our network in the office is obviously behind a firewall and the AD server is running behind this firewall. From inside the network i can authenticate using python-ldap with the AD's internal IP address and the port 389 and all works well.</p> <p>When i move this to the hosted webserver i change the ip address and port that has been openend up on our firewall. For simplicity the port we opened up is 389 however the requests to authenticate always timeout. When logged into webfaction and running python from the shell and querying the ipaddress i get webfactional's general ip address rather than my static ip.</p> <p>Is this whats happening when i try and auth in django? the request comes from the underlying ip address that python is running on rather than the static ip that my firewall is expecting?</p> <p>Im fairly clueless to all this networking and port mapping so any help would be much appreciated! </p> <p>Hope that makes sense?</p>
0
2009-06-13T10:09:05Z
992,795
<p>I would recommend against opening the port on the firewall directly to LDAP. Instead I would suggest making an SSH tunnel. This will put the necessary encryptionn around the LDAP traffic. Here is an example.</p> <pre><code>ssh -N -p 22 username@ldapserver -L 2222/localhost/389 </code></pre> <p>This assumes that the ssh server is running on port 22 of your ldap server, and is accessible from your web host. It will create a tunnel from port 389 on the ldap server to port 2222 on the web host. Then, you configure your django application on the web host to think that the LDAP server is running on localhost port 2222. </p>
3
2009-06-14T13:00:59Z
[ "python", "active-directory", "ldap", "webserver" ]
how to take a matrix in python?
990,469
<p>i want to create a matrix of size 1234*5678 with it being filled with 1 to 5678 in row major order?>..!! </p>
1
2009-06-13T10:19:27Z
990,491
<p><a href="http://bytes.com/topic/python/answers/594203-please-how-create-matrix-python" rel="nofollow">Here's a forum post</a> that has some code examples of what you are trying to achieve.</p>
1
2009-06-13T10:37:15Z
[ "python" ]
how to take a matrix in python?
990,469
<p>i want to create a matrix of size 1234*5678 with it being filled with 1 to 5678 in row major order?>..!! </p>
1
2009-06-13T10:19:27Z
990,510
<p>Or just use <a href="http://numpy.scipy.org/" rel="nofollow">Numerical Python</a> if you want to do some mathematical stuff on matrix too (like multiplication, ...). If they use row major order for the matrix layout in memory I can't tell you but it gets coverd in their documentation</p>
2
2009-06-13T11:00:28Z
[ "python" ]
how to take a matrix in python?
990,469
<p>i want to create a matrix of size 1234*5678 with it being filled with 1 to 5678 in row major order?>..!! </p>
1
2009-06-13T10:19:27Z
990,553
<p>I think you will need to use numpy to hold such a big matrix efficiently , not just computation. You have ~5e6 items of 4/8 bytes means 20/40 Mb in pure C already, several times of that in python without an efficient data structure (a list of rows, each row a list).</p> <p>Now, concerning your question:</p> <pre><code>import numpy as np a = np.empty((1234, 5678), dtype=np.int) a[:] = np.linspace(1, 5678, 5678) </code></pre> <p>You first create an array of the requested size, with type int (I assume you know you want 4 bytes integer, which is what np.int will give you on most platforms). The 3rd line uses broadcasting so that each row (a[0], a[1], ... a[1233]) is assigned the values of the np.linspace line (which gives you an array of [1, ....., 5678]). If you want F storage, that is column major:</p> <pre><code>a = np.empty((1234, 4567), dtype=np.int, order='F') ... </code></pre> <p>The matrix a will takes only a tiny amount of memory more than an array in C, and for computation at least, the indexing capabilities of arrays are much better than python lists.</p> <p>A nitpick: numeric is the name of the old numerical package for python - the recommended name is numpy.</p>
6
2009-06-13T11:38:56Z
[ "python" ]
Using doctest "result parser" within unit-tests in Python?
990,500
<p>I recently faced a problem about combining unit tests and doctests in Python. I worked around this problem in other way, but I still have question about it.</p> <p>Python's doctest module parses docstrings in a module and run commands following ">>> " at the beginning of each line and compare the output of it and those in docstrings.</p> <p>I wonder that I could use <em>that comparison method</em> implemented by doctest module when I want. I know that it's possible add doctest to test suite as a test case, but here I want to do it inside a single test case.</p> <p>It is something like this:</p> <pre><code>class MyTest(TestCase): def testIt(self): # some codes like self.assertEqual(...) output = StringIO() with StdoutCollector(output): # do something that uses stdout # I want something like this: doctest.compare_result(output.getvalue(), 'expected output') # do more things </code></pre> <p>Because doctest uses some heuristics to compare the outputs like ellipsis.</p> <p>Would somebody give an idea or suggestions?</p>
2
2009-06-13T10:46:53Z
990,630
<p>See <a href="http://docs.python.org/library/doctest.html#doctest.OutputChecker.check%5Foutput" rel="nofollow"><code>doctest.OutputChecker.check_output()</code></a></p>
2
2009-06-13T13:00:27Z
[ "python", "unit-testing", "testing", "documentation", "doctest" ]
How to leave/exit/deactivate a python virtualenv?
990,754
<p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p> <pre><code>me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ </code></pre> <p>However, how do I exit all virtual machines and workon my real machine again? Right now, the only way I have of getting back to</p> <pre><code>me@mymachine:~$ </code></pre> <p>is to exit the shell and start a new one. That's kind of annoying. Is there a command to workon "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?</p>
662
2009-06-13T14:15:36Z
990,779
<p>Usually, activating a virtualenv gives you a shell function named:</p> <pre><code>$ deactivate </code></pre> <p>which puts things back to normal.</p> <p><strong>Edit:</strong> I have just looked specifically again at the code for virtualenvwrapper, and, yes, it too supports "deactivate" as the way to escape from all virtualenvs.</p> <h2><strong>Edit:</strong> If you are trying to leave an Anaconda environment, the procedure is a bit different: run the two-word command <code>source deactivate</code> since they implement deactivation using a stand-alone script.</h2> <pre><code>bash-4.3$ deactivate pyenv-virtualenv: deactivate must be sourced. Run 'source deactivate' instead of 'deactivate' bash-4.3$ source deactivate pyenv-virtualenv: no virtualenv has been activated. </code></pre>
1,129
2009-06-13T14:31:00Z
[ "python", "virtualenv", "virtualenvwrapper" ]
How to leave/exit/deactivate a python virtualenv?
990,754
<p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p> <pre><code>me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ </code></pre> <p>However, how do I exit all virtual machines and workon my real machine again? Right now, the only way I have of getting back to</p> <pre><code>me@mymachine:~$ </code></pre> <p>is to exit the shell and start a new one. That's kind of annoying. Is there a command to workon "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?</p>
662
2009-06-13T14:15:36Z
27,429,748
<p>Had the same problem myself while working on an installer script, I took a look at what the <em>bin/activate_this.py</em> did and reversed it. </p> <p>Example:</p> <pre><code>#! /usr/bin/python # -*- coding: utf-8 -*- import os import sys # path to virtualenv venv_path = os.path.join('/home', 'sixdays', '.virtualenvs', 'test32') # Save old values old_os_path = os.environ['PATH'] old_sys_path = list(sys.path) old_sys_prefix = sys.prefix def deactivate(): # Change back by setting values to starting values os.environ['PATH'] = old_os_path sys.prefix = old_sys_prefix sys.path[:0] = old_sys_path # Activate the virtualenvironment activate_this = os.path.join(venv_path, 'bin/activate_this.py') execfile(activate_this, dict(__file__=activate_this)) # Print list of pip packages for virtualenv for example purpose import pip print str(pip.get_installed_distributions()) # Unload pip module del pip # deactive/switch back to initial interpreter deactivate() # print list of initial environment pip packages for example purpose import pip print str(pip.get_installed_distributions()) </code></pre> <p>Not 100% sure if it works as intended, I may have missed something completely.</p>
-1
2014-12-11T18:18:42Z
[ "python", "virtualenv", "virtualenvwrapper" ]
How to leave/exit/deactivate a python virtualenv?
990,754
<p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p> <pre><code>me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ </code></pre> <p>However, how do I exit all virtual machines and workon my real machine again? Right now, the only way I have of getting back to</p> <pre><code>me@mymachine:~$ </code></pre> <p>is to exit the shell and start a new one. That's kind of annoying. Is there a command to workon "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?</p>
662
2009-06-13T14:15:36Z
27,947,686
<p>I defined an <a href="http://askubuntu.com/questions/17536/how-do-i-create-a-permanent-bash-alias">alias</a> <strong>workoff</strong> as the opposite of workon:</p> <pre><code>alias workoff='deactivate' </code></pre> <p>Easy to remember:</p> <pre><code>[bobstein@host ~]$ workon django_project (django_project)[bobstein@host ~]$ workoff [bobstein@host ~]$ </code></pre>
17
2015-01-14T16:23:13Z
[ "python", "virtualenv", "virtualenvwrapper" ]
How to leave/exit/deactivate a python virtualenv?
990,754
<p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p> <pre><code>me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ </code></pre> <p>However, how do I exit all virtual machines and workon my real machine again? Right now, the only way I have of getting back to</p> <pre><code>me@mymachine:~$ </code></pre> <p>is to exit the shell and start a new one. That's kind of annoying. Is there a command to workon "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?</p>
662
2009-06-13T14:15:36Z
29,586,756
<p>$ deactivate </p> <p>If this doesn't work , try $ source deactivate</p>
2
2015-04-12T06:41:08Z
[ "python", "virtualenv", "virtualenvwrapper" ]
How to leave/exit/deactivate a python virtualenv?
990,754
<p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p> <pre><code>me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ </code></pre> <p>However, how do I exit all virtual machines and workon my real machine again? Right now, the only way I have of getting back to</p> <pre><code>me@mymachine:~$ </code></pre> <p>is to exit the shell and start a new one. That's kind of annoying. Is there a command to workon "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?</p>
662
2009-06-13T14:15:36Z
33,932,473
<p>to activate python virtual environment:</p> <pre><code>$cd ~/python-venv/ $./bin/activate </code></pre> <p>to deactivate:</p> <pre><code>$deactivate </code></pre>
4
2015-11-26T07:06:58Z
[ "python", "virtualenv", "virtualenvwrapper" ]
How to leave/exit/deactivate a python virtualenv?
990,754
<p>I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. </p> <pre><code>me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ </code></pre> <p>However, how do I exit all virtual machines and workon my real machine again? Right now, the only way I have of getting back to</p> <pre><code>me@mymachine:~$ </code></pre> <p>is to exit the shell and start a new one. That's kind of annoying. Is there a command to workon "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?</p>
662
2009-06-13T14:15:36Z
39,263,132
<p>You can use <code>virtualenvwrapper</code> in order to ease the way you work with <code>virtualenv</code></p> <p>Installing <code>virtualenvwrapper</code></p> <pre><code>pip install virtualenvwrapper </code></pre> <p>If you are using standard shell, open your <code>~/.bashrc</code> or <code>~/.zshrc</code> if you use oh-my-zsh. Add this two lines:</p> <pre><code>export WORKON_HOME=$HOME/.virtualenvs source /usr/local/bin/virtualenvwrapper.sh </code></pre> <p>To activate an existing virtualenv, use command workon:</p> <pre><code>$ workon myenv (myenv)$ </code></pre> <p>In order to deactivate your virtualenv:</p> <pre><code>(myenv)$ deactivate </code></pre> <p>Here is my <a href="http://levipy.com/virtualenv-and-virtualenvwrapper-tutorial/" rel="nofollow">tutorial</a>, step by step in how to install virtualenv and virtualenvwrapper</p>
-1
2016-09-01T05:13:21Z
[ "python", "virtualenv", "virtualenvwrapper" ]
Reclassing an instance in Python
990,758
<p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p> <p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway).</p> <p>The following solution seems to work.</p> <pre><code># This class comes from an external library. I don't (want) to control # it, and I want to be open to changes that get made to the class # by the library provider. class Programmer(object): def __init__(self,name): self._name = name def greet(self): print "Hi, my name is %s." % self._name def hard_work(self): print "The garbage collector will take care of everything." # This is my subclass. class C_Programmer(Programmer): def __init__(self, *args, **kwargs): super(C_Programmer,self).__init__(*args, **kwargs) self.learn_C() def learn_C(self): self._knowledge = ["malloc","free","pointer arithmetic","curly braces"] def hard_work(self): print "I'll have to remember " + " and ".join(self._knowledge) + "." # The questionable thing: Reclassing a programmer. @classmethod def teach_C(cls, programmer): programmer.__class__ = cls # &lt;-- do I really want to do this? programmer.learn_C() joel = C_Programmer("Joel") joel.greet() joel.hard_work() #&gt;Hi, my name is Joel. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. jeff = Programmer("Jeff") # We (or someone else) makes changes to the instance. The reclassing shouldn't # overwrite these. jeff._name = "Jeff A" jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;The garbage collector will take care of everything. # Let magic happen. C_Programmer.teach_C(jeff) jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. </code></pre> <p>However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical <code>__class__</code> just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this.</p> <p>Is there?</p> <p><hr /></p> <p>Edit: Thanks everyone for your answers. Here is what I get from them:</p> <ul> <li><p>Although the idea of reclassing an instance by assigning to <code>__class__</code> is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments &amp; votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general.</p></li> <li><p>None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming.</p></li> </ul> <p>As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (<code>import this</code>), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way.</p> <ul> <li><p>Using <code>{has,get,set}attr</code> seems more explicit, as we are explicitly making our changes to the object instead of using magic.</p></li> <li><p>Using <code>__class__ = newclass</code> seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class.</p></li> </ul> <p>Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes." </p> <p>I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far.</p> <p>P.S. The actual use case is a UI data control object that needs to grow additional functionality <em>at runtime</em>. However, the question is meant to be very general.</p>
45
2009-06-13T14:17:41Z
990,790
<p>Heheh, fun example.</p> <p>"Reclassing" is pretty weird, at first glance. What about the 'copy constructor' approach? You can do this with the Reflection-like <code>hasattr</code>, <code>getattr</code> and <code>setattr</code>. This code will copy everything from one object to another, unless it already exists. If you don't want to copy methods, you can exclude them; see the commented <code>if</code>.</p> <pre><code>class Foo(object): def __init__(self): self.cow = 2 self.moose = 6 class Bar(object): def __init__(self): self.cat = 2 self.cow = 11 def from_foo(foo): bar = Bar() attributes = dir(foo) for attr in attributes: if (hasattr(bar, attr)): break value = getattr(foo, attr) # if hasattr(value, '__call__'): # break # skip callables (i.e. functions) setattr(bar, attr, value) return bar </code></pre> <p>All this reflection isn't pretty, but sometimes you need an ugly reflection machine to make cool stuff happen. ;)</p>
1
2009-06-13T14:43:34Z
[ "subclass", "python" ]
Reclassing an instance in Python
990,758
<p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p> <p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway).</p> <p>The following solution seems to work.</p> <pre><code># This class comes from an external library. I don't (want) to control # it, and I want to be open to changes that get made to the class # by the library provider. class Programmer(object): def __init__(self,name): self._name = name def greet(self): print "Hi, my name is %s." % self._name def hard_work(self): print "The garbage collector will take care of everything." # This is my subclass. class C_Programmer(Programmer): def __init__(self, *args, **kwargs): super(C_Programmer,self).__init__(*args, **kwargs) self.learn_C() def learn_C(self): self._knowledge = ["malloc","free","pointer arithmetic","curly braces"] def hard_work(self): print "I'll have to remember " + " and ".join(self._knowledge) + "." # The questionable thing: Reclassing a programmer. @classmethod def teach_C(cls, programmer): programmer.__class__ = cls # &lt;-- do I really want to do this? programmer.learn_C() joel = C_Programmer("Joel") joel.greet() joel.hard_work() #&gt;Hi, my name is Joel. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. jeff = Programmer("Jeff") # We (or someone else) makes changes to the instance. The reclassing shouldn't # overwrite these. jeff._name = "Jeff A" jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;The garbage collector will take care of everything. # Let magic happen. C_Programmer.teach_C(jeff) jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. </code></pre> <p>However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical <code>__class__</code> just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this.</p> <p>Is there?</p> <p><hr /></p> <p>Edit: Thanks everyone for your answers. Here is what I get from them:</p> <ul> <li><p>Although the idea of reclassing an instance by assigning to <code>__class__</code> is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments &amp; votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general.</p></li> <li><p>None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming.</p></li> </ul> <p>As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (<code>import this</code>), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way.</p> <ul> <li><p>Using <code>{has,get,set}attr</code> seems more explicit, as we are explicitly making our changes to the object instead of using magic.</p></li> <li><p>Using <code>__class__ = newclass</code> seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class.</p></li> </ul> <p>Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes." </p> <p>I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far.</p> <p>P.S. The actual use case is a UI data control object that needs to grow additional functionality <em>at runtime</em>. However, the question is meant to be very general.</p>
45
2009-06-13T14:17:41Z
990,859
<p>I will say this is perfectly fine, if it works for you.</p>
-1
2009-06-13T15:21:50Z
[ "subclass", "python" ]
Reclassing an instance in Python
990,758
<p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p> <p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway).</p> <p>The following solution seems to work.</p> <pre><code># This class comes from an external library. I don't (want) to control # it, and I want to be open to changes that get made to the class # by the library provider. class Programmer(object): def __init__(self,name): self._name = name def greet(self): print "Hi, my name is %s." % self._name def hard_work(self): print "The garbage collector will take care of everything." # This is my subclass. class C_Programmer(Programmer): def __init__(self, *args, **kwargs): super(C_Programmer,self).__init__(*args, **kwargs) self.learn_C() def learn_C(self): self._knowledge = ["malloc","free","pointer arithmetic","curly braces"] def hard_work(self): print "I'll have to remember " + " and ".join(self._knowledge) + "." # The questionable thing: Reclassing a programmer. @classmethod def teach_C(cls, programmer): programmer.__class__ = cls # &lt;-- do I really want to do this? programmer.learn_C() joel = C_Programmer("Joel") joel.greet() joel.hard_work() #&gt;Hi, my name is Joel. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. jeff = Programmer("Jeff") # We (or someone else) makes changes to the instance. The reclassing shouldn't # overwrite these. jeff._name = "Jeff A" jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;The garbage collector will take care of everything. # Let magic happen. C_Programmer.teach_C(jeff) jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. </code></pre> <p>However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical <code>__class__</code> just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this.</p> <p>Is there?</p> <p><hr /></p> <p>Edit: Thanks everyone for your answers. Here is what I get from them:</p> <ul> <li><p>Although the idea of reclassing an instance by assigning to <code>__class__</code> is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments &amp; votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general.</p></li> <li><p>None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming.</p></li> </ul> <p>As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (<code>import this</code>), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way.</p> <ul> <li><p>Using <code>{has,get,set}attr</code> seems more explicit, as we are explicitly making our changes to the object instead of using magic.</p></li> <li><p>Using <code>__class__ = newclass</code> seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class.</p></li> </ul> <p>Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes." </p> <p>I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far.</p> <p>P.S. The actual use case is a UI data control object that needs to grow additional functionality <em>at runtime</em>. However, the question is meant to be very general.</p>
45
2009-06-13T14:17:41Z
990,876
<p>I'm not sure that the use of inheritance is best in this case (at least with regards to "reclassing"). It seems like you're on the right track, but it sounds like composition or aggregation would be best for this. Here's an example of what I'm thinking of (in untested, pseudo-esque code):</p> <pre><code>from copy import copy # As long as none of these attributes are defined in the base class, # this should be safe class SkilledProgrammer(Programmer): def __init__(self, *skillsets): super(SkilledProgrammer, self).__init__() self.skillsets = set(skillsets) def teach(programmer, other_programmer): """If other_programmer has skillsets, append this programmer's skillsets. Otherwise, create a new skillset that is a copy of this programmer's""" if hasattr(other_programmer, skillsets) and other_programmer.skillsets: other_programmer.skillsets.union(programmer.skillsets) else: other_programmer.skillsets = copy(programmer.skillsets) def has_skill(programmer, skill): for skillset in programmer.skillsets: if skill in skillset.skills return True return False def has_skillset(programmer, skillset): return skillset in programmer.skillsets class SkillSet(object): def __init__(self, *skills): self.skills = set(skills) C = SkillSet("malloc","free","pointer arithmetic","curly braces") SQL = SkillSet("SELECT", "INSERT", "DELETE", "UPDATE") Bob = SkilledProgrammer(C) Jill = Programmer() teach(Bob, Jill) #teaches Jill C has_skill(Jill, "malloc") #should return True has_skillset(Jill, SQL) #should return False </code></pre> <p>You may have to read more about <a href="http://docs.python.org/library/stdtypes.html#set">sets</a> and <a href="http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists">arbitrary argument lists</a> if you aren't familiar with them to get this example.</p>
11
2009-06-13T15:31:03Z
[ "subclass", "python" ]
Reclassing an instance in Python
990,758
<p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p> <p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway).</p> <p>The following solution seems to work.</p> <pre><code># This class comes from an external library. I don't (want) to control # it, and I want to be open to changes that get made to the class # by the library provider. class Programmer(object): def __init__(self,name): self._name = name def greet(self): print "Hi, my name is %s." % self._name def hard_work(self): print "The garbage collector will take care of everything." # This is my subclass. class C_Programmer(Programmer): def __init__(self, *args, **kwargs): super(C_Programmer,self).__init__(*args, **kwargs) self.learn_C() def learn_C(self): self._knowledge = ["malloc","free","pointer arithmetic","curly braces"] def hard_work(self): print "I'll have to remember " + " and ".join(self._knowledge) + "." # The questionable thing: Reclassing a programmer. @classmethod def teach_C(cls, programmer): programmer.__class__ = cls # &lt;-- do I really want to do this? programmer.learn_C() joel = C_Programmer("Joel") joel.greet() joel.hard_work() #&gt;Hi, my name is Joel. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. jeff = Programmer("Jeff") # We (or someone else) makes changes to the instance. The reclassing shouldn't # overwrite these. jeff._name = "Jeff A" jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;The garbage collector will take care of everything. # Let magic happen. C_Programmer.teach_C(jeff) jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. </code></pre> <p>However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical <code>__class__</code> just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this.</p> <p>Is there?</p> <p><hr /></p> <p>Edit: Thanks everyone for your answers. Here is what I get from them:</p> <ul> <li><p>Although the idea of reclassing an instance by assigning to <code>__class__</code> is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments &amp; votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general.</p></li> <li><p>None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming.</p></li> </ul> <p>As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (<code>import this</code>), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way.</p> <ul> <li><p>Using <code>{has,get,set}attr</code> seems more explicit, as we are explicitly making our changes to the object instead of using magic.</p></li> <li><p>Using <code>__class__ = newclass</code> seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class.</p></li> </ul> <p>Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes." </p> <p>I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far.</p> <p>P.S. The actual use case is a UI data control object that needs to grow additional functionality <em>at runtime</em>. However, the question is meant to be very general.</p>
45
2009-06-13T14:17:41Z
990,915
<p>This technique seems reasonably Pythonic to me. Composition would also be a good choice, but assigning to <code>__class__</code> is perfectly valid (see <a href="http://code.activestate.com/recipes/68429/" rel="nofollow">here</a> for a recipe that uses it in a slightly different way).</p>
1
2009-06-13T15:53:16Z
[ "subclass", "python" ]
Reclassing an instance in Python
990,758
<p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p> <p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway).</p> <p>The following solution seems to work.</p> <pre><code># This class comes from an external library. I don't (want) to control # it, and I want to be open to changes that get made to the class # by the library provider. class Programmer(object): def __init__(self,name): self._name = name def greet(self): print "Hi, my name is %s." % self._name def hard_work(self): print "The garbage collector will take care of everything." # This is my subclass. class C_Programmer(Programmer): def __init__(self, *args, **kwargs): super(C_Programmer,self).__init__(*args, **kwargs) self.learn_C() def learn_C(self): self._knowledge = ["malloc","free","pointer arithmetic","curly braces"] def hard_work(self): print "I'll have to remember " + " and ".join(self._knowledge) + "." # The questionable thing: Reclassing a programmer. @classmethod def teach_C(cls, programmer): programmer.__class__ = cls # &lt;-- do I really want to do this? programmer.learn_C() joel = C_Programmer("Joel") joel.greet() joel.hard_work() #&gt;Hi, my name is Joel. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. jeff = Programmer("Jeff") # We (or someone else) makes changes to the instance. The reclassing shouldn't # overwrite these. jeff._name = "Jeff A" jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;The garbage collector will take care of everything. # Let magic happen. C_Programmer.teach_C(jeff) jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. </code></pre> <p>However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical <code>__class__</code> just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this.</p> <p>Is there?</p> <p><hr /></p> <p>Edit: Thanks everyone for your answers. Here is what I get from them:</p> <ul> <li><p>Although the idea of reclassing an instance by assigning to <code>__class__</code> is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments &amp; votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general.</p></li> <li><p>None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming.</p></li> </ul> <p>As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (<code>import this</code>), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way.</p> <ul> <li><p>Using <code>{has,get,set}attr</code> seems more explicit, as we are explicitly making our changes to the object instead of using magic.</p></li> <li><p>Using <code>__class__ = newclass</code> seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class.</p></li> </ul> <p>Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes." </p> <p>I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far.</p> <p>P.S. The actual use case is a UI data control object that needs to grow additional functionality <em>at runtime</em>. However, the question is meant to be very general.</p>
45
2009-06-13T14:17:41Z
991,202
<p>This is fine. I've used this idiom plenty of times. One thing to keep in mind though is that this idea doesn't play well with old-style classes and various C extensions. Normally this wouldn't be an issue, but since you are using an external library you'll just have to make sure you're not dealing with any old-style classes or C extensions.</p>
3
2009-06-13T18:13:46Z
[ "subclass", "python" ]
Reclassing an instance in Python
990,758
<p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p> <p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway).</p> <p>The following solution seems to work.</p> <pre><code># This class comes from an external library. I don't (want) to control # it, and I want to be open to changes that get made to the class # by the library provider. class Programmer(object): def __init__(self,name): self._name = name def greet(self): print "Hi, my name is %s." % self._name def hard_work(self): print "The garbage collector will take care of everything." # This is my subclass. class C_Programmer(Programmer): def __init__(self, *args, **kwargs): super(C_Programmer,self).__init__(*args, **kwargs) self.learn_C() def learn_C(self): self._knowledge = ["malloc","free","pointer arithmetic","curly braces"] def hard_work(self): print "I'll have to remember " + " and ".join(self._knowledge) + "." # The questionable thing: Reclassing a programmer. @classmethod def teach_C(cls, programmer): programmer.__class__ = cls # &lt;-- do I really want to do this? programmer.learn_C() joel = C_Programmer("Joel") joel.greet() joel.hard_work() #&gt;Hi, my name is Joel. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. jeff = Programmer("Jeff") # We (or someone else) makes changes to the instance. The reclassing shouldn't # overwrite these. jeff._name = "Jeff A" jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;The garbage collector will take care of everything. # Let magic happen. C_Programmer.teach_C(jeff) jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. </code></pre> <p>However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical <code>__class__</code> just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this.</p> <p>Is there?</p> <p><hr /></p> <p>Edit: Thanks everyone for your answers. Here is what I get from them:</p> <ul> <li><p>Although the idea of reclassing an instance by assigning to <code>__class__</code> is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments &amp; votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general.</p></li> <li><p>None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming.</p></li> </ul> <p>As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (<code>import this</code>), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way.</p> <ul> <li><p>Using <code>{has,get,set}attr</code> seems more explicit, as we are explicitly making our changes to the object instead of using magic.</p></li> <li><p>Using <code>__class__ = newclass</code> seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class.</p></li> </ul> <p>Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes." </p> <p>I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far.</p> <p>P.S. The actual use case is a UI data control object that needs to grow additional functionality <em>at runtime</em>. However, the question is meant to be very general.</p>
45
2009-06-13T14:17:41Z
991,262
<p>Reclassing instances like this is done in <a href="http://selenic.com/mercurial/">Mercurial</a> (a distributed revision control system) when extensions (plugins) want to change the object that represent the local repository. The object is called <code>repo</code> and is initially a <code>localrepo</code> instance. It is passed to each extension in turn and, when needed, extensions will define a new class which is a subclass of <code>repo.__class__</code> and <em>change</em> the class of <code>repo</code> to this new subclass!</p> <p>It looks <a href="http://www.selenic.com/hg/index.cgi/file/d19ab9a56bf4/hgext/bookmarks.py#l229">like this</a> in code:</p> <pre><code>def reposetup(ui, repo): # ... class bookmark_repo(repo.__class__): def rollback(self): if os.path.exists(self.join('undo.bookmarks')): util.rename(self.join('undo.bookmarks'), self.join('bookmarks')) return super(bookmark_repo, self).rollback() # ... repo.__class__ = bookmark_repo </code></pre> <p>The extension (I took the code from the bookmarks extension) defines a module level function called <code>reposetup</code>. Mercurial will call this when initializing the extension and pass a <code>ui</code> (user interface) and <code>repo</code> (repository) argument.</p> <p>The function then defines a subclass of whatever class <code>repo</code> happens to be. It would <em>not</em> suffice to simply subclass <code>localrepo</code> since extensions need to be able to extend each other. So if the first extension changes <code>repo.__class__</code> to <code>foo_repo</code>, the next extension should change <code>repo.__class__</code> to a subclass of <code>foo_repo</code> and not just a subclass of <code>localrepo</code>. Finally the function changes the instanceø's class, just like you did in your code.</p> <p>I hope this code can show a legitimate use of this language feature. I think it's the only place where I've seen it used in the wild.</p>
14
2009-06-13T18:47:45Z
[ "subclass", "python" ]
Reclassing an instance in Python
990,758
<p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p> <p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway).</p> <p>The following solution seems to work.</p> <pre><code># This class comes from an external library. I don't (want) to control # it, and I want to be open to changes that get made to the class # by the library provider. class Programmer(object): def __init__(self,name): self._name = name def greet(self): print "Hi, my name is %s." % self._name def hard_work(self): print "The garbage collector will take care of everything." # This is my subclass. class C_Programmer(Programmer): def __init__(self, *args, **kwargs): super(C_Programmer,self).__init__(*args, **kwargs) self.learn_C() def learn_C(self): self._knowledge = ["malloc","free","pointer arithmetic","curly braces"] def hard_work(self): print "I'll have to remember " + " and ".join(self._knowledge) + "." # The questionable thing: Reclassing a programmer. @classmethod def teach_C(cls, programmer): programmer.__class__ = cls # &lt;-- do I really want to do this? programmer.learn_C() joel = C_Programmer("Joel") joel.greet() joel.hard_work() #&gt;Hi, my name is Joel. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. jeff = Programmer("Jeff") # We (or someone else) makes changes to the instance. The reclassing shouldn't # overwrite these. jeff._name = "Jeff A" jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;The garbage collector will take care of everything. # Let magic happen. C_Programmer.teach_C(jeff) jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. </code></pre> <p>However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical <code>__class__</code> just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this.</p> <p>Is there?</p> <p><hr /></p> <p>Edit: Thanks everyone for your answers. Here is what I get from them:</p> <ul> <li><p>Although the idea of reclassing an instance by assigning to <code>__class__</code> is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments &amp; votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general.</p></li> <li><p>None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming.</p></li> </ul> <p>As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (<code>import this</code>), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way.</p> <ul> <li><p>Using <code>{has,get,set}attr</code> seems more explicit, as we are explicitly making our changes to the object instead of using magic.</p></li> <li><p>Using <code>__class__ = newclass</code> seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class.</p></li> </ul> <p>Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes." </p> <p>I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far.</p> <p>P.S. The actual use case is a UI data control object that needs to grow additional functionality <em>at runtime</em>. However, the question is meant to be very general.</p>
45
2009-06-13T14:17:41Z
3,284,809
<p>"The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change it's class." - Head First Design Pattern. Something very similar write Gamma et.al. in their Design Patterns book. (I have it at my other place, so no quote). I think that's the whole point of this design pattern. But if I can change the class of an object at runtime, most of the time i don't need the pattern (there are cases when State Pattern does more than simulate a class change).</p> <p>Also, changing class at runtime doesn't always work:</p> <pre><code>class A(object): def __init__(self, val): self.val = val def get_val(self): return self.val class B(A): def __init__(self, val1, val2): A.__init__(self, val1) self.val2 = val2 def get_val(self): return self.val + self.val2 a = A(3) b = B(4, 6) print a.get_val() print b.get_val() a.__class__ = B print a.get_val() # oops! </code></pre> <p>Apart from that, I consider changing class at runtime Pythonic and use it from time to time.</p>
3
2010-07-19T20:31:20Z
[ "subclass", "python" ]
Reclassing an instance in Python
990,758
<p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p> <p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway).</p> <p>The following solution seems to work.</p> <pre><code># This class comes from an external library. I don't (want) to control # it, and I want to be open to changes that get made to the class # by the library provider. class Programmer(object): def __init__(self,name): self._name = name def greet(self): print "Hi, my name is %s." % self._name def hard_work(self): print "The garbage collector will take care of everything." # This is my subclass. class C_Programmer(Programmer): def __init__(self, *args, **kwargs): super(C_Programmer,self).__init__(*args, **kwargs) self.learn_C() def learn_C(self): self._knowledge = ["malloc","free","pointer arithmetic","curly braces"] def hard_work(self): print "I'll have to remember " + " and ".join(self._knowledge) + "." # The questionable thing: Reclassing a programmer. @classmethod def teach_C(cls, programmer): programmer.__class__ = cls # &lt;-- do I really want to do this? programmer.learn_C() joel = C_Programmer("Joel") joel.greet() joel.hard_work() #&gt;Hi, my name is Joel. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. jeff = Programmer("Jeff") # We (or someone else) makes changes to the instance. The reclassing shouldn't # overwrite these. jeff._name = "Jeff A" jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;The garbage collector will take care of everything. # Let magic happen. C_Programmer.teach_C(jeff) jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. </code></pre> <p>However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical <code>__class__</code> just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this.</p> <p>Is there?</p> <p><hr /></p> <p>Edit: Thanks everyone for your answers. Here is what I get from them:</p> <ul> <li><p>Although the idea of reclassing an instance by assigning to <code>__class__</code> is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments &amp; votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general.</p></li> <li><p>None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming.</p></li> </ul> <p>As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (<code>import this</code>), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way.</p> <ul> <li><p>Using <code>{has,get,set}attr</code> seems more explicit, as we are explicitly making our changes to the object instead of using magic.</p></li> <li><p>Using <code>__class__ = newclass</code> seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class.</p></li> </ul> <p>Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes." </p> <p>I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far.</p> <p>P.S. The actual use case is a UI data control object that needs to grow additional functionality <em>at runtime</em>. However, the question is meant to be very general.</p>
45
2009-06-13T14:17:41Z
23,684,684
<p>In ojrac's answer, the <code>break</code> breaks out of the <code>for</code>-loop and doesn't test any more attributes. I think it makes more sense to just use the <code>if</code>-statement to decide what to do with each attribute one at a time, and continue through the <code>for</code>-loop over all attributes. Otherwise, I like ojrac's answer, as I too see assigning to <code>__class__</code> as weird. (I'm a beginner with Python and as far as I remember this is my first post to StackOverFlow. Thanks for all the great information!!)</p> <p>So I tried to implement that. I noticed that dir() doesn't list all the attributes. <a href="http://jedidjah.ch/code/2013/9/8/wrong_dir_function/" rel="nofollow">http://jedidjah.ch/code/2013/9/8/wrong_dir_function/</a> So I added '<strong>class</strong>', '<strong>doc</strong>', '<strong>module</strong>' and '<strong>init</strong>' to the list of things to add if they're not there already, (although they're probably all already there), and wondered whether there were more things dir misses. I also noticed that I was (potentially) assigning to '<strong>class</strong>' after having said that was weird.</p>
0
2014-05-15T17:10:40Z
[ "subclass", "python" ]
Closing file opened by ConfigParser
990,867
<p>I have the following:</p> <pre><code>config = ConfigParser() config.read('connections.cfg') sections = config.sections() </code></pre> <p>How can I close the file opened with <code>config.read</code>?</p> <p>In my case, as new sections/data are added to the <code>config.cfg</code> file, I update my wxtree widget. However, it only updates once, and I suspect it's because <code>config.read</code> leaves the file open.</p> <p>And while we are at it, what is the main difference between <code>ConfigParser</code> and <code>RawConfigParser</code>?</p>
8
2009-06-13T15:28:14Z
990,927
<p>To test your suspicion, use <a href="http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser.readfp" rel="nofollow">ConfigParser.readfp()</a> and handle opening and closing of the file by yourself. Make the <code>readfp</code> call after the changes are made.</p> <pre><code>config = ConfigParser() #...on each change fp = open('connections.cfg') config.readfp(fp) fp.close() sections = config.sections() </code></pre>
4
2009-06-13T16:01:03Z
[ "python", "configparser" ]
Closing file opened by ConfigParser
990,867
<p>I have the following:</p> <pre><code>config = ConfigParser() config.read('connections.cfg') sections = config.sections() </code></pre> <p>How can I close the file opened with <code>config.read</code>?</p> <p>In my case, as new sections/data are added to the <code>config.cfg</code> file, I update my wxtree widget. However, it only updates once, and I suspect it's because <code>config.read</code> leaves the file open.</p> <p>And while we are at it, what is the main difference between <code>ConfigParser</code> and <code>RawConfigParser</code>?</p>
8
2009-06-13T15:28:14Z
990,933
<p>Use <a href="http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser.readfp" rel="nofollow">readfp</a> instead of read:</p> <pre><code>with open('connections.cfg') as fp: config = ConfigParser() config.readfp(fp) sections = config.sections() </code></pre>
8
2009-06-13T16:03:27Z
[ "python", "configparser" ]
Closing file opened by ConfigParser
990,867
<p>I have the following:</p> <pre><code>config = ConfigParser() config.read('connections.cfg') sections = config.sections() </code></pre> <p>How can I close the file opened with <code>config.read</code>?</p> <p>In my case, as new sections/data are added to the <code>config.cfg</code> file, I update my wxtree widget. However, it only updates once, and I suspect it's because <code>config.read</code> leaves the file open.</p> <p>And while we are at it, what is the main difference between <code>ConfigParser</code> and <code>RawConfigParser</code>?</p>
8
2009-06-13T15:28:14Z
990,959
<p>The difference between <code>ConfigParser</code> and <code>RawConfigParser</code> is that <code>ConfigParser</code> will attempt to "magically" expand references to other config variables, like so:</p> <pre><code>x = 9000 %(y)s y = spoons </code></pre> <p>In this case, <code>x</code> will be <code>9000 spoons</code>, and <code>y</code> will just be <code>spoons</code>. If you need this expansion feature, the docs recommend that you instead use <code>SafeConfigParser</code>. I don't know what exatly the difference between the two is. If you don't need the expansion (you probably don't) just need <code>RawConfigParser</code>.</p>
5
2009-06-13T16:21:01Z
[ "python", "configparser" ]
Closing file opened by ConfigParser
990,867
<p>I have the following:</p> <pre><code>config = ConfigParser() config.read('connections.cfg') sections = config.sections() </code></pre> <p>How can I close the file opened with <code>config.read</code>?</p> <p>In my case, as new sections/data are added to the <code>config.cfg</code> file, I update my wxtree widget. However, it only updates once, and I suspect it's because <code>config.read</code> leaves the file open.</p> <p>And while we are at it, what is the main difference between <code>ConfigParser</code> and <code>RawConfigParser</code>?</p>
8
2009-06-13T15:28:14Z
16,666,375
<p><code>ConfigParser.read(filenames)</code> actually takes care of that for you.</p> <p>While coding I have encountered this issue and found myself asking myself the very same question: </p> <blockquote> <p><em>Reading basically means I also have to close this resource after I'm done with it, right?</em></p> </blockquote> <p>I read the answer you got here suggesting to open the file yourself and use <code>config.readfp(fp)</code> as an alternative. I looked at the <a href="http://docs.python.org/2/library/configparser.html">documentation</a> and saw that indeed there is no <code>ConfigParser.close()</code>. So I researched a little more and read the ConfigParser code implementation itself: </p> <pre><code>def read(self, filenames): """Read and parse a filename or a list of filenames. Files that cannot be opened are silently ignored; this is designed so that you can specify a list of potential configuration file locations (e.g. current directory, user's home directory, systemwide directory), and all existing configuration files in the list will be read. A single filename may also be given. Return list of successfully read files. """ if isinstance(filenames, basestring): filenames = [filenames] read_ok = [] for filename in filenames: try: fp = open(filename) except IOError: continue self._read(fp, filename) fp.close() read_ok.append(filename) return read_ok </code></pre> <p>This is the actual <code>read()</code> method from ConfigParser.py source code. As you can see, 3rd line from the bottom, <code>fp.close()</code> closes the opened resource after its usage in any case. This is offered to you, already included in the box with ConfigParser.read() :)</p>
11
2013-05-21T09:20:18Z
[ "python", "configparser" ]
String reversal in Python
990,934
<p>I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?</p> <p>I am not able to convert the integer into a list so not able to apply the reverse function.</p>
7
2009-06-13T16:03:35Z
990,939
<p>Code:</p> <pre><code>&gt;&gt;&gt; n = 1234 &gt;&gt;&gt; print str(n)[::-1] 4321 </code></pre>
4
2009-06-13T16:07:53Z
[ "python" ]
String reversal in Python
990,934
<p>I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?</p> <p>I am not able to convert the integer into a list so not able to apply the reverse function.</p>
7
2009-06-13T16:03:35Z
990,940
<p>You can use the slicing operator to reverse a string:</p> <pre><code>s = "hello, world" s = s[::-1] print s # prints "dlrow ,olleh" </code></pre> <p>To convert an integer to a string, reverse it, and convert it back to an integer, you can do:</p> <pre><code>x = 314159 x = int(str(x)[::-1]) print x # prints 951413 </code></pre>
30
2009-06-13T16:07:54Z
[ "python" ]
String reversal in Python
990,934
<p>I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?</p> <p>I am not able to convert the integer into a list so not able to apply the reverse function.</p>
7
2009-06-13T16:03:35Z
990,943
<pre><code>&gt;&gt;&gt; int(''.join(reversed(str(12345)))) 54321 </code></pre>
2
2009-06-13T16:09:59Z
[ "python" ]
How to calculate a mod b in python?
991,027
<p>Is there a modulo function in the python <code>math</code> library?</p> <p>Isn't <code>15 % 4</code>, 3? But <code>15 mod 4</code> is 1, right?</p>
53
2009-06-13T16:57:21Z
991,034
<p>There's the <code>%</code> sign. It's not just for the remainder, it is the modulo operation.</p>
86
2009-06-13T16:59:23Z
[ "python" ]
How to calculate a mod b in python?
991,027
<p>Is there a modulo function in the python <code>math</code> library?</p> <p>Isn't <code>15 % 4</code>, 3? But <code>15 mod 4</code> is 1, right?</p>
53
2009-06-13T16:57:21Z
991,037
<p>Why don't you use % ?</p> <pre><code> print 4 % 2 # 0 </code></pre>
8
2009-06-13T16:59:38Z
[ "python" ]
How to calculate a mod b in python?
991,027
<p>Is there a modulo function in the python <code>math</code> library?</p> <p>Isn't <code>15 % 4</code>, 3? But <code>15 mod 4</code> is 1, right?</p>
53
2009-06-13T16:57:21Z
991,043
<p><code>mod = a % b</code></p> <p>This stores the result of <code>a mod b</code> in the variable <code>mod</code>.</p> <p>And you are right, <code>15 mod 4</code> is 3, which is exactly what python returns:</p> <pre><code>&gt;&gt;&gt; 15 % 4 3 </code></pre> <p>@Macarse: Yes, but that is true for any \= construct in python, so I should think there's no need to point that out seperately for modulo.</p>
13
2009-06-13T17:00:46Z
[ "python" ]
How to calculate a mod b in python?
991,027
<p>Is there a modulo function in the python <code>math</code> library?</p> <p>Isn't <code>15 % 4</code>, 3? But <code>15 mod 4</code> is 1, right?</p>
53
2009-06-13T16:57:21Z
991,053
<pre><code>&gt;&gt;&gt; 15 % 4 3 &gt;&gt;&gt; </code></pre> <p>The modulo gives the remainder after integer division.</p>
19
2009-06-13T17:06:26Z
[ "python" ]
How to calculate a mod b in python?
991,027
<p>Is there a modulo function in the python <code>math</code> library?</p> <p>Isn't <code>15 % 4</code>, 3? But <code>15 mod 4</code> is 1, right?</p>
53
2009-06-13T16:57:21Z
992,639
<p>you can also try <code>divmod(x, y)</code> which returns a tuple <code>(x / y, x % y)</code></p>
25
2009-06-14T10:58:40Z
[ "python" ]
an error in taking an input in python
991,220
<p>111111111111111111111111111111111111111111111111111111111111</p> <p>when i take this as input , it appends an L at the end like this </p> <p>111111111111111111111111111111111111111111111111111111111111L</p> <p>thus affecting my calculations on it .. how can i remove it?</p> <pre><code>import math t=raw_input() l1=[] a=0 while (str(t)!="" and int(t)!= 0): l=1 k=int(t) while(k!= 1): l=l+1 a=(0.5 + 2.5*(k %2))*k + k % 2 k=a l1.append(l) t=raw_input() a=a+1 for i in range(0,int(a)): print l1[i] </code></pre> <p>this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111</p> <p>so i guess something is wrong when python considers such a huge number</p>
0
2009-06-13T18:24:05Z
991,226
<p>It's being input as a Long Integer, which should behave just like any other number in terms of doing calculations. It's only when you display it using <a href="http://docs.python.org/library/functions.html#repr" rel="nofollow"><code>repr</code></a> (or something that invokes <code>repr</code>, like printing a list) that it gets the 'L'.</p> <p>What exactly is going wrong?</p> <p><strong>Edit</strong>: Thanks for the code. As far as I can see, giving it a long or short number makes no difference, but it's not really clear what it's supposed to do.</p>
3
2009-06-13T18:26:32Z
[ "python" ]
an error in taking an input in python
991,220
<p>111111111111111111111111111111111111111111111111111111111111</p> <p>when i take this as input , it appends an L at the end like this </p> <p>111111111111111111111111111111111111111111111111111111111111L</p> <p>thus affecting my calculations on it .. how can i remove it?</p> <pre><code>import math t=raw_input() l1=[] a=0 while (str(t)!="" and int(t)!= 0): l=1 k=int(t) while(k!= 1): l=l+1 a=(0.5 + 2.5*(k %2))*k + k % 2 k=a l1.append(l) t=raw_input() a=a+1 for i in range(0,int(a)): print l1[i] </code></pre> <p>this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111</p> <p>so i guess something is wrong when python considers such a huge number</p>
0
2009-06-13T18:24:05Z
991,231
<p>Are you sure that L is really part of it? When you print such large numbers, Python will append an L to indicate it's a long integer object.</p>
0
2009-06-13T18:28:12Z
[ "python" ]
an error in taking an input in python
991,220
<p>111111111111111111111111111111111111111111111111111111111111</p> <p>when i take this as input , it appends an L at the end like this </p> <p>111111111111111111111111111111111111111111111111111111111111L</p> <p>thus affecting my calculations on it .. how can i remove it?</p> <pre><code>import math t=raw_input() l1=[] a=0 while (str(t)!="" and int(t)!= 0): l=1 k=int(t) while(k!= 1): l=l+1 a=(0.5 + 2.5*(k %2))*k + k % 2 k=a l1.append(l) t=raw_input() a=a+1 for i in range(0,int(a)): print l1[i] </code></pre> <p>this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111</p> <p>so i guess something is wrong when python considers such a huge number</p>
0
2009-06-13T18:24:05Z
991,245
<p>As RichieHindle noticed in his answer, it is being represented as a Long Integer. You can read about the different ways that numbers can be represented in Python at the following <a href="http://www.python.org/doc/2.5.2/lib/typesnumeric.html" rel="nofollow">page</a>.</p> <p>When I use numbers that large in Python, I see the L at the end of the number as well. It shouldn't affect any of the computations done on the number. For example:</p> <pre><code>&gt;&gt;&gt; a = 111111111111111111111111111111111111111 &gt;&gt;&gt; a + 1 111111111111111111111111111111111111112L &gt;&gt;&gt; str(a) '111111111111111111111111111111111111111' &gt;&gt;&gt; int(a) 111111111111111111111111111111111111111L </code></pre> <p>I did that on the python command line. When you output the number, it will have the internal representation for the number, but it shouldn't affect any of your computations. The link I reference above specifies that long integers have <strong><em>unlimited precision</em></strong>. So cool!</p>
2
2009-06-13T18:35:59Z
[ "python" ]
an error in taking an input in python
991,220
<p>111111111111111111111111111111111111111111111111111111111111</p> <p>when i take this as input , it appends an L at the end like this </p> <p>111111111111111111111111111111111111111111111111111111111111L</p> <p>thus affecting my calculations on it .. how can i remove it?</p> <pre><code>import math t=raw_input() l1=[] a=0 while (str(t)!="" and int(t)!= 0): l=1 k=int(t) while(k!= 1): l=l+1 a=(0.5 + 2.5*(k %2))*k + k % 2 k=a l1.append(l) t=raw_input() a=a+1 for i in range(0,int(a)): print l1[i] </code></pre> <p>this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111</p> <p>so i guess something is wrong when python considers such a huge number</p>
0
2009-06-13T18:24:05Z
991,301
<p>It looks like there are two distinct things happening here. First, as the other posters have noted, the L suffix simply indicates that Python has converted the input value to a long integer. The second issue is on this line:</p> <pre><code>a=(0.5 + 2.5*(k %2))*k + k % 2 </code></pre> <p>This implicitly results in a floating point number for the value of <code>(0.5 + 2.5*(k %2))*k</code>. Since floats only have 53 bits of precision the result is incorrect due to rounding. Try refactoring the line to avoid floating point math, like this:</p> <pre><code>a=(1 + 5*(k %2))*k//2 + k % 2 </code></pre>
3
2009-06-13T19:09:26Z
[ "python" ]
an error in taking an input in python
991,220
<p>111111111111111111111111111111111111111111111111111111111111</p> <p>when i take this as input , it appends an L at the end like this </p> <p>111111111111111111111111111111111111111111111111111111111111L</p> <p>thus affecting my calculations on it .. how can i remove it?</p> <pre><code>import math t=raw_input() l1=[] a=0 while (str(t)!="" and int(t)!= 0): l=1 k=int(t) while(k!= 1): l=l+1 a=(0.5 + 2.5*(k %2))*k + k % 2 k=a l1.append(l) t=raw_input() a=a+1 for i in range(0,int(a)): print l1[i] </code></pre> <p>this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111</p> <p>so i guess something is wrong when python considers such a huge number</p>
0
2009-06-13T18:24:05Z
991,421
<p>Another way to avoid numerical errors in python is to use Decimal type instead of standard float. </p> <p>Please refer to <a href="http://docs.python.org/library/decimal.html" rel="nofollow">official docs</a></p>
2
2009-06-13T20:12:46Z
[ "python" ]
Deleting files by type in Python on Windows
991,279
<p>I know how to delete single files, however I am lost in my implementation of how to delete all files in a directory of one type.</p> <p>Say the directory is \myfolder</p> <p>I want to delete all files that are .config files, but nothing to the other ones. How would I do this?</p> <p>Thanks Kindly</p>
6
2009-06-13T19:00:23Z
991,302
<p>I would do something like the following:</p> <pre><code>import os files = os.listdir("myfolder") for f in files: if not os.path.isdir(f) and ".config" in f: os.remove(f) </code></pre> <p>It lists the files in a directory and if it's not a directory and the filename has ".config" anywhere in it, delete it. You'll either need to be in the same directory as myfolder, or give it the full path to the directory. If you need to do this recursively, I would use the os.walk <a href="http://docs.python.org/library/os.html#os.walk" rel="nofollow">function</a>. </p>
4
2009-06-13T19:10:30Z
[ "python", "file" ]
Deleting files by type in Python on Windows
991,279
<p>I know how to delete single files, however I am lost in my implementation of how to delete all files in a directory of one type.</p> <p>Say the directory is \myfolder</p> <p>I want to delete all files that are .config files, but nothing to the other ones. How would I do this?</p> <p>Thanks Kindly</p>
6
2009-06-13T19:00:23Z
991,306
<p>Use the <a href="http://docs.python.org/library/glob.html"><code>glob</code></a> module:</p> <pre><code>import os from glob import glob for f in glob ('myfolder/*.config'): os.unlink (f) </code></pre>
15
2009-06-13T19:13:30Z
[ "python", "file" ]
Deleting files by type in Python on Windows
991,279
<p>I know how to delete single files, however I am lost in my implementation of how to delete all files in a directory of one type.</p> <p>Say the directory is \myfolder</p> <p>I want to delete all files that are .config files, but nothing to the other ones. How would I do this?</p> <p>Thanks Kindly</p>
6
2009-06-13T19:00:23Z
991,311
<p>Here ya go:</p> <pre><code>import os # Return all files in dir, and all its subdirectories, ending in pattern def gen_files(dir, pattern): for dirname, subdirs, files in os.walk(dir): for f in files: if f.endswith(pattern): yield os.path.join(dirname, f) # Remove all files in the current dir matching *.config for f in gen_files('.', '.config'): os.remove(f) </code></pre> <p>Note also that <code>gen_files</code> can be easily rewritten to accept a tuple of patterns, since <code>str.endswith</code> accepts a tuple</p>
1
2009-06-13T19:16:40Z
[ "python", "file" ]
Counting repeated characters in a string in Python
991,350
<p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?</p> <p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372">Anthony's answer</a>): Whatever you have suggested till now I have to write 26 times. Is there an easier way?</p>
21
2009-06-13T19:37:41Z
991,372
<p>You want to use a <a href="http://docs.python.org/library/stdtypes.html#dict" rel="nofollow">dict</a>.</p> <pre><code>#!/usr/bin/env python input = "this is a string" d = {} for c in input: try: d[c] += 1 except: d[c] = 1 for k in d.keys(): print "%s: %d" % (k, d[k]) </code></pre>
2
2009-06-13T19:50:38Z
[ "python" ]
Counting repeated characters in a string in Python
991,350
<p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?</p> <p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372">Anthony's answer</a>): Whatever you have suggested till now I have to write 26 times. Is there an easier way?</p>
21
2009-06-13T19:37:41Z
991,374
<pre><code>import collections d = collections.defaultdict(int) for c in thestring: d[c] += 1 </code></pre> <p>A <code>collections.defaultdict</code> is like a <code>dict</code> (subclasses it, actually), but when an entry is sought and not found, instead of reporting it doesn't have it, it makes it and inserts it by calling the supplied 0-argument callable. Most popular are <code>defaultdict(int)</code>, for counting (or, equivalently, to make a multiset AKA bag data structure), and <code>defaultdict(list)</code>, which does away forever with the need to use <code>.setdefault(akey, []).append(avalue)</code> and similar awkward idioms.</p> <p>So once you've done this <code>d</code> is a dict-like container mapping every character to the number of times it appears, and you can emit it any way you like, of course. For example, most-popular character first:</p> <pre><code>for c in sorted(d, key=d.get, reverse=True): print '%s %6d' % (c, d[c]) </code></pre>
79
2009-06-13T19:51:22Z
[ "python" ]
Counting repeated characters in a string in Python
991,350
<p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?</p> <p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372">Anthony's answer</a>): Whatever you have suggested till now I have to write 26 times. Is there an easier way?</p>
21
2009-06-13T19:37:41Z
991,376
<p>You can use a dictionary:</p> <pre><code>s = "asldaksldkalskdla" dict = {} for letter in s: if letter not in dict.keys(): dict[letter] = 1 else: dict[letter] += 1 print dict </code></pre>
1
2009-06-13T19:52:17Z
[ "python" ]
Counting repeated characters in a string in Python
991,350
<p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?</p> <p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372">Anthony's answer</a>): Whatever you have suggested till now I have to write 26 times. Is there an easier way?</p>
21
2009-06-13T19:37:41Z
991,379
<p>My first idea was to do this:</p> <pre><code>chars = "abcdefghijklmnopqrstuvwxyz" check_string = "i am checking this string to see how many times each character appears" for char in chars: count = check_string.count(char) if count &gt; 1: print char, count </code></pre> <p>This is not a good idea, however! This is going to scan the string 26 times, so you're going to potentially do 26 times more work than some of the other answers. You really should do this:</p> <pre><code>count = {} for s in check_string: if count.has_key(s): count[s] += 1 else: count[s] = 1 for key in count: if count[key] &gt; 1: print key, count[key] </code></pre> <p>This ensures that you only go through the string once, instead of 26 times. </p> <p><strong>Also, Alex's answer is a great one - I was not familiar with the collections module. I'll be using that in the future. His answer is more concise than mine is and technically superior. I recommend using his code over mine.</strong></p>
18
2009-06-13T19:54:45Z
[ "python" ]
Counting repeated characters in a string in Python
991,350
<p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?</p> <p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372">Anthony's answer</a>): Whatever you have suggested till now I have to write 26 times. Is there an easier way?</p>
21
2009-06-13T19:37:41Z
991,475
<p>This is the shortest, most practical I can comeup with without importing extra modules.</p> <pre><code>text = "hello cruel world. This is a sample text" d = dict.fromkeys(text, 0) for c in text: d[c] += 1 </code></pre> <p>print d['a'] would output 2</p> <p>And it's also fast.</p>
12
2009-06-13T20:40:15Z
[ "python" ]
Counting repeated characters in a string in Python
991,350
<p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?</p> <p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372">Anthony's answer</a>): Whatever you have suggested till now I have to write 26 times. Is there an easier way?</p>
21
2009-06-13T19:37:41Z
991,520
<p>I can count the number of days I know Python on my two hands so forgive me if I answer something silly :)</p> <p>Instead of using a dict, I thought why not use a list? I'm not sure how lists and dictionaries are implemented in Python so this would have to be measured to know what's faster. </p> <p>If this was C++ I would just use a normal c-array/vector for constant time access (that would definitely be faster) but I don't know what the corresponding datatype is in Python (if there's one...):</p> <pre><code>count = [0 for i in range(26)] for c in ''.join(s.lower().split()): # get rid of whitespaces and capital letters count[ord(c) - 97] += 1 # ord('a') == 97 </code></pre> <p>It's also possible to make the list's size ord('z') and then get rid of the 97 subtraction everywhere, but if you optimize, why not all the way :)</p> <p>EDIT: A commenter suggested that the join/split is not worth the possible gain of using a list, so I thought why not get rid of it:</p> <pre><code>count = [0 for i in range(26)] for c in s: if c.isalpha(): count[ord(c.lower()) - 97] += 1 </code></pre>
1
2009-06-13T21:07:54Z
[ "python" ]
Counting repeated characters in a string in Python
991,350
<p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?</p> <p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372">Anthony's answer</a>): Whatever you have suggested till now I have to write 26 times. Is there an easier way?</p>
21
2009-06-13T19:37:41Z
993,044
<p>Python 2.7+ includes the <a href="http://docs.python.org/dev/py3k/library/collections.html#collections.Counter" rel="nofollow">collections.Counter</a> class:</p> <pre><code>import collections results = collections.Counter(the_string) print(results) </code></pre>
17
2009-06-14T15:39:00Z
[ "python" ]
Counting repeated characters in a string in Python
991,350
<p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?</p> <p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372">Anthony's answer</a>): Whatever you have suggested till now I have to write 26 times. Is there an easier way?</p>
21
2009-06-13T19:37:41Z
20,486,518
<p>Here is the solution..</p> <pre><code>my_list=[] history="" history_count=0 my_str="happppyyyy" for letter in my_str: if letter in history: my_list.remove((history,history_count)) history=letter history_count+=1 else: history_count=0 history_count+=1 history=letter my_list.append((history,history_count)) print my_list </code></pre>
0
2013-12-10T05:03:16Z
[ "python" ]
Counting repeated characters in a string in Python
991,350
<p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?</p> <p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372">Anthony's answer</a>): Whatever you have suggested till now I have to write 26 times. Is there an easier way?</p>
21
2009-06-13T19:37:41Z
27,667,665
<p>If someone is looking for the simplest way without <code>collections</code> module. I guess this will be helpful:</p> <pre><code>&gt;&gt;&gt; s = "asldaksldkalskdla" &gt;&gt;&gt; {i:s.count(i) for i in set(s)} {'a': 4, 'd': 3, 'k': 3, 's': 3, 'l': 4} </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; [(i,s.count(i)) for i in set(s)] [('a', 4), ('k', 3), ('s', 3), ('l', 4), ('d', 3)] </code></pre>
2
2014-12-27T13:22:49Z
[ "python" ]
Counting repeated characters in a string in Python
991,350
<p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?</p> <p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372">Anthony's answer</a>): Whatever you have suggested till now I have to write 26 times. Is there an easier way?</p>
21
2009-06-13T19:37:41Z
28,789,528
<pre><code>dict = {} for i in set(str): b = str.count(i, 0, len(str)) dict[i] = b print dict </code></pre> <p>If my string is:</p> <pre><code>str = "this is string!" </code></pre> <p>Above code will print:</p> <pre><code>{'!': 1, ' ': 2, 'g': 1, 'i': 3, 'h': 1, 'n': 1, 's': 3, 'r': 1, 't': 2} </code></pre>
2
2015-03-01T02:46:12Z
[ "python" ]
Counting repeated characters in a string in Python
991,350
<p>I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?</p> <p><strong>Update</strong> (in reference to <a href="http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python/991372#991372">Anthony's answer</a>): Whatever you have suggested till now I have to write 26 times. Is there an easier way?</p>
21
2009-06-13T19:37:41Z
32,354,951
<p>this will show a dict of characters with occurrence count</p> <pre><code>str = 'aabcdefghijklmnopqrstuvwxyz' mydict = {} for char in str: mydict[char]=mydict.get(char,0)+1 print mydict </code></pre>
1
2015-09-02T13:45:46Z
[ "python" ]
re.search() breaks for key in form.keys() loop
991,351
<p>Perhaps I am just crazy or missing something really basic. Why would this happen?</p> <p>If I use this url</p> <p>index.cgi?mode=pos&amp;pos_mode=checkout&amp;0_name=Shampoo&amp;0_type=Product&amp;0_price=4.50&amp;0_qty=1&amp;0_total=4.50</p> <p>which runs this code</p> <pre><code>form = cgi.FieldStorage() for key in form.keys() print key if re.search("name", key): print "Found name." </code></pre> <p>The result prints</p> <pre> mode </pre> <p>If I remove the re.search() it prints all the keys. Why?</p> <p>I searched stackoverflow and google before I posted but I didn't come up with anything. Thanks in advance.</p>
0
2009-06-13T19:38:04Z
991,377
<p>Perhaps you get an error? Try checking types of all keys or anything you suspect could be wrong.</p>
1
2009-06-13T19:53:14Z
[ "python" ]
re.search() breaks for key in form.keys() loop
991,351
<p>Perhaps I am just crazy or missing something really basic. Why would this happen?</p> <p>If I use this url</p> <p>index.cgi?mode=pos&amp;pos_mode=checkout&amp;0_name=Shampoo&amp;0_type=Product&amp;0_price=4.50&amp;0_qty=1&amp;0_total=4.50</p> <p>which runs this code</p> <pre><code>form = cgi.FieldStorage() for key in form.keys() print key if re.search("name", key): print "Found name." </code></pre> <p>The result prints</p> <pre> mode </pre> <p>If I remove the re.search() it prints all the keys. Why?</p> <p>I searched stackoverflow and google before I posted but I didn't come up with anything. Thanks in advance.</p>
0
2009-06-13T19:38:04Z
991,380
<p>Are you getting an exception? Check your server logs. Have you done:</p> <pre><code>import re </code></pre> <p>at the top of the script? Try wrapping the code in <code>try</code> / <code>except</code>.</p>
3
2009-06-13T19:54:45Z
[ "python" ]
Code reuse between django and appengine Model classes
991,611
<p>I created a custom django.auth User class which works with Google Appengine, but it involves a fair amount of copied code (practically every method).</p> <p>It isn't possible to create a subclass because appengine and django have different database models with their own metaclass magic. </p> <p>So my question is this: is there an elegant way to copy methods from django.auth's User class?</p> <pre><code>from google.appengine.ext import db from django.contrib.auth import models class User(db.Model): password = db.StringProperty() ... # copied method set_password = models.User.set_password.im_func </code></pre>
1
2009-06-13T22:00:40Z
991,712
<p>Im not sure I understand your question right. Why would you need to define another "User" class if Django already provides the same functionality ? </p> <p>You could also just import the "User" class and add a ForeignKey to each model requiring a "user" attribute.</p>
0
2009-06-13T22:56:01Z
[ "python", "django", "google-app-engine", "django-authentication" ]
Code reuse between django and appengine Model classes
991,611
<p>I created a custom django.auth User class which works with Google Appengine, but it involves a fair amount of copied code (practically every method).</p> <p>It isn't possible to create a subclass because appengine and django have different database models with their own metaclass magic. </p> <p>So my question is this: is there an elegant way to copy methods from django.auth's User class?</p> <pre><code>from google.appengine.ext import db from django.contrib.auth import models class User(db.Model): password = db.StringProperty() ... # copied method set_password = models.User.set_password.im_func </code></pre>
1
2009-06-13T22:00:40Z
996,521
<p>You might want to take a look at what the django helper or app-engine-patch does.</p> <p>Helper: <a href="http://code.google.com/p/google-app-engine-django/" rel="nofollow">http://code.google.com/p/google-app-engine-django/</a> Patch: <a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">http://code.google.com/p/app-engine-patch/</a></p>
0
2009-06-15T14:44:56Z
[ "python", "django", "google-app-engine", "django-authentication" ]
Very simple Python script, puzzling behaviour
991,784
<p>first of all, I'm not a programmer, so the answer to this might be completely obvious to someone more experienced. I was playing around with python(2.5) to solve some probability puzzle, however I kept getting results which were way off from the mark I thought they should be. So after some experimenting, I managed to identify the behaviour which was causing the problem. The script which seemed to isolate the weird behaviour is this:</p> <pre><code>import random random.seed() reps = 1000000 sub = [0]*10 hits = 0 first = random.randint(0,9) while True: second = random.randint(0,9) if second != first: break sub[first] = 1 sub[second] = 1 sub[random.randint(0,9)] = 1 for i in range(1,reps): first = random.randint(0,9) while True: second = random.randint(0,9) if second != first: break if ((sub[first]) or (sub[second])): hits = hits + 1 print "result: ", hits*1.0/reps*100.0 </code></pre> <p>Now, this is not the problem I was initially trying to solve and the result for this script should be 34/90 or around 37.7 which is simple enough combinatorics. Sometimes, the script does give that result, however more often it gives 53.4, which seems to make no sense. This is pretty much just idle curiosity as to why exactly this script behaves like it does. </p>
1
2009-06-13T23:35:57Z
991,791
<p>The result depends on whether line 13:</p> <pre><code>sub[random.randint(0,9)] = 1 </code></pre> <p>hits the same index as one of lines 11 or 12:</p> <pre><code>sub[first] = 1 sub[second] = 1 </code></pre> <p>You protect <code>second</code> from being the same as <code>first</code>, but you don't protect that third entry from being the same as one of <code>first</code> or <code>second</code>.</p>
3
2009-06-13T23:40:14Z
[ "python" ]
Very simple Python script, puzzling behaviour
991,784
<p>first of all, I'm not a programmer, so the answer to this might be completely obvious to someone more experienced. I was playing around with python(2.5) to solve some probability puzzle, however I kept getting results which were way off from the mark I thought they should be. So after some experimenting, I managed to identify the behaviour which was causing the problem. The script which seemed to isolate the weird behaviour is this:</p> <pre><code>import random random.seed() reps = 1000000 sub = [0]*10 hits = 0 first = random.randint(0,9) while True: second = random.randint(0,9) if second != first: break sub[first] = 1 sub[second] = 1 sub[random.randint(0,9)] = 1 for i in range(1,reps): first = random.randint(0,9) while True: second = random.randint(0,9) if second != first: break if ((sub[first]) or (sub[second])): hits = hits + 1 print "result: ", hits*1.0/reps*100.0 </code></pre> <p>Now, this is not the problem I was initially trying to solve and the result for this script should be 34/90 or around 37.7 which is simple enough combinatorics. Sometimes, the script does give that result, however more often it gives 53.4, which seems to make no sense. This is pretty much just idle curiosity as to why exactly this script behaves like it does. </p>
1
2009-06-13T23:35:57Z
991,810
<p>BTW, for the best way to "generate 3 different randomly distributed integers between 0 and 9 included", I heartily recommend <code>a, b, c = random.sample(xrange(10), 3)</code> [[s/xrange/range/ in Python 3.0]] rather than the <code>while</code> loops you're using.</p>
5
2009-06-13T23:51:38Z
[ "python" ]
Changing brightness of the Macbook(Pro) keyboard backlight
991,813
<p>Programaticly, how can I modify the brightness of the backlit keyboard on a Macbook or Macbook Pro using Python?</p>
3
2009-06-13T23:52:27Z
991,823
<p>Amit Singh discusses these undocumented APIs in this <a href="http://www.osxbook.com/book/bonus/chapter10/light/" rel="nofollow">online bonus chapter</a>, but does so using C -- I'm not sure if a Python extension exists to do the same work from Python, perhaps as part of PyObjC (otherwise, such an extension would have to be written -- or <code>ctypes</code> used to access the shared C libraries directly from Python [shudder;-)]).</p>
8
2009-06-13T23:58:38Z
[ "python", "osx", "hardware" ]