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 |
|---|---|---|---|---|---|---|---|---|---|
Can I write Python web application for Windows and Linux platforms at the same time?
| 662,762
|
<p>Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?</p>
<p>CGI? Maybe something new? WSGI | FastCGI ? </p>
| 3
|
2009-03-19T15:52:10Z
| 663,372
|
<p>Writing python web apps is a topic on itself, but I would say that by default, it will be portable on multiple servers / platforms. </p>
<p>When developping python web applications, you will often use frameworks that provide their own web server. For performance reasons, you might want to place it behind apache, but it is not even necessary, however, you might get a performance boost by placing it behind an apache server.</p>
<p>Some of the most popular frameworks for web python are : Plone, Zope, CherryPy and TurboGears, only to name a few.</p>
<p>Under apache, you could also use python server pages through mod_python, and since apache runs on windows too, this would aslo be portable.</p>
| 0
|
2009-03-19T18:09:19Z
|
[
"python",
"cgi",
"fastcgi",
"wsgi"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 663,175
|
<pre><code>>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
</code></pre>
<p>Python calls this concept "slicing" and it works on more than just strings. Take a look <a href="http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation">here</a> for a comprehensive introduction.</p>
| 1,557
|
2009-03-19T17:30:44Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 663,177
|
<p>Yes there is. Your example is very close:</p>
<pre><code>myString[2:]
</code></pre>
| 13
|
2009-03-19T17:30:50Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 663,178
|
<p><code>myString[2:]</code> .. leave off the second index to go to the end</p>
| 5
|
2009-03-19T17:30:56Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 663,182
|
<p><code>mystring[2:]</code> </p>
| 4
|
2009-03-19T17:31:15Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 663,185
|
<p>You've got it right there except for "end". Its called slice notation. Your example should read.</p>
<pre><code>new_sub_string = myString[2:]
</code></pre>
<p>If you leave out the second param it is implicitly the end of the string.</p>
| 5
|
2009-03-19T17:31:34Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 663,333
|
<p>One example seems to be missing here: full (shallow) copy.</p>
<pre><code>>>> x = "Hello World!"
>>> x
'Hello World!'
>>> x[:]
'Hello World!'
>>> x==x[:]
True
>>>
</code></pre>
<p>This is a common idiom for creating a copy of sequence types (not of interned strings). <code>[:]</code> Shallow copies a list, See <a href="http://stackoverflow.com/questions/323689/python-list-slice-used-for-no-obvious-reason">python-list-slice-used-for-no-obvious-reason</a>.</p>
| 20
|
2009-03-19T18:02:38Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 9,528,361
|
<p>A common way to achieve this is by String slicing. <code>MyString[a:b]</code> gives you a substring from index a to (b - 1)</p>
| 34
|
2012-03-02T05:19:02Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 9,780,082
|
<p>Just for completeness as nobody else has mentioned it. The third parameter to an array slice is a step. So reversing a string is as simple as:</p>
<pre><code>some_string[::-1]
</code></pre>
<p>Or selecting alternate characters would be:</p>
<pre><code>"H-e-l-l-o- -W-o-r-l-d"[::2] # outputs "Hello World"
</code></pre>
<p>The ability to step forwards and backwards through the string maintains consistency with being able to array slice from the start or end.</p>
| 196
|
2012-03-20T00:58:50Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 11,698,785
|
<p>here is some method to do sub string.using slicing and dicing.</p>
<pre><code>>>> a = "Hello World"
>>> a[1:]
'ello World'
>>> a[2:]
'llo World'
>>> a[:1]
'H'
>>> a[:2]
'He'
>>> a[-1:]
'd'
>>> a[-2:]
'ld'
>>> a[:-1]
'Hello Worl'
>>> a[:-2]
'Hello Wor'
</code></pre>
| 4
|
2012-07-28T06:15:51Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 11,808,384
|
<p>Substr() normally (i.e. PHP, Perl) works this way: </p>
<pre><code>s = Substr(s, beginning, LENGTH)
</code></pre>
<p>So the parameters are beginning and LENGTH</p>
<p>But Python's behaviour is different, it expects beginning and one after END (!). <strong>This is difficult to spot by beginners.</strong> So the correct replacement for Substr(s, beginning, LENGTH) is</p>
<pre><code>s = s[ beginning : beginning + LENGTH]
</code></pre>
| 49
|
2012-08-04T11:43:03Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 29,121,528
|
<p>Maybe I missed it, but I couldn't find a complete answer on this page to the original question(s) because variables are not further discussed here. So I had to go on searching.</p>
<p>Since I'm not yet allowed to comment, let me add my conclusion here. I'm sure I was not the only one interested in it when accessing this page: </p>
<pre><code> >>>myString = 'Hello World'
>>>end = 5
>>>myString[2:end]
'llo'
</code></pre>
<p>If you leave the first part, you get </p>
<pre><code> >>>myString[:end]
'Hello'
</code></pre>
<p>And if you left the : in the middle as well you got the simplest substring, which would be the 5th character (count starting with 0, so it's the blank in this case):</p>
<pre><code> >>>myString[end]
' '
</code></pre>
| 4
|
2015-03-18T12:01:43Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 39,240,743
|
<p>I would like to add two points to the discussion:</p>
<ol>
<li><p>You can use <code>None</code> instead on an empty space to specify "from the start" or "to the end":</p>
<pre><code>'abcde'[2:None] == 'abcde'[2:] == 'cde'
</code></pre>
<p>This is particularly helpful in functions:</p>
<pre><code>def remove_from_tail(string, n_char=None):
"""Remove `n_char` from the end of `string`."""
return string[:-n_char if n_char >= 1 else None]
</code></pre></li>
<li><p>Python has <a href="https://docs.python.org/3/library/functions.html#slice" rel="nofollow">slice</a> objects:</p>
<pre><code>idx = slice(2, None)
'abcde'[idx] == 'abcde'[2:] == 'cde'
</code></pre></li>
</ol>
| 0
|
2016-08-31T04:28:09Z
|
[
"python",
"string"
] |
Is there a way to substring a string in Python?
| 663,171
|
<p>Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?</p>
<p>Maybe like <code>myString[2:end]</code>?</p>
<p>If leaving the second part means 'till the end', if you leave the first part, does it start from the start?</p>
| 990
|
2009-03-19T17:29:41Z
| 39,240,974
|
<p>No one mention about using hardcode indexes itself can be a mess. </p>
<p>In order to avoid that, python offers a built-in object <code>slice()</code>. </p>
<pre><code>string = "my company has 1000$ on profit, but I lost 500$ gambling."
</code></pre>
<p>If we want to know how many money I got left. </p>
<p>Normal solution:</p>
<pre><code>final = int(string[15:19]) - int(string[43:46])
print(final)
>>>500
</code></pre>
<p>Using slices:</p>
<pre><code>EARNINGS = slice(15,19)
LOSSES = slice(43,46)
final = int(string[EARNINGS]) - int(string[LOSSES])
print(final)
>>>500
</code></pre>
<p>You can notice using slice you gain readability</p>
| 0
|
2016-08-31T04:50:52Z
|
[
"python",
"string"
] |
Python: How do you login to a page and view the resulting page in a browser?
| 663,490
|
<p>I've been googling around for quite some time now and can't seem to get this to work. A lot of my searches have pointed me to finding similar problems but they all seem to be related to cookie grabbing/storing. I think I've set that up properly, but when I try to open the 'hidden' page, it keeps bringing me back to the login page saying my session has expired.</p>
<pre><code>import urllib, urllib2, cookielib, webbrowser
username = 'userhere'
password = 'passwordhere'
url = 'http://example.com'
webbrowser.open(url, new=1, autoraise=1)
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://example.com', login_data)
resp = opener.open('http://example.com/afterlogin')
print resp
webbrowser.open(url, new=1, autoraise=1)
</code></pre>
| 4
|
2009-03-19T18:40:44Z
| 664,126
|
<p>First off, when doing cookie-based authentication, you need to have a <a href="http://docs.python.org/library/cookielib.html#cookielib.CookieJar" rel="nofollow"><code>CookieJar</code></a> to store your cookies in, much in the same way that your browser stores its cookies a place where it can find them again.</p>
<p>After opening a login-page through python, and saving the cookie from a successful login, you should use the <a href="http://docs.python.org/library/cookielib.html#cookielib.MozillaCookieJar" rel="nofollow"><code>MozillaCookieJar</code></a> to pass the python created cookies to a format a firefox browser can parse. Firefox 3.x no longer uses the cookie format that MozillaCookieJar produces, and I have not been able to find viable alternatives.</p>
<p>If all you need to do is to retrieve specific (in advance known format formatted) data, then I suggest you keep all your HTTP interactions within python. It is much easier, and you don't have to rely on specific browsers being available. If it is absolutely necessary to show stuff in a browser, you could render the so-called 'hidden' page through urllib2 (which incidentally integrates very nicely with cookielib), save the html to a temporary file and pass this to the <a href="http://docs.python.org/library/webbrowser.html?highlight=webbrowser#webbrowser.open" rel="nofollow"><code>webbrowser.open</code></a> which will then render that specific page. Further redirects are not possible.</p>
| 4
|
2009-03-19T21:21:16Z
|
[
"python",
"login"
] |
Python: How do you login to a page and view the resulting page in a browser?
| 663,490
|
<p>I've been googling around for quite some time now and can't seem to get this to work. A lot of my searches have pointed me to finding similar problems but they all seem to be related to cookie grabbing/storing. I think I've set that up properly, but when I try to open the 'hidden' page, it keeps bringing me back to the login page saying my session has expired.</p>
<pre><code>import urllib, urllib2, cookielib, webbrowser
username = 'userhere'
password = 'passwordhere'
url = 'http://example.com'
webbrowser.open(url, new=1, autoraise=1)
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://example.com', login_data)
resp = opener.open('http://example.com/afterlogin')
print resp
webbrowser.open(url, new=1, autoraise=1)
</code></pre>
| 4
|
2009-03-19T18:40:44Z
| 683,596
|
<p>I've generally used the <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize library</a> to handle stuff like this. That doesn't answer your question about why your existing code isn't working, but it's something else to play with.</p>
| 1
|
2009-03-25T21:41:43Z
|
[
"python",
"login"
] |
Python: How do you login to a page and view the resulting page in a browser?
| 663,490
|
<p>I've been googling around for quite some time now and can't seem to get this to work. A lot of my searches have pointed me to finding similar problems but they all seem to be related to cookie grabbing/storing. I think I've set that up properly, but when I try to open the 'hidden' page, it keeps bringing me back to the login page saying my session has expired.</p>
<pre><code>import urllib, urllib2, cookielib, webbrowser
username = 'userhere'
password = 'passwordhere'
url = 'http://example.com'
webbrowser.open(url, new=1, autoraise=1)
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://example.com', login_data)
resp = opener.open('http://example.com/afterlogin')
print resp
webbrowser.open(url, new=1, autoraise=1)
</code></pre>
| 4
|
2009-03-19T18:40:44Z
| 692,163
|
<p>The provided code calls:</p>
<pre><code>opener.open('http://example.com', login_data)
</code></pre>
<p>but throws away the response. I would look at this response to see if it says "Bad password" or "I only accept IE" or similar.</p>
| 0
|
2009-03-28T04:02:01Z
|
[
"python",
"login"
] |
Looking for knowledge base integrated with bug tracker in python
| 663,603
|
<p>Ok, I am not sure I want to use Request Tracker and RTFM, which is a possible solution.</p>
<p>I'd like to have a knowledge base with my bug tracker/todo list , so that when
I solve a problem, I would have a record of its resolution for myself or others later.</p>
<p>What python based solutions are available?</p>
| 4
|
2009-03-19T19:12:19Z
| 663,618
|
<p>Try <a href="http://trac.edgewall.org/" rel="nofollow">Trac</a></p>
| 4
|
2009-03-19T19:13:48Z
|
[
"python",
"knowledge-management"
] |
Looking for knowledge base integrated with bug tracker in python
| 663,603
|
<p>Ok, I am not sure I want to use Request Tracker and RTFM, which is a possible solution.</p>
<p>I'd like to have a knowledge base with my bug tracker/todo list , so that when
I solve a problem, I would have a record of its resolution for myself or others later.</p>
<p>What python based solutions are available?</p>
| 4
|
2009-03-19T19:12:19Z
| 671,744
|
<p>A highly flexible issue tracker in Python I would recommend is "Roundup":
<a href="http://roundup.sourceforge.net/" rel="nofollow">http://roundup.sourceforge.net/</a>.</p>
<p>An example of its use can be seen online at <a href="http://bugs.python.org/" rel="nofollow">http://bugs.python.org/</a>.</p>
| 4
|
2009-03-22T22:50:50Z
|
[
"python",
"knowledge-management"
] |
Looking for knowledge base integrated with bug tracker in python
| 663,603
|
<p>Ok, I am not sure I want to use Request Tracker and RTFM, which is a possible solution.</p>
<p>I'd like to have a knowledge base with my bug tracker/todo list , so that when
I solve a problem, I would have a record of its resolution for myself or others later.</p>
<p>What python based solutions are available?</p>
| 4
|
2009-03-19T19:12:19Z
| 22,592,567
|
<p>I do have experience using probably 20-30 different bug trackers, installed or hosted and so far if you are up to deal with a big number of bugs and you want to spend less time coding-the-issues-tracker, to get Atlassian Jira, which is free for open-source projects.</p>
<p>Yes, it's not Python, it is Java, starts slowly and requires lots of resources. At the same time, RAM is far less expensive than your own time and if you want to extend the system you can do it in Python by using <a href="https://pypi.python.org/pypi/jira-python/" rel="nofollow">https://pypi.python.org/pypi/jira-python/</a> </p>
<p>Do you think that Jira is the most used bug tracker for no reason? It wasn't the first on the market, in fact is quite new compared with others. </p>
<p>Once deployed you can focus on improving the workflows instead of patching the bug tracker. </p>
<p>One of the best features that it has is the ability to link to external issues and be able to see their status, without having to click on them. As an warning, for someone coming from another tracekr you may discover that there are some design limitations, like the fact that a bug can have a single assignee. Don't be scared about it, if you look further you will find that there are way to assign tickets to groups of peoples.</p>
| 0
|
2014-03-23T15:03:07Z
|
[
"python",
"knowledge-management"
] |
What's the difference between dict() and {}?
| 664,118
|
<p>So let's say I wanna make a dictionary. We'll call it <code>d</code>. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:</p>
<pre><code>d = {'hash': 'bang', 'slash': 'dot'}
</code></pre>
<p>Or I could do this:</p>
<pre><code>d = dict(hash='bang', slash='dot')
</code></pre>
<p>Or this, curiously:</p>
<pre><code>d = dict({'hash': 'bang', 'slash': 'dot'})
</code></pre>
<p>Or this:</p>
<pre><code>d = dict([['hash', 'bang'], ['slash', 'dot']])
</code></pre>
<p>And a whole other multitude of ways with the <code>dict()</code> function. So obviously one of the things <code>dict()</code> provides is flexibility in syntax and initialization. But that's not what I'm asking about.</p>
<p>Say I were to make <code>d</code> just an empty dictionary. What goes on behind the scenes of the Python interpreter when I do <code>d = {}</code> versus <code>d = dict()</code>? Is it simply two ways to do the same thing? Does using <code>{}</code> have the <i>additional</i> call of <code>dict()</code>? Does one have (even negligible) more overhead than the other? While the question is really completely unimportant, it's a curiosity I would love to have answered.</p>
| 39
|
2009-03-19T21:19:58Z
| 664,143
|
<pre><code>>>> def f():
... return {'a' : 1, 'b' : 2}
...
>>> def g():
... return dict(a=1, b=2)
...
>>> g()
{'a': 1, 'b': 2}
>>> f()
{'a': 1, 'b': 2}
>>> import dis
>>> dis.dis(f)
2 0 BUILD_MAP 0
3 DUP_TOP
4 LOAD_CONST 1 ('a')
7 LOAD_CONST 2 (1)
10 ROT_THREE
11 STORE_SUBSCR
12 DUP_TOP
13 LOAD_CONST 3 ('b')
16 LOAD_CONST 4 (2)
19 ROT_THREE
20 STORE_SUBSCR
21 RETURN_VALUE
>>> dis.dis(g)
2 0 LOAD_GLOBAL 0 (dict)
3 LOAD_CONST 1 ('a')
6 LOAD_CONST 2 (1)
9 LOAD_CONST 3 ('b')
12 LOAD_CONST 4 (2)
15 CALL_FUNCTION 512
18 RETURN_VALUE
</code></pre>
<p>dict() is apparently some C built-in. A really smart or dedicated person (not me) could look at the interpreter source and tell you more. I just wanted to show off dis.dis. :)</p>
| 55
|
2009-03-19T21:25:14Z
|
[
"python",
"initialization",
"instantiation"
] |
What's the difference between dict() and {}?
| 664,118
|
<p>So let's say I wanna make a dictionary. We'll call it <code>d</code>. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:</p>
<pre><code>d = {'hash': 'bang', 'slash': 'dot'}
</code></pre>
<p>Or I could do this:</p>
<pre><code>d = dict(hash='bang', slash='dot')
</code></pre>
<p>Or this, curiously:</p>
<pre><code>d = dict({'hash': 'bang', 'slash': 'dot'})
</code></pre>
<p>Or this:</p>
<pre><code>d = dict([['hash', 'bang'], ['slash', 'dot']])
</code></pre>
<p>And a whole other multitude of ways with the <code>dict()</code> function. So obviously one of the things <code>dict()</code> provides is flexibility in syntax and initialization. But that's not what I'm asking about.</p>
<p>Say I were to make <code>d</code> just an empty dictionary. What goes on behind the scenes of the Python interpreter when I do <code>d = {}</code> versus <code>d = dict()</code>? Is it simply two ways to do the same thing? Does using <code>{}</code> have the <i>additional</i> call of <code>dict()</code>? Does one have (even negligible) more overhead than the other? While the question is really completely unimportant, it's a curiosity I would love to have answered.</p>
| 39
|
2009-03-19T21:19:58Z
| 664,184
|
<p>As far as performance goes:</p>
<pre><code>>>> from timeit import timeit
>>> timeit("a = {'a': 1, 'b': 2}")
0.424...
>>> timeit("a = dict(a = 1, b = 2)")
0.889...
</code></pre>
| 26
|
2009-03-19T21:41:00Z
|
[
"python",
"initialization",
"instantiation"
] |
What's the difference between dict() and {}?
| 664,118
|
<p>So let's say I wanna make a dictionary. We'll call it <code>d</code>. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:</p>
<pre><code>d = {'hash': 'bang', 'slash': 'dot'}
</code></pre>
<p>Or I could do this:</p>
<pre><code>d = dict(hash='bang', slash='dot')
</code></pre>
<p>Or this, curiously:</p>
<pre><code>d = dict({'hash': 'bang', 'slash': 'dot'})
</code></pre>
<p>Or this:</p>
<pre><code>d = dict([['hash', 'bang'], ['slash', 'dot']])
</code></pre>
<p>And a whole other multitude of ways with the <code>dict()</code> function. So obviously one of the things <code>dict()</code> provides is flexibility in syntax and initialization. But that's not what I'm asking about.</p>
<p>Say I were to make <code>d</code> just an empty dictionary. What goes on behind the scenes of the Python interpreter when I do <code>d = {}</code> versus <code>d = dict()</code>? Is it simply two ways to do the same thing? Does using <code>{}</code> have the <i>additional</i> call of <code>dict()</code>? Does one have (even negligible) more overhead than the other? While the question is really completely unimportant, it's a curiosity I would love to have answered.</p>
| 39
|
2009-03-19T21:19:58Z
| 664,416
|
<p>Basically, {} is syntax and is handled on a language and bytecode level. dict() is just another builtin with a more flexible initialization syntax. Note that dict() was only added in the middle of 2.x series.</p>
| 6
|
2009-03-19T23:15:01Z
|
[
"python",
"initialization",
"instantiation"
] |
What's the difference between dict() and {}?
| 664,118
|
<p>So let's say I wanna make a dictionary. We'll call it <code>d</code>. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:</p>
<pre><code>d = {'hash': 'bang', 'slash': 'dot'}
</code></pre>
<p>Or I could do this:</p>
<pre><code>d = dict(hash='bang', slash='dot')
</code></pre>
<p>Or this, curiously:</p>
<pre><code>d = dict({'hash': 'bang', 'slash': 'dot'})
</code></pre>
<p>Or this:</p>
<pre><code>d = dict([['hash', 'bang'], ['slash', 'dot']])
</code></pre>
<p>And a whole other multitude of ways with the <code>dict()</code> function. So obviously one of the things <code>dict()</code> provides is flexibility in syntax and initialization. But that's not what I'm asking about.</p>
<p>Say I were to make <code>d</code> just an empty dictionary. What goes on behind the scenes of the Python interpreter when I do <code>d = {}</code> versus <code>d = dict()</code>? Is it simply two ways to do the same thing? Does using <code>{}</code> have the <i>additional</i> call of <code>dict()</code>? Does one have (even negligible) more overhead than the other? While the question is really completely unimportant, it's a curiosity I would love to have answered.</p>
| 39
|
2009-03-19T21:19:58Z
| 667,437
|
<p><em>Update</em>: thanks for the responses. Removed speculation about copy-on-write.</p>
<p>One other difference between <code>{}</code> and <code>dict</code> is that <code>dict</code> always allocates a new dictionary (even if the contents are static) whereas <code>{}</code> doesn't <em>always</em> do so (see <a href="http://stackoverflow.com/questions/664118/whats-the-difference-between-dict-and/681358#681358">mgood's answer</a> for when and why):</p>
<pre><code>def dict1():
return {'a':'b'}
def dict2():
return dict(a='b')
print id(dict1()), id(dict1())
print id(dict2()), id(dict2())
</code></pre>
<p>produces:</p>
<pre>
$ ./mumble.py
11642752 11642752
11867168 11867456
</pre>
<p>I'm not suggesting you try to take advantage of this or not, it depends on the particular situation, just pointing it out. (It's also probably evident from the <a href="http://stackoverflow.com/questions/664118/whats-the-difference-between-dict-and/664143#664143">disassembly</a> if you understand the opcodes).</p>
| 3
|
2009-03-20T18:44:30Z
|
[
"python",
"initialization",
"instantiation"
] |
What's the difference between dict() and {}?
| 664,118
|
<p>So let's say I wanna make a dictionary. We'll call it <code>d</code>. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:</p>
<pre><code>d = {'hash': 'bang', 'slash': 'dot'}
</code></pre>
<p>Or I could do this:</p>
<pre><code>d = dict(hash='bang', slash='dot')
</code></pre>
<p>Or this, curiously:</p>
<pre><code>d = dict({'hash': 'bang', 'slash': 'dot'})
</code></pre>
<p>Or this:</p>
<pre><code>d = dict([['hash', 'bang'], ['slash', 'dot']])
</code></pre>
<p>And a whole other multitude of ways with the <code>dict()</code> function. So obviously one of the things <code>dict()</code> provides is flexibility in syntax and initialization. But that's not what I'm asking about.</p>
<p>Say I were to make <code>d</code> just an empty dictionary. What goes on behind the scenes of the Python interpreter when I do <code>d = {}</code> versus <code>d = dict()</code>? Is it simply two ways to do the same thing? Does using <code>{}</code> have the <i>additional</i> call of <code>dict()</code>? Does one have (even negligible) more overhead than the other? While the question is really completely unimportant, it's a curiosity I would love to have answered.</p>
| 39
|
2009-03-19T21:19:58Z
| 681,358
|
<p>@Jacob: There is a difference in how the objects are allocated, but they are not copy-on-write. Python allocates a fixed-size "free list" where it can quickly allocate dictionary objects (until it fills). Dictionaries allocated via the <code>{}</code> syntax (or a C call to <code>PyDict_New</code>) can come from this free list. When the dictionary is no longer referenced it gets returned to the free list and that memory block can be reused (though the fields are reset first).</p>
<p>This first dictionary gets immediately returned to the free list, and the next will reuse its memory space:</p>
<pre><code>>>> id({})
340160
>>> id({1: 2})
340160
</code></pre>
<p>If you keep a reference, the next dictionary will come from the next free slot:</p>
<pre><code>>>> x = {}
>>> id(x)
340160
>>> id({})
340016
</code></pre>
<p>But we can delete the reference to that dictionary and free its slot again:</p>
<pre><code>>>> del x
>>> id({})
340160
</code></pre>
<p>Since the <code>{}</code> syntax is handled in byte-code it can use this optimization mentioned above. On the other hand <code>dict()</code> is handled like a regular class constructor and Python uses the generic memory allocator, which does not follow an easily predictable pattern like the free list above.</p>
<p>Also, looking at compile.c from Python 2.6, with the <code>{}</code> syntax it seems to pre-size the hashtable based on the number of items it's storing which is known at parse time.</p>
| 20
|
2009-03-25T12:28:03Z
|
[
"python",
"initialization",
"instantiation"
] |
What's the difference between dict() and {}?
| 664,118
|
<p>So let's say I wanna make a dictionary. We'll call it <code>d</code>. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:</p>
<pre><code>d = {'hash': 'bang', 'slash': 'dot'}
</code></pre>
<p>Or I could do this:</p>
<pre><code>d = dict(hash='bang', slash='dot')
</code></pre>
<p>Or this, curiously:</p>
<pre><code>d = dict({'hash': 'bang', 'slash': 'dot'})
</code></pre>
<p>Or this:</p>
<pre><code>d = dict([['hash', 'bang'], ['slash', 'dot']])
</code></pre>
<p>And a whole other multitude of ways with the <code>dict()</code> function. So obviously one of the things <code>dict()</code> provides is flexibility in syntax and initialization. But that's not what I'm asking about.</p>
<p>Say I were to make <code>d</code> just an empty dictionary. What goes on behind the scenes of the Python interpreter when I do <code>d = {}</code> versus <code>d = dict()</code>? Is it simply two ways to do the same thing? Does using <code>{}</code> have the <i>additional</i> call of <code>dict()</code>? Does one have (even negligible) more overhead than the other? While the question is really completely unimportant, it's a curiosity I would love to have answered.</p>
| 39
|
2009-03-19T21:19:58Z
| 5,837,762
|
<p>dict() is used when you want to create a dictionary from an iterable, like :</p>
<pre><code>dict( generator which yields (key,value) pairs )
dict( list of (key,value) pairs )
</code></pre>
| 0
|
2011-04-29T21:50:46Z
|
[
"python",
"initialization",
"instantiation"
] |
What's the difference between dict() and {}?
| 664,118
|
<p>So let's say I wanna make a dictionary. We'll call it <code>d</code>. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:</p>
<pre><code>d = {'hash': 'bang', 'slash': 'dot'}
</code></pre>
<p>Or I could do this:</p>
<pre><code>d = dict(hash='bang', slash='dot')
</code></pre>
<p>Or this, curiously:</p>
<pre><code>d = dict({'hash': 'bang', 'slash': 'dot'})
</code></pre>
<p>Or this:</p>
<pre><code>d = dict([['hash', 'bang'], ['slash', 'dot']])
</code></pre>
<p>And a whole other multitude of ways with the <code>dict()</code> function. So obviously one of the things <code>dict()</code> provides is flexibility in syntax and initialization. But that's not what I'm asking about.</p>
<p>Say I were to make <code>d</code> just an empty dictionary. What goes on behind the scenes of the Python interpreter when I do <code>d = {}</code> versus <code>d = dict()</code>? Is it simply two ways to do the same thing? Does using <code>{}</code> have the <i>additional</i> call of <code>dict()</code>? Does one have (even negligible) more overhead than the other? While the question is really completely unimportant, it's a curiosity I would love to have answered.</p>
| 39
|
2009-03-19T21:19:58Z
| 37,548,506
|
<p>In order to create an empty set we should use the keyword set before it
i.e <code>set()</code> this creates an empty set where as in dicts only the flower brackets can create an empty dict</p>
<p>Lets go with an example </p>
<pre><code>print isinstance({},dict)
True
print isinstance({},set)
False
print isinstance(set(),set)
True
</code></pre>
| 0
|
2016-05-31T14:30:01Z
|
[
"python",
"initialization",
"instantiation"
] |
Uninitialized value in Python?
| 664,219
|
<p>What's the uninitialized value in Python, so I can compare if something is initialized, like:</p>
<pre><code>val
if val == undefined ?
</code></pre>
<p>EDIT: added a pseudo keyword.</p>
<p>EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.</p>
<h3>Duplicate: <a href="http://stackoverflow.com/questions/664294/just-declaring-a-variable-in-python">Just declaring a variable in Python?</a></h3>
| 2
|
2009-03-19T21:53:47Z
| 664,222
|
<p>Will throw a <code>NameError</code> exception:</p>
<pre><code>>>> val
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'val' is not defined
</code></pre>
<p>You can either catch that or use <code>'val' in dir()</code>, i.e.:</p>
<pre><code>try:
val
except NameError:
print("val not set")
</code></pre>
<p>or</p>
<pre><code>if 'val' in dir():
print('val set')
else:
print('val not set')
</code></pre>
| 8
|
2009-03-19T21:54:54Z
|
[
"python"
] |
Uninitialized value in Python?
| 664,219
|
<p>What's the uninitialized value in Python, so I can compare if something is initialized, like:</p>
<pre><code>val
if val == undefined ?
</code></pre>
<p>EDIT: added a pseudo keyword.</p>
<p>EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.</p>
<h3>Duplicate: <a href="http://stackoverflow.com/questions/664294/just-declaring-a-variable-in-python">Just declaring a variable in Python?</a></h3>
| 2
|
2009-03-19T21:53:47Z
| 664,228
|
<pre><code>try:
print val
except NameError:
print "val wasn't set."
</code></pre>
| 0
|
2009-03-19T21:56:54Z
|
[
"python"
] |
Uninitialized value in Python?
| 664,219
|
<p>What's the uninitialized value in Python, so I can compare if something is initialized, like:</p>
<pre><code>val
if val == undefined ?
</code></pre>
<p>EDIT: added a pseudo keyword.</p>
<p>EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.</p>
<h3>Duplicate: <a href="http://stackoverflow.com/questions/664294/just-declaring-a-variable-in-python">Just declaring a variable in Python?</a></h3>
| 2
|
2009-03-19T21:53:47Z
| 664,230
|
<p>In python, variables either refer to an object, or they don't exist. If they don't exist, you will get a NameError. Of course, one of the objects they might refer to is <code>None</code>.</p>
<pre><code>try:
val
except NameError:
print "val is not set"
if val is None:
print "val is None"
</code></pre>
| 5
|
2009-03-19T21:57:05Z
|
[
"python"
] |
Uninitialized value in Python?
| 664,219
|
<p>What's the uninitialized value in Python, so I can compare if something is initialized, like:</p>
<pre><code>val
if val == undefined ?
</code></pre>
<p>EDIT: added a pseudo keyword.</p>
<p>EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.</p>
<h3>Duplicate: <a href="http://stackoverflow.com/questions/664294/just-declaring-a-variable-in-python">Just declaring a variable in Python?</a></h3>
| 2
|
2009-03-19T21:53:47Z
| 664,234
|
<p>To add to <a href="http://stackoverflow.com/questions/664219/uninitialized-value-of-python/664222#664222">phihag's answer</a>: you can use <a href="http://docs.python.org/library/functions.html#dir" rel="nofollow"><code>dir()</code></a> to get a list of all of the variables in the current scope, so if you want to test if <code>var</code> is in the current scope without using exceptions, you can do:</p>
<pre><code>if 'var' in dir():
# var is in scope
</code></pre>
| 0
|
2009-03-19T21:59:16Z
|
[
"python"
] |
Uninitialized value in Python?
| 664,219
|
<p>What's the uninitialized value in Python, so I can compare if something is initialized, like:</p>
<pre><code>val
if val == undefined ?
</code></pre>
<p>EDIT: added a pseudo keyword.</p>
<p>EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.</p>
<h3>Duplicate: <a href="http://stackoverflow.com/questions/664294/just-declaring-a-variable-in-python">Just declaring a variable in Python?</a></h3>
| 2
|
2009-03-19T21:53:47Z
| 664,256
|
<p>A name does not exist unless a value is assigned to it. There is None, which generally represents no usable value, but it is a value in its own right.</p>
| 5
|
2009-03-19T22:06:40Z
|
[
"python"
] |
Uninitialized value in Python?
| 664,219
|
<p>What's the uninitialized value in Python, so I can compare if something is initialized, like:</p>
<pre><code>val
if val == undefined ?
</code></pre>
<p>EDIT: added a pseudo keyword.</p>
<p>EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.</p>
<h3>Duplicate: <a href="http://stackoverflow.com/questions/664294/just-declaring-a-variable-in-python">Just declaring a variable in Python?</a></h3>
| 2
|
2009-03-19T21:53:47Z
| 664,257
|
<p>In Python, for a variable to exist, something must have been assigned to it. You can think of your variable name as a dictionary key that must have some value associated with it (even if that value is None).</p>
| 1
|
2009-03-19T22:06:50Z
|
[
"python"
] |
Uninitialized value in Python?
| 664,219
|
<p>What's the uninitialized value in Python, so I can compare if something is initialized, like:</p>
<pre><code>val
if val == undefined ?
</code></pre>
<p>EDIT: added a pseudo keyword.</p>
<p>EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.</p>
<h3>Duplicate: <a href="http://stackoverflow.com/questions/664294/just-declaring-a-variable-in-python">Just declaring a variable in Python?</a></h3>
| 2
|
2009-03-19T21:53:47Z
| 664,430
|
<p><strong>Q: How do I discover if a variable is defined at a point in my code?</strong></p>
<p><strong>A: Read up in the source file until you see a line where that variable is defined.</strong></p>
| 0
|
2009-03-19T23:19:25Z
|
[
"python"
] |
Uninitialized value in Python?
| 664,219
|
<p>What's the uninitialized value in Python, so I can compare if something is initialized, like:</p>
<pre><code>val
if val == undefined ?
</code></pre>
<p>EDIT: added a pseudo keyword.</p>
<p>EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.</p>
<h3>Duplicate: <a href="http://stackoverflow.com/questions/664294/just-declaring-a-variable-in-python">Just declaring a variable in Python?</a></h3>
| 2
|
2009-03-19T21:53:47Z
| 664,491
|
<p>This question leads on to some fun diversions concerning the nature of python objects and it's garbage collector:</p>
<p>It's probably helpful to understand that all variables in python are really pointers, that is they are names in a namespace (implemented as a hash-table) whch point to an address in memory where the object actually resides. </p>
<p>Asking for the value of an uninitialized variable is the same as asking for the value of the thing a pointer points to when the pointer has not yet been created yet... it's obviously nonsense which is why the most sensible thing Python can do is throw a meaningful NameError.</p>
<p>Another oddity of the python language is that it's possible that an object exists long before you execute an assignment statement. Consider:</p>
<pre><code>a = 1
</code></pre>
<p>Did you magically create an int(1) object here? Nope - it already existed. Since int(1) is an immutable singleton there are already a few hundred pointers to it:</p>
<pre><code>>>> sys.getrefcount(a)
592
>>>
</code></pre>
<p>Fun, eh?</p>
<p><strong>EDIT:</strong> commment by JFS (posted here to show the code)</p>
<pre><code>>>> a = 1 + 1
>>> sys.getrefcount(a) # integers less than 256 (or so) are cached
145
>>> b = 1000 + 1000
>>> sys.getrefcount(b)
2
>>> sys.getrefcount(2000)
3
>>> sys.getrefcount(1000+1000)
2
</code></pre>
| 1
|
2009-03-19T23:54:06Z
|
[
"python"
] |
Uninitialized value in Python?
| 664,219
|
<p>What's the uninitialized value in Python, so I can compare if something is initialized, like:</p>
<pre><code>val
if val == undefined ?
</code></pre>
<p>EDIT: added a pseudo keyword.</p>
<p>EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.</p>
<h3>Duplicate: <a href="http://stackoverflow.com/questions/664294/just-declaring-a-variable-in-python">Just declaring a variable in Python?</a></h3>
| 2
|
2009-03-19T21:53:47Z
| 665,319
|
<p>Usually a value of <code>None</code> is used to mark something as "declared but not yet initialized; I would consider an uninitialized variable a defekt in the code</p>
| 0
|
2009-03-20T08:19:26Z
|
[
"python"
] |
Is it possible only to declare a variable without assigning any value in Python?
| 664,294
|
<p>Is it possible to declare a variable in Python, like so?:</p>
<pre><code>var
</code></pre>
<p>so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?</p>
<p>EDIT: I want to do this for cases like this:</p>
<pre><code>value
for index in sequence:
if value == None and conditionMet:
value = index
break
</code></pre>
<h3>Duplicate</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/664219/uninitialized-value-in-python">Uninitialised value in python</a> (by same author)</li>
<li><a href="http://stackoverflow.com/questions/571514/are-there-any-declaration-keywords-in-python">Are there any declaration keywords in Python?</a> (by the same author)</li>
</ul>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls">Python: variable scope and function calls</a></li>
<li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables">Other languages have "variables"</a></li>
</ul>
| 113
|
2009-03-19T22:21:53Z
| 664,297
|
<p>Why not just do this:</p>
<pre><code>var = None
</code></pre>
<p>Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above.</p>
<p>This is nice, because you'll never end up with an uninitialized variable. But be careful -- this doesn't mean that you won't end up with <em>incorrectly</em> initialized variables. If you init something to <code>None</code>, make sure that's what you really want, and assign something more meaningful if you can.</p>
| 147
|
2009-03-19T22:23:05Z
|
[
"python",
"variable-assignment",
"variable-declaration"
] |
Is it possible only to declare a variable without assigning any value in Python?
| 664,294
|
<p>Is it possible to declare a variable in Python, like so?:</p>
<pre><code>var
</code></pre>
<p>so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?</p>
<p>EDIT: I want to do this for cases like this:</p>
<pre><code>value
for index in sequence:
if value == None and conditionMet:
value = index
break
</code></pre>
<h3>Duplicate</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/664219/uninitialized-value-in-python">Uninitialised value in python</a> (by same author)</li>
<li><a href="http://stackoverflow.com/questions/571514/are-there-any-declaration-keywords-in-python">Are there any declaration keywords in Python?</a> (by the same author)</li>
</ul>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls">Python: variable scope and function calls</a></li>
<li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables">Other languages have "variables"</a></li>
</ul>
| 113
|
2009-03-19T22:21:53Z
| 664,299
|
<p>I'm not sure what you're trying to do. Python is a very dynamic language; you don't usually need to declare variables until you're actually going to assign to or use them. I think what you want to do is just</p>
<pre><code>foo = None
</code></pre>
<p>which will assign the value <code>None</code> to the variable <code>foo</code>.</p>
<p>EDIT: What you <em>really</em> seem to want to do is just this:</p>
<pre><code>#note how I don't do *anything* with value here
#we can just start using it right inside the loop
for index in sequence:
if conditionMet:
value = index
break
try:
doSomething(value)
except NameError:
print "Didn't find anything"
</code></pre>
<p>It's a little difficult to tell if that's really the right style to use from such a short code example, but it <em>is</em> a more "Pythonic" way to work.</p>
<p>EDIT: below is comment by JFS (posted here to show the code)</p>
<h3>Unrelated to the OP's question but the above code can be rewritten as:</h3>
<pre><code>for item in sequence:
if some_condition(item):
found = True
break
else: # no break or len(sequence) == 0
found = False
if found:
do_something(item)
</code></pre>
<p>NOTE: if <code>some_condition()</code> raises an exception then <code>found</code> is unbound.<br />
NOTE: if len(sequence) == 0 then <code>item</code> is unbound.</p>
<p>The above code is not advisable. Its purpose is to illustrate how local variables work, namely whether "variable" is "defined" could be determined only at runtime in this case.
Preferable way:</p>
<pre><code>for item in sequence:
if some_condition(item):
do_something(item)
break
</code></pre>
<p>Or </p>
<pre><code>found = False
for item in sequence:
if some_condition(item):
found = True
break
if found:
do_something(item)
</code></pre>
| 10
|
2009-03-19T22:24:10Z
|
[
"python",
"variable-assignment",
"variable-declaration"
] |
Is it possible only to declare a variable without assigning any value in Python?
| 664,294
|
<p>Is it possible to declare a variable in Python, like so?:</p>
<pre><code>var
</code></pre>
<p>so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?</p>
<p>EDIT: I want to do this for cases like this:</p>
<pre><code>value
for index in sequence:
if value == None and conditionMet:
value = index
break
</code></pre>
<h3>Duplicate</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/664219/uninitialized-value-in-python">Uninitialised value in python</a> (by same author)</li>
<li><a href="http://stackoverflow.com/questions/571514/are-there-any-declaration-keywords-in-python">Are there any declaration keywords in Python?</a> (by the same author)</li>
</ul>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls">Python: variable scope and function calls</a></li>
<li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables">Other languages have "variables"</a></li>
</ul>
| 113
|
2009-03-19T22:21:53Z
| 664,302
|
<p>I usually initialize the variable to something that denotes the type like</p>
<pre><code>var = ""
</code></pre>
<p>or </p>
<pre><code>var = 0
</code></pre>
<p>If it is going to be an object then don't initialize it until you instantiate it:</p>
<pre><code>var = Var()
</code></pre>
| 2
|
2009-03-19T22:24:31Z
|
[
"python",
"variable-assignment",
"variable-declaration"
] |
Is it possible only to declare a variable without assigning any value in Python?
| 664,294
|
<p>Is it possible to declare a variable in Python, like so?:</p>
<pre><code>var
</code></pre>
<p>so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?</p>
<p>EDIT: I want to do this for cases like this:</p>
<pre><code>value
for index in sequence:
if value == None and conditionMet:
value = index
break
</code></pre>
<h3>Duplicate</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/664219/uninitialized-value-in-python">Uninitialised value in python</a> (by same author)</li>
<li><a href="http://stackoverflow.com/questions/571514/are-there-any-declaration-keywords-in-python">Are there any declaration keywords in Python?</a> (by the same author)</li>
</ul>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls">Python: variable scope and function calls</a></li>
<li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables">Other languages have "variables"</a></li>
</ul>
| 113
|
2009-03-19T22:21:53Z
| 664,352
|
<p>I'd heartily recommend that you read <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables">Other languages have "variables"</a> (I added it as a related link) â in two minutes you'll know that Python has "names", not "variables".</p>
<pre><code>val = None
# ...
if val is None:
val = any_object
</code></pre>
| 37
|
2009-03-19T22:47:39Z
|
[
"python",
"variable-assignment",
"variable-declaration"
] |
Is it possible only to declare a variable without assigning any value in Python?
| 664,294
|
<p>Is it possible to declare a variable in Python, like so?:</p>
<pre><code>var
</code></pre>
<p>so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?</p>
<p>EDIT: I want to do this for cases like this:</p>
<pre><code>value
for index in sequence:
if value == None and conditionMet:
value = index
break
</code></pre>
<h3>Duplicate</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/664219/uninitialized-value-in-python">Uninitialised value in python</a> (by same author)</li>
<li><a href="http://stackoverflow.com/questions/571514/are-there-any-declaration-keywords-in-python">Are there any declaration keywords in Python?</a> (by the same author)</li>
</ul>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls">Python: variable scope and function calls</a></li>
<li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables">Other languages have "variables"</a></li>
</ul>
| 113
|
2009-03-19T22:21:53Z
| 664,386
|
<p>First of all, my response to the question you've originally asked</p>
<p><strong>Q: How do I discover if a variable is defined at a point in my code?</strong></p>
<p><strong>A: Read up in the source file until you see a line where that variable is defined.</strong></p>
<p>But further, you've given a code example that there are various permutations of that are quite pythonic. You're after a way to scan a sequence for elements that match a condition, so here are some solutions:</p>
<pre><code>def findFirstMatch(sequence):
for value in sequence:
if matchCondition(value):
return value
raise LookupError("Could not find match in sequence")
</code></pre>
<p>Clearly in this example you could replace the <code>raise</code> with a <code>return None</code> depending on what you wanted to achieve.</p>
<p>If you wanted everything that matched the condition you could do this:</p>
<pre><code>def findAllMatches(sequence):
matches = []
for value in sequence:
if matchCondition(value):
matches.append(value)
return matches
</code></pre>
<p>There is another way of doing this with <code>yield</code> that I won't bother showing you, because it's quite complicated in the way that it works.</p>
<p>Further, there is a one line way of achieving this:</p>
<pre><code>all_matches = [value for value in sequence if matchCondition(value)]
</code></pre>
| 2
|
2009-03-19T22:59:51Z
|
[
"python",
"variable-assignment",
"variable-declaration"
] |
Is it possible only to declare a variable without assigning any value in Python?
| 664,294
|
<p>Is it possible to declare a variable in Python, like so?:</p>
<pre><code>var
</code></pre>
<p>so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?</p>
<p>EDIT: I want to do this for cases like this:</p>
<pre><code>value
for index in sequence:
if value == None and conditionMet:
value = index
break
</code></pre>
<h3>Duplicate</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/664219/uninitialized-value-in-python">Uninitialised value in python</a> (by same author)</li>
<li><a href="http://stackoverflow.com/questions/571514/are-there-any-declaration-keywords-in-python">Are there any declaration keywords in Python?</a> (by the same author)</li>
</ul>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls">Python: variable scope and function calls</a></li>
<li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables">Other languages have "variables"</a></li>
</ul>
| 113
|
2009-03-19T22:21:53Z
| 664,391
|
<p>You look like you're trying to write C in Python. If you want to find something in a sequence, Python has builtin functions to do that, like</p>
<pre><code>value = sequence.index(blarg)
</code></pre>
| 1
|
2009-03-19T23:03:49Z
|
[
"python",
"variable-assignment",
"variable-declaration"
] |
Is it possible only to declare a variable without assigning any value in Python?
| 664,294
|
<p>Is it possible to declare a variable in Python, like so?:</p>
<pre><code>var
</code></pre>
<p>so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?</p>
<p>EDIT: I want to do this for cases like this:</p>
<pre><code>value
for index in sequence:
if value == None and conditionMet:
value = index
break
</code></pre>
<h3>Duplicate</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/664219/uninitialized-value-in-python">Uninitialised value in python</a> (by same author)</li>
<li><a href="http://stackoverflow.com/questions/571514/are-there-any-declaration-keywords-in-python">Are there any declaration keywords in Python?</a> (by the same author)</li>
</ul>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls">Python: variable scope and function calls</a></li>
<li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables">Other languages have "variables"</a></li>
</ul>
| 113
|
2009-03-19T22:21:53Z
| 664,396
|
<p>If I'm understanding your example right, you don't need to refer to 'value' in the if statement anyway. You're breaking out of the loop as soon as it could be set to anything.</p>
<pre><code>value = None
for index in sequence:
doSomethingHere
if conditionMet:
value = index
break
</code></pre>
| 2
|
2009-03-19T23:04:45Z
|
[
"python",
"variable-assignment",
"variable-declaration"
] |
Is it possible only to declare a variable without assigning any value in Python?
| 664,294
|
<p>Is it possible to declare a variable in Python, like so?:</p>
<pre><code>var
</code></pre>
<p>so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?</p>
<p>EDIT: I want to do this for cases like this:</p>
<pre><code>value
for index in sequence:
if value == None and conditionMet:
value = index
break
</code></pre>
<h3>Duplicate</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/664219/uninitialized-value-in-python">Uninitialised value in python</a> (by same author)</li>
<li><a href="http://stackoverflow.com/questions/571514/are-there-any-declaration-keywords-in-python">Are there any declaration keywords in Python?</a> (by the same author)</li>
</ul>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls">Python: variable scope and function calls</a></li>
<li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables">Other languages have "variables"</a></li>
</ul>
| 113
|
2009-03-19T22:21:53Z
| 1,661,181
|
<p>Well, if you want to check if a variable is defined or not then why not check if its in the locals() or globals() arrays? Your code rewritten:</p>
<pre><code>for index in sequence:
if 'value' not in globals() and conditionMet:
value = index
break
</code></pre>
<p>If it's a local variable you are looking for then replace globals() with locals(). </p>
| 3
|
2009-11-02T13:00:57Z
|
[
"python",
"variable-assignment",
"variable-declaration"
] |
Is it possible only to declare a variable without assigning any value in Python?
| 664,294
|
<p>Is it possible to declare a variable in Python, like so?:</p>
<pre><code>var
</code></pre>
<p>so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?</p>
<p>EDIT: I want to do this for cases like this:</p>
<pre><code>value
for index in sequence:
if value == None and conditionMet:
value = index
break
</code></pre>
<h3>Duplicate</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/664219/uninitialized-value-in-python">Uninitialised value in python</a> (by same author)</li>
<li><a href="http://stackoverflow.com/questions/571514/are-there-any-declaration-keywords-in-python">Are there any declaration keywords in Python?</a> (by the same author)</li>
</ul>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls">Python: variable scope and function calls</a></li>
<li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables">Other languages have "variables"</a></li>
</ul>
| 113
|
2009-03-19T22:21:53Z
| 25,803,365
|
<pre><code>var_str = str()
var_int = int()
</code></pre>
| 0
|
2014-09-12T07:51:37Z
|
[
"python",
"variable-assignment",
"variable-declaration"
] |
Is it possible only to declare a variable without assigning any value in Python?
| 664,294
|
<p>Is it possible to declare a variable in Python, like so?:</p>
<pre><code>var
</code></pre>
<p>so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?</p>
<p>EDIT: I want to do this for cases like this:</p>
<pre><code>value
for index in sequence:
if value == None and conditionMet:
value = index
break
</code></pre>
<h3>Duplicate</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/664219/uninitialized-value-in-python">Uninitialised value in python</a> (by same author)</li>
<li><a href="http://stackoverflow.com/questions/571514/are-there-any-declaration-keywords-in-python">Are there any declaration keywords in Python?</a> (by the same author)</li>
</ul>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls">Python: variable scope and function calls</a></li>
<li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables">Other languages have "variables"</a></li>
</ul>
| 113
|
2009-03-19T22:21:53Z
| 39,994,840
|
<p>If <code>None</code> is a valid data value then you can use <code>var = object()</code> as a sentinel like <a href="http://python-notes.curiousefficiency.org/en/latest/python_concepts/break_else.html" rel="nofollow">Nick Coghlan suggests</a>.</p>
| 0
|
2016-10-12T09:13:59Z
|
[
"python",
"variable-assignment",
"variable-declaration"
] |
Using norwegian letters æøå in python
| 664,372
|
<p>Hello
I'm learning python and PyGTK now, and have created a simple Music Organizer.
<a href="http://pastebin.com/m2b596852" rel="nofollow">http://pastebin.com/m2b596852</a>
But when it edits songs with the Norwegian letters æ, ø, and å it's just changing them to a weird character.</p>
<p>So is there any good way of opening or encode the names into utf-8 characters?</p>
<h3>Two relevant places from the above code:</h3>
<p>Read info from a file:</p>
<pre><code>def __parse(self, filename):
"parse ID3v1.0 tags from MP3 file"
self.clear()
self['artist'] = 'Unknown'
self['title'] = 'Unknown'
try:
fsock = open(filename, "rb", 0)
try:
fsock.seek(-128, 2)
tagdata = fsock.read(128)
finally:
fsock.close()
if tagdata[:3] == 'TAG':
for tag, (start, end, parseFunc) in self.tagDataMap.items():
self[tag] = parseFunc(tagdata[start:end])
except IOError:
pass
</code></pre>
<p>Print to sys.stdout info:</p>
<pre><code>for info in files:
try:
os.rename(info['name'],
os.path.join(self.dir, info['artist'])+' - '+info['title']+'.mp3')
print 'From: '+ info['name'].replace(os.path.join(self.dir, ''), '')
print 'To: '+ info['artist'] +' - '+info['title']+'.mp3'
print
self.progressbar.set_fraction(i/num)
self.progressbar.set_text('File %d of %d' % (i, num))
i += 1
except IOError:
print 'Rename fail'
</code></pre>
| 2
|
2009-03-19T22:54:03Z
| 664,404
|
<p>You'd need to convert the bytestrings you read from the file into Unicode character strings. Looking at your code, I would do this in the parsing function, i.e. replace <code>stripnulls</code> with something like this</p>
<pre><code>def stripnulls_and_decode(data):
return codecs.utf_8_decode(data.replace("\00", "")).strip()
</code></pre>
<p>Note that this will only work if the strings in the file are in fact encoded in UTF-8 - if they're in a different encoding, you'd have to use the corresponding decoding function from the <code>codecs</code> module.</p>
| 1
|
2009-03-19T23:06:49Z
|
[
"python",
"utf-8"
] |
Using norwegian letters æøå in python
| 664,372
|
<p>Hello
I'm learning python and PyGTK now, and have created a simple Music Organizer.
<a href="http://pastebin.com/m2b596852" rel="nofollow">http://pastebin.com/m2b596852</a>
But when it edits songs with the Norwegian letters æ, ø, and å it's just changing them to a weird character.</p>
<p>So is there any good way of opening or encode the names into utf-8 characters?</p>
<h3>Two relevant places from the above code:</h3>
<p>Read info from a file:</p>
<pre><code>def __parse(self, filename):
"parse ID3v1.0 tags from MP3 file"
self.clear()
self['artist'] = 'Unknown'
self['title'] = 'Unknown'
try:
fsock = open(filename, "rb", 0)
try:
fsock.seek(-128, 2)
tagdata = fsock.read(128)
finally:
fsock.close()
if tagdata[:3] == 'TAG':
for tag, (start, end, parseFunc) in self.tagDataMap.items():
self[tag] = parseFunc(tagdata[start:end])
except IOError:
pass
</code></pre>
<p>Print to sys.stdout info:</p>
<pre><code>for info in files:
try:
os.rename(info['name'],
os.path.join(self.dir, info['artist'])+' - '+info['title']+'.mp3')
print 'From: '+ info['name'].replace(os.path.join(self.dir, ''), '')
print 'To: '+ info['artist'] +' - '+info['title']+'.mp3'
print
self.progressbar.set_fraction(i/num)
self.progressbar.set_text('File %d of %d' % (i, num))
i += 1
except IOError:
print 'Rename fail'
</code></pre>
| 2
|
2009-03-19T22:54:03Z
| 664,456
|
<p>I don't know what encodings are used for mp3 tags but if you are sure that it is UTF-8 then:</p>
<pre><code> tagdata[start:end].decode("utf-8")
</code></pre>
<p>The line <code># -*- coding: utf-8 -*-</code> defines your source code encoding and doesn't define encoding used to read from or write to files.</p>
| 1
|
2009-03-19T23:33:04Z
|
[
"python",
"utf-8"
] |
Using norwegian letters æøå in python
| 664,372
|
<p>Hello
I'm learning python and PyGTK now, and have created a simple Music Organizer.
<a href="http://pastebin.com/m2b596852" rel="nofollow">http://pastebin.com/m2b596852</a>
But when it edits songs with the Norwegian letters æ, ø, and å it's just changing them to a weird character.</p>
<p>So is there any good way of opening or encode the names into utf-8 characters?</p>
<h3>Two relevant places from the above code:</h3>
<p>Read info from a file:</p>
<pre><code>def __parse(self, filename):
"parse ID3v1.0 tags from MP3 file"
self.clear()
self['artist'] = 'Unknown'
self['title'] = 'Unknown'
try:
fsock = open(filename, "rb", 0)
try:
fsock.seek(-128, 2)
tagdata = fsock.read(128)
finally:
fsock.close()
if tagdata[:3] == 'TAG':
for tag, (start, end, parseFunc) in self.tagDataMap.items():
self[tag] = parseFunc(tagdata[start:end])
except IOError:
pass
</code></pre>
<p>Print to sys.stdout info:</p>
<pre><code>for info in files:
try:
os.rename(info['name'],
os.path.join(self.dir, info['artist'])+' - '+info['title']+'.mp3')
print 'From: '+ info['name'].replace(os.path.join(self.dir, ''), '')
print 'To: '+ info['artist'] +' - '+info['title']+'.mp3'
print
self.progressbar.set_fraction(i/num)
self.progressbar.set_text('File %d of %d' % (i, num))
i += 1
except IOError:
print 'Rename fail'
</code></pre>
| 2
|
2009-03-19T22:54:03Z
| 664,499
|
<p>You want to start by decoding the input FROM the charset it is in TO utf-8 (in Python, encode means "take it from unicode/utf-8 to some other charset"). </p>
<p>Some googling suggests the Norwegian charset is plain-ole 'iso-8859-1'... I hope someone can correct me if I'm wrong on this detail. Regardless, whatever the name of the charset in the following example:</p>
<pre><code>tagdata[start:end].decode('iso-8859-1')
</code></pre>
<p>In a real-world app, I realize you can't guarantee that the input is norwegian, or any other charset. In this case, you will probably want to proceed through a series of likely charsets to see which you can convert successfully. Both SO and Google have some suggestions on algorithms for doing this effectively in Python. It sounds scarier than it really is.</p>
| 4
|
2009-03-19T23:57:53Z
|
[
"python",
"utf-8"
] |
How to recover a broken python "cPickle" dump?
| 664,444
|
<p>I am using <code>rss2email</code> for converting a number of RSS feeds into mail for easier consumption. That is, I <em>was</em> using it because it broke in a horrible way today: On every run, it only gives me this backtrace:</p>
<pre><code>Traceback (most recent call last):
File "/usr/share/rss2email/rss2email.py", line 740, in <module>
elif action == "list": list()
File "/usr/share/rss2email/rss2email.py", line 681, in list
feeds, feedfileObject = load(lock=0)
File "/usr/share/rss2email/rss2email.py", line 422, in load
feeds = pickle.load(feedfileObject)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p>The only helpful fact that I have been able to construct from this backtrace is that the file <code>~/.rss2email/feeds.dat</code> in which <code>rss2email</code> keeps all its configuration and runtime state is somehow broken. Apparently, <code>rss2email</code> reads its state and dumps it back using <code>cPickle</code> on every run.</p>
<p>I have even found the line containing that <code>'sxOYAAuyzSx0WqN3BVPjE+6pgPU'</code>string mentioned above in the giant (>12MB) <code>feeds.dat</code> file. To my untrained eye, the dump does not appear to be truncated or otherwise damaged.</p>
<p>What approaches could I try in order to reconstruct the file?</p>
<p>The Python version is 2.5.4 on a Debian/unstable system.</p>
<p><strong>EDIT</strong></p>
<p>Peter Gibson and J.F. Sebastian have suggested directly loading from the
pickle file and I had tried that before. Apparently, a <code>Feed</code> class
that is defined in <code>rss2email.py</code> is needed, so here's my script:</p>
<pre><code>#!/usr/bin/python
import sys
# import pickle
import cPickle as pickle
sys.path.insert(0,"/usr/share/rss2email")
from rss2email import Feed
feedfile = open("feeds.dat", 'rb')
feeds = pickle.load(feedfile)
</code></pre>
<p>The "plain" pickle variant produces the following traceback:</p>
<pre><code>Traceback (most recent call last):
File "./r2e-rescue.py", line 8, in <module>
feeds = pickle.load(feedfile)
File "/usr/lib/python2.5/pickle.py", line 1370, in load
return Unpickler(file).load()
File "/usr/lib/python2.5/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.5/pickle.py", line 1133, in load_reduce
value = func(*args)
TypeError: 'str' object is not callable
</code></pre>
<p>The <code>cPickle</code> variant produces essentially the same thing as calling
<code>r2e</code> itself:</p>
<pre><code>Traceback (most recent call last):
File "./r2e-rescue.py", line 10, in <module>
feeds = pickle.load(feedfile)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p><strong>EDIT 2</strong></p>
<p>Following J.F. Sebastian's suggestion around putting "printf
debugging" into <code>Feed.__setstate__</code> into my test script, these are the
last few lines before Python bails out.</p>
<pre><code> u'http:/com/news.ars/post/20080924-everyone-declares-victory-in-smutfree-wireless-broadband-test.html': u'http:/com/news.ars/post/20080924-everyone-declares-victory-in-smutfree-wireless-broadband-test.html'},
'to': None,
'url': 'http://arstechnica.com/'}
Traceback (most recent call last):
File "./r2e-rescue.py", line 23, in ?
feeds = pickle.load(feedfile)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p>The same thing happens on a Debian/etch box using python 2.4.4-2.</p>
| 2
|
2009-03-19T23:25:03Z
| 664,577
|
<p>Have you tried manually loading the feeds.dat file using both cPickle and pickle? If the output differs it might hint at the error.</p>
<p>Something like (from your home directory):</p>
<pre><code>import cPickle, pickle
f = open('.rss2email/feeds.dat', 'r')
obj1 = cPickle.load(f)
obj2 = pickle.load(f)
</code></pre>
<p>(you might need to open in binary mode 'rb' if rss2email doesn't pickle in ascii).</p>
<p>Pete</p>
<p>Edit: The fact that cPickle and pickle give the same error suggests that the feeds.dat file is the problem. Probably a change in the Feed class between versions of rss2email as suggested in the Ubuntu bug J.F. Sebastian links to.</p>
| 3
|
2009-03-20T00:40:19Z
|
[
"python",
"rss",
"pickle"
] |
How to recover a broken python "cPickle" dump?
| 664,444
|
<p>I am using <code>rss2email</code> for converting a number of RSS feeds into mail for easier consumption. That is, I <em>was</em> using it because it broke in a horrible way today: On every run, it only gives me this backtrace:</p>
<pre><code>Traceback (most recent call last):
File "/usr/share/rss2email/rss2email.py", line 740, in <module>
elif action == "list": list()
File "/usr/share/rss2email/rss2email.py", line 681, in list
feeds, feedfileObject = load(lock=0)
File "/usr/share/rss2email/rss2email.py", line 422, in load
feeds = pickle.load(feedfileObject)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p>The only helpful fact that I have been able to construct from this backtrace is that the file <code>~/.rss2email/feeds.dat</code> in which <code>rss2email</code> keeps all its configuration and runtime state is somehow broken. Apparently, <code>rss2email</code> reads its state and dumps it back using <code>cPickle</code> on every run.</p>
<p>I have even found the line containing that <code>'sxOYAAuyzSx0WqN3BVPjE+6pgPU'</code>string mentioned above in the giant (>12MB) <code>feeds.dat</code> file. To my untrained eye, the dump does not appear to be truncated or otherwise damaged.</p>
<p>What approaches could I try in order to reconstruct the file?</p>
<p>The Python version is 2.5.4 on a Debian/unstable system.</p>
<p><strong>EDIT</strong></p>
<p>Peter Gibson and J.F. Sebastian have suggested directly loading from the
pickle file and I had tried that before. Apparently, a <code>Feed</code> class
that is defined in <code>rss2email.py</code> is needed, so here's my script:</p>
<pre><code>#!/usr/bin/python
import sys
# import pickle
import cPickle as pickle
sys.path.insert(0,"/usr/share/rss2email")
from rss2email import Feed
feedfile = open("feeds.dat", 'rb')
feeds = pickle.load(feedfile)
</code></pre>
<p>The "plain" pickle variant produces the following traceback:</p>
<pre><code>Traceback (most recent call last):
File "./r2e-rescue.py", line 8, in <module>
feeds = pickle.load(feedfile)
File "/usr/lib/python2.5/pickle.py", line 1370, in load
return Unpickler(file).load()
File "/usr/lib/python2.5/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.5/pickle.py", line 1133, in load_reduce
value = func(*args)
TypeError: 'str' object is not callable
</code></pre>
<p>The <code>cPickle</code> variant produces essentially the same thing as calling
<code>r2e</code> itself:</p>
<pre><code>Traceback (most recent call last):
File "./r2e-rescue.py", line 10, in <module>
feeds = pickle.load(feedfile)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p><strong>EDIT 2</strong></p>
<p>Following J.F. Sebastian's suggestion around putting "printf
debugging" into <code>Feed.__setstate__</code> into my test script, these are the
last few lines before Python bails out.</p>
<pre><code> u'http:/com/news.ars/post/20080924-everyone-declares-victory-in-smutfree-wireless-broadband-test.html': u'http:/com/news.ars/post/20080924-everyone-declares-victory-in-smutfree-wireless-broadband-test.html'},
'to': None,
'url': 'http://arstechnica.com/'}
Traceback (most recent call last):
File "./r2e-rescue.py", line 23, in ?
feeds = pickle.load(feedfile)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p>The same thing happens on a Debian/etch box using python 2.4.4-2.</p>
| 2
|
2009-03-19T23:25:03Z
| 664,591
|
<p>Sounds like the internals of cPickle are getting tangled up. This thread (<a href="http://bytes.com/groups/python/565085-cpickle-problems" rel="nofollow">http://bytes.com/groups/python/565085-cpickle-problems</a>) looks like it might have a clue..</p>
| 2
|
2009-03-20T00:46:26Z
|
[
"python",
"rss",
"pickle"
] |
How to recover a broken python "cPickle" dump?
| 664,444
|
<p>I am using <code>rss2email</code> for converting a number of RSS feeds into mail for easier consumption. That is, I <em>was</em> using it because it broke in a horrible way today: On every run, it only gives me this backtrace:</p>
<pre><code>Traceback (most recent call last):
File "/usr/share/rss2email/rss2email.py", line 740, in <module>
elif action == "list": list()
File "/usr/share/rss2email/rss2email.py", line 681, in list
feeds, feedfileObject = load(lock=0)
File "/usr/share/rss2email/rss2email.py", line 422, in load
feeds = pickle.load(feedfileObject)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p>The only helpful fact that I have been able to construct from this backtrace is that the file <code>~/.rss2email/feeds.dat</code> in which <code>rss2email</code> keeps all its configuration and runtime state is somehow broken. Apparently, <code>rss2email</code> reads its state and dumps it back using <code>cPickle</code> on every run.</p>
<p>I have even found the line containing that <code>'sxOYAAuyzSx0WqN3BVPjE+6pgPU'</code>string mentioned above in the giant (>12MB) <code>feeds.dat</code> file. To my untrained eye, the dump does not appear to be truncated or otherwise damaged.</p>
<p>What approaches could I try in order to reconstruct the file?</p>
<p>The Python version is 2.5.4 on a Debian/unstable system.</p>
<p><strong>EDIT</strong></p>
<p>Peter Gibson and J.F. Sebastian have suggested directly loading from the
pickle file and I had tried that before. Apparently, a <code>Feed</code> class
that is defined in <code>rss2email.py</code> is needed, so here's my script:</p>
<pre><code>#!/usr/bin/python
import sys
# import pickle
import cPickle as pickle
sys.path.insert(0,"/usr/share/rss2email")
from rss2email import Feed
feedfile = open("feeds.dat", 'rb')
feeds = pickle.load(feedfile)
</code></pre>
<p>The "plain" pickle variant produces the following traceback:</p>
<pre><code>Traceback (most recent call last):
File "./r2e-rescue.py", line 8, in <module>
feeds = pickle.load(feedfile)
File "/usr/lib/python2.5/pickle.py", line 1370, in load
return Unpickler(file).load()
File "/usr/lib/python2.5/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.5/pickle.py", line 1133, in load_reduce
value = func(*args)
TypeError: 'str' object is not callable
</code></pre>
<p>The <code>cPickle</code> variant produces essentially the same thing as calling
<code>r2e</code> itself:</p>
<pre><code>Traceback (most recent call last):
File "./r2e-rescue.py", line 10, in <module>
feeds = pickle.load(feedfile)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p><strong>EDIT 2</strong></p>
<p>Following J.F. Sebastian's suggestion around putting "printf
debugging" into <code>Feed.__setstate__</code> into my test script, these are the
last few lines before Python bails out.</p>
<pre><code> u'http:/com/news.ars/post/20080924-everyone-declares-victory-in-smutfree-wireless-broadband-test.html': u'http:/com/news.ars/post/20080924-everyone-declares-victory-in-smutfree-wireless-broadband-test.html'},
'to': None,
'url': 'http://arstechnica.com/'}
Traceback (most recent call last):
File "./r2e-rescue.py", line 23, in ?
feeds = pickle.load(feedfile)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p>The same thing happens on a Debian/etch box using python 2.4.4-2.</p>
| 2
|
2009-03-19T23:25:03Z
| 664,624
|
<ol>
<li><code>'sxOYAAuyzSx0WqN3BVPjE+6pgPU'</code> is most probably unrelated to the pickle's problem</li>
<li><p>Post an error traceback for (to determine what class defines the attribute that can't be called (the one that leads to the TypeError):</p>
<pre><code>python -c "import pickle; pickle.load(open('feeds.dat'))"
</code></pre></li>
</ol>
<p><strong>EDIT:</strong></p>
<p>Add the following to your code and run (redirect stderr to file then use <code>'tail -2'</code> on it to print last 2 lines): </p>
<pre><code>from pprint import pprint
def setstate(self, dict_):
pprint(dict_, stream=sys.stderr, depth=None)
self.__dict__.update(dict_)
Feed.__setstate__ = setstate
</code></pre>
<p>If the above doesn't yield an interesting output then use general troubleshooting tactics:</p>
<p>Confirm that <code>'feeds.dat'</code> is the problem:</p>
<ul>
<li>backup <code>~/.rss2email</code> directory</li>
<li>install rss2email into virtualenv/pip sandbox (or use zc.buildout) to isolate the environment (make sure you are using feedparser.py from the trunk). </li>
<li>add couple of feeds, add feeds until <code>'feeds.dat'</code> size is greater than the current. Run some tests.</li>
<li>try old 'feeds.dat'</li>
<li>try new 'feeds.dat' on existing rss2email installation </li>
</ul>
<p>See <a href="https://bugs.launchpad.net/ubuntu/%2Bsource/rss2email/%2Bbug/244953" rel="nofollow">r2e bails out with TypeError</a> bug on Ubuntu.</p>
| 2
|
2009-03-20T01:01:15Z
|
[
"python",
"rss",
"pickle"
] |
How to recover a broken python "cPickle" dump?
| 664,444
|
<p>I am using <code>rss2email</code> for converting a number of RSS feeds into mail for easier consumption. That is, I <em>was</em> using it because it broke in a horrible way today: On every run, it only gives me this backtrace:</p>
<pre><code>Traceback (most recent call last):
File "/usr/share/rss2email/rss2email.py", line 740, in <module>
elif action == "list": list()
File "/usr/share/rss2email/rss2email.py", line 681, in list
feeds, feedfileObject = load(lock=0)
File "/usr/share/rss2email/rss2email.py", line 422, in load
feeds = pickle.load(feedfileObject)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p>The only helpful fact that I have been able to construct from this backtrace is that the file <code>~/.rss2email/feeds.dat</code> in which <code>rss2email</code> keeps all its configuration and runtime state is somehow broken. Apparently, <code>rss2email</code> reads its state and dumps it back using <code>cPickle</code> on every run.</p>
<p>I have even found the line containing that <code>'sxOYAAuyzSx0WqN3BVPjE+6pgPU'</code>string mentioned above in the giant (>12MB) <code>feeds.dat</code> file. To my untrained eye, the dump does not appear to be truncated or otherwise damaged.</p>
<p>What approaches could I try in order to reconstruct the file?</p>
<p>The Python version is 2.5.4 on a Debian/unstable system.</p>
<p><strong>EDIT</strong></p>
<p>Peter Gibson and J.F. Sebastian have suggested directly loading from the
pickle file and I had tried that before. Apparently, a <code>Feed</code> class
that is defined in <code>rss2email.py</code> is needed, so here's my script:</p>
<pre><code>#!/usr/bin/python
import sys
# import pickle
import cPickle as pickle
sys.path.insert(0,"/usr/share/rss2email")
from rss2email import Feed
feedfile = open("feeds.dat", 'rb')
feeds = pickle.load(feedfile)
</code></pre>
<p>The "plain" pickle variant produces the following traceback:</p>
<pre><code>Traceback (most recent call last):
File "./r2e-rescue.py", line 8, in <module>
feeds = pickle.load(feedfile)
File "/usr/lib/python2.5/pickle.py", line 1370, in load
return Unpickler(file).load()
File "/usr/lib/python2.5/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.5/pickle.py", line 1133, in load_reduce
value = func(*args)
TypeError: 'str' object is not callable
</code></pre>
<p>The <code>cPickle</code> variant produces essentially the same thing as calling
<code>r2e</code> itself:</p>
<pre><code>Traceback (most recent call last):
File "./r2e-rescue.py", line 10, in <module>
feeds = pickle.load(feedfile)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p><strong>EDIT 2</strong></p>
<p>Following J.F. Sebastian's suggestion around putting "printf
debugging" into <code>Feed.__setstate__</code> into my test script, these are the
last few lines before Python bails out.</p>
<pre><code> u'http:/com/news.ars/post/20080924-everyone-declares-victory-in-smutfree-wireless-broadband-test.html': u'http:/com/news.ars/post/20080924-everyone-declares-victory-in-smutfree-wireless-broadband-test.html'},
'to': None,
'url': 'http://arstechnica.com/'}
Traceback (most recent call last):
File "./r2e-rescue.py", line 23, in ?
feeds = pickle.load(feedfile)
TypeError: ("'str' object is not callable", 'sxOYAAuyzSx0WqN3BVPjE+6pgPU', ((2009, 3, 19, 1, 19, 31, 3, 78, 0), {}))
</code></pre>
<p>The same thing happens on a Debian/etch box using python 2.4.4-2.</p>
| 2
|
2009-03-19T23:25:03Z
| 719,464
|
<h1>How I solved my problem</h1>
<h2>A Perl port of <code>pickle.py</code></h2>
<p>Following J.F. Sebastian's comment about how simple the the <code>pickle</code>
format is, I went out to port parts of <code>pickle.py</code> to Perl. A couple
of quick regular expressions would have been a faster way to access my
data, but I felt that the hack value and an opportunity to learn more
about Python would be be worth it. Plus, I still feel much more
comfortable using (and debugging code in) Perl than Python.</p>
<p>Most of the porting effort (simple types, tuples, lists, dictionaries)
went very straightforward. Perl's and Python's different notions of
classes and objects has been the only issue so far where a bit more
than simple translation of idioms was needed. The result is a module
called <code>Pickle::Parse</code> which after a bit of polishing will be
published on CPAN.</p>
<p>A module called <code>Python::Serialise::Pickle</code> existed on CPAN, but I
found its parsing capabilities lacking: It spews debugging output all
over the place and doesn't seem to support classes/objects.</p>
<h2>Parsing, transforming data, detecting actual errors in the stream</h2>
<p>Based upon <code>Pickle::Parse</code>, I tried to parse the <code>feeds.dat</code> file.
After a few iteration of fixing trivial bugs in my parsing code, I got
an error message that was strikingly similar to <code>pickle.py</code>'s original
<em>object not callable</em> error message:</p>
<pre><code>Can't use string ("sxOYAAuyzSx0WqN3BVPjE+6pgPU") as a subroutine
ref while "strict refs" in use at lib/Pickle/Parse.pm line 489,
<STDIN> line 187102.
</code></pre>
<p>Ha! Now we're at a point where it's quite likely that the actual data
stream is broken. Plus, we get an idea <em>where</em> it is broken.</p>
<p>It turned out that the first line of the following sequence was wrong:</p>
<pre><code>g7724
((I2009
I3
I19
I1
I19
I31
I3
I78
I0
t(dtRp62457
</code></pre>
<p>Position 7724 in the "memo" pointed to that string
<code>"sxOYAAuyzSx0WqN3BVPjE+6pgPU"</code>. From similar records earlier in the
stream, it was clear that a <code>time.struct_time</code> object was needed
instead. All later records shared this wrong pointer. With a simple
search/replace operation, it was trivial to fix this.</p>
<p>I find it ironic that I found the source of the error by accident
through Perl's feature that tells the user its position in the input
data stream when it dies.</p>
<h2>Conclusion</h2>
<ol>
<li>I will move away from <code>rss2email</code> as soon as I find time to
automatically transform its pickled configuration/state mess to
another tool's format.</li>
<li><code>pickle.py</code> needs more meaningful error messages that tell the user
about the position of the data stream (not the poision in its own
code) where things go wrong.</li>
<li>Porting parts <code>pickle.py</code> to Perl was fun and, in the end, rewarding.</li>
</ol>
| 5
|
2009-04-05T18:49:16Z
|
[
"python",
"rss",
"pickle"
] |
How to Make an Image Uniform Brightness (using Python/PIL)
| 664,760
|
<p>I want to take an image of a document that was photographed and make it look like it was scanned. Since a scanner will put a constant light source over the whole document, I want to achieve that effect on a photo of a document. The desired effect would be to remove any shadows or areas of low light (or at least make them less noticeable) and have the whole photo be fairly bright.</p>
<p>My first thought would be to locate the brightest part of the target image, and them make the whole image that brightness. Assuming that's even the right algorithm, how would I do it in PIL? Is there a get brightness method? etc?</p>
<p>(This is a follow-up to <a href="http://stackoverflow.com/questions/662638/how-to-alter-photographed-document-to-look-scanned">this earlier question</a>.)</p>
| 3
|
2009-03-20T02:05:35Z
| 664,804
|
<p>As a first attempt, try thresholding the image. Dark areas become black, light areas become white. I haven't used PIL, but I imagine there's any easy way to do it.</p>
| 2
|
2009-03-20T02:33:23Z
|
[
"python",
"image",
"image-processing",
"python-imaging-library",
"brightness"
] |
How to Make an Image Uniform Brightness (using Python/PIL)
| 664,760
|
<p>I want to take an image of a document that was photographed and make it look like it was scanned. Since a scanner will put a constant light source over the whole document, I want to achieve that effect on a photo of a document. The desired effect would be to remove any shadows or areas of low light (or at least make them less noticeable) and have the whole photo be fairly bright.</p>
<p>My first thought would be to locate the brightest part of the target image, and them make the whole image that brightness. Assuming that's even the right algorithm, how would I do it in PIL? Is there a get brightness method? etc?</p>
<p>(This is a follow-up to <a href="http://stackoverflow.com/questions/662638/how-to-alter-photographed-document-to-look-scanned">this earlier question</a>.)</p>
| 3
|
2009-03-20T02:05:35Z
| 664,834
|
<p>Try ImageChops.screen(image1, image2) with 2 copies of the image. If that's not satisfactory, try some of the other functions in the ImageChops module.</p>
<p>Also, you may want to convert it to grayscale first: ImageOps.grayscale(image). </p>
| 2
|
2009-03-20T02:54:27Z
|
[
"python",
"image",
"image-processing",
"python-imaging-library",
"brightness"
] |
How to Make an Image Uniform Brightness (using Python/PIL)
| 664,760
|
<p>I want to take an image of a document that was photographed and make it look like it was scanned. Since a scanner will put a constant light source over the whole document, I want to achieve that effect on a photo of a document. The desired effect would be to remove any shadows or areas of low light (or at least make them less noticeable) and have the whole photo be fairly bright.</p>
<p>My first thought would be to locate the brightest part of the target image, and them make the whole image that brightness. Assuming that's even the right algorithm, how would I do it in PIL? Is there a get brightness method? etc?</p>
<p>(This is a follow-up to <a href="http://stackoverflow.com/questions/662638/how-to-alter-photographed-document-to-look-scanned">this earlier question</a>.)</p>
| 3
|
2009-03-20T02:05:35Z
| 676,764
|
<p>First try it manually in a image editing program, like GIMP. I think what you're looking for is adjusting brightness and contrast.</p>
| 0
|
2009-03-24T10:12:01Z
|
[
"python",
"image",
"image-processing",
"python-imaging-library",
"brightness"
] |
How to Make an Image Uniform Brightness (using Python/PIL)
| 664,760
|
<p>I want to take an image of a document that was photographed and make it look like it was scanned. Since a scanner will put a constant light source over the whole document, I want to achieve that effect on a photo of a document. The desired effect would be to remove any shadows or areas of low light (or at least make them less noticeable) and have the whole photo be fairly bright.</p>
<p>My first thought would be to locate the brightest part of the target image, and them make the whole image that brightness. Assuming that's even the right algorithm, how would I do it in PIL? Is there a get brightness method? etc?</p>
<p>(This is a follow-up to <a href="http://stackoverflow.com/questions/662638/how-to-alter-photographed-document-to-look-scanned">this earlier question</a>.)</p>
| 3
|
2009-03-20T02:05:35Z
| 850,972
|
<p>What type of image? If it's supposed to be ideally pure black and white, as with text pages, then your raw data probably is something like a grayscale gradient with varying levels of not-quite-black letters. Thresholding against a constant may give good results, but not if the illumination is too uneven or lens glare interferes. Threshold the image against a smoothed version of itself. Smooth it using PIL_usm.gblur(image, radius) where radius (in pixels) is something like ten, twenty or some value comparable to the width of elements of the letters. Quick hackcode from old notes just for illustration:</p>
<pre><code>import Image
import PIL_usm
# see http://www.cazabon.com/pyCMS/PIL_usm.html for PIL_usm
img = Image.open(...)
sm = PIL_usm(img, 10)
thr = Image.ImageChops.subtract(img,sm, .001, 128)
# or whatever works 4u...
</code></pre>
<p>OTOH, if these documents have photographs or other non-bilevel graphics, you'll need to be more clever. </p>
| 0
|
2009-05-12T02:55:33Z
|
[
"python",
"image",
"image-processing",
"python-imaging-library",
"brightness"
] |
Hierarchy traversal and comparison modules for Python?
| 664,898
|
<p>I deal with a lot of hierarchies in my day to day development. File systems, nested DAG nodes in Autodesk Maya, etc.</p>
<p>I'm wondering, are there any good modules for Python specifically designed to traverse and compare hierarchies of objects?</p>
<p>Of particular interest would be ways to do 'fuzzy' comparisons between two <em>nearly</em> identical hierarchies. Some of the reasons for doing this would be for matching two node hierarchies in Maya from two different characters in order to transfer animation from one to the other.</p>
<p>Based on what I've been reading, I'd probably need something with a name threshold (which I could build myself) for comparing how close two node names are to each other. I'd then need a way to optionally ignore the order that child nodes appear in the hierarchy. Lastly, I'd need to deal with a depth threshold, in cases where a node may have been slightly moved up or down the hierarchy.</p>
| 5
|
2009-03-20T03:37:34Z
| 664,925
|
<p><a href="http://code.google.com/p/pytree/" rel="nofollow">http://code.google.com/p/pytree/</a></p>
<p>these maybe overkill or not suited at all for what you need:</p>
<p><a href="http://networkx.lanl.gov/" rel="nofollow">http://networkx.lanl.gov/</a></p>
<p><a href="http://www.osl.iu.edu/~dgregor/bgl-python/" rel="nofollow">http://www.osl.iu.edu/~dgregor/bgl-python/</a></p>
| 1
|
2009-03-20T03:53:27Z
|
[
"python",
"tree",
"module",
"hierarchy",
"traversal"
] |
Hierarchy traversal and comparison modules for Python?
| 664,898
|
<p>I deal with a lot of hierarchies in my day to day development. File systems, nested DAG nodes in Autodesk Maya, etc.</p>
<p>I'm wondering, are there any good modules for Python specifically designed to traverse and compare hierarchies of objects?</p>
<p>Of particular interest would be ways to do 'fuzzy' comparisons between two <em>nearly</em> identical hierarchies. Some of the reasons for doing this would be for matching two node hierarchies in Maya from two different characters in order to transfer animation from one to the other.</p>
<p>Based on what I've been reading, I'd probably need something with a name threshold (which I could build myself) for comparing how close two node names are to each other. I'd then need a way to optionally ignore the order that child nodes appear in the hierarchy. Lastly, I'd need to deal with a depth threshold, in cases where a node may have been slightly moved up or down the hierarchy.</p>
| 5
|
2009-03-20T03:37:34Z
| 665,548
|
<p>I'm not sure I see the need for a complete module -- hierarchies are a design pattern, and each hierarchy has enough unique features that it's hard to generalize.</p>
<pre><code>class Node( object ):
def __init__( self, myData, children=None )
self.myData= myData
self.children= children if children is not None else []
def visit( self, aVisitor ):
aVisitor.at( self )
aVisitor.down()
for c in self.children:
aVisitor.at( c )
aVisitor.up()
class Visitor( object ):
def __init__( self ):
self.depth= 0
def down( self ):
self.depth += 1
def up( self ):
self.depth -= 1
</code></pre>
<p>I find that this is all I need. And I've found that it's hard to make a reusable module out of this because (a) there's so little here and (b) each application adds or changes so much code.</p>
<p>Further, I find that the most commonly used hierarchy is the file system, for which I have the <code>os</code> module. The second most commonly used hierarchy is XML messages, for which I have ElementTree (usually via lxml). After those two, I use the above structures as templates for my classes, not as a literal reusable module.</p>
| 4
|
2009-03-20T10:00:05Z
|
[
"python",
"tree",
"module",
"hierarchy",
"traversal"
] |
Hierarchy traversal and comparison modules for Python?
| 664,898
|
<p>I deal with a lot of hierarchies in my day to day development. File systems, nested DAG nodes in Autodesk Maya, etc.</p>
<p>I'm wondering, are there any good modules for Python specifically designed to traverse and compare hierarchies of objects?</p>
<p>Of particular interest would be ways to do 'fuzzy' comparisons between two <em>nearly</em> identical hierarchies. Some of the reasons for doing this would be for matching two node hierarchies in Maya from two different characters in order to transfer animation from one to the other.</p>
<p>Based on what I've been reading, I'd probably need something with a name threshold (which I could build myself) for comparing how close two node names are to each other. I'd then need a way to optionally ignore the order that child nodes appear in the hierarchy. Lastly, I'd need to deal with a depth threshold, in cases where a node may have been slightly moved up or down the hierarchy.</p>
| 5
|
2009-03-20T03:37:34Z
| 670,492
|
<p>I recommend digging around xmldifff <a href="http://www.logilab.org/859" rel="nofollow">http://www.logilab.org/859</a> and seeing how they compare nodes and handle parallel trees. Or, try writing a [recursive] generator that yields each [significant] node in a tree, say <code>f(t)</code>, then use <code>itertools.izip(f(t1),f(t2))</code> to collect together pairs of nodes for comparison.</p>
<p>Most of the hierarchical structures I deal with have more than one "axis", like elements and attributes in XML, and some nodes are more significant than others.</p>
<p>For a more bizarre solution, serialize the two trees to text files, make a referential note that line #n comes from node #x in a tree. Do that to both trees, feed the files into diff, and scan the results to notice which parts of the tree have changed. You can map that line #n from file 1 (and therefore node #x in the first tree) and line #m from file 2 (and therefore node #y of the second tree) mean that some part of each tree is the same or different.</p>
<p>For any solution your are going to have to establish a "canonical form" of your tree, one that might drop all ignorable whitespace, display attributes, optional nodes, etc., from the comparison process. It might also mean doing a breadth first vs. depth first traversal of the tree(s).</p>
| 2
|
2009-03-22T03:06:05Z
|
[
"python",
"tree",
"module",
"hierarchy",
"traversal"
] |
How can I improve this "register" view in Django?
| 664,937
|
<p>I've got a Django-based site that allows users to register (but requires an admin to approve the account before they can view certain parts of the site). I'm basing it off of <code>django.contrib.auth</code>. I require users to register with an email address from a certain domain name, so I've overridden the <code>UserCreationForm</code>'s <code>save()</code> and <code>clean_email()</code> methods.</p>
<p>My registration page uses the following view. I'm interested in hearing about how I might improve this viewâcode improvements or process improvements (or anything else, really).</p>
<pre><code>def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
message = None
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = user.email
# If valid new user account
if (user is not None) and (user.is_active):
login(request, user)
message = "<strong>Congratulations!</strong> You have been registered."
# Send emails
try:
# Admin email
pk = None
try: pk = User.objects.filter(username=username)[0].pk
except: pass
admin_email_template = loader.get_template('accounts/email_notify_admin_of_registration.txt')
admin_email_context = Context({
'first_name': first_name,
'last_name': last_name,
'username': username,
'email': email,
'pk': pk,
})
admin_email_body = admin_email_template.render(admin_email_context)
mail_admins("New User Registration", admin_email_body)
# User email
user_email_template = loader.get_template('accounts/email_registration_success.txt')
user_email_context = Context({
'first_name': form.cleaned_data['first_name'],
'username': username,
'password': password,
})
user_email_body = user_email_template.render(user_email_context)
user.email_user("Successfully Registered at example.com", user_email_body)
except:
message = "There was an error sending you the confirmation email. You should still be able to login normally."
else:
message = "There was an error automatically logging you in. Try <a href=\"/login/\">logging in</a> manually."
# Display success page
return render_to_response('accounts/register_success.html', {
'username': username,
'message': message,
},
context_instance=RequestContext(request)
)
else: # If not POST
form = UserCreationForm()
return render_to_response('accounts/register.html', {
'form': form,
},
context_instance=RequestContext(request)
)
</code></pre>
| 3
|
2009-03-20T03:59:12Z
| 665,070
|
<p>First response: It looks a heck of a lot better than 95% of the "improve my code" questions.</p>
<p>Is there anything in particular you are dissatisfied with?</p>
| 0
|
2009-03-20T05:17:32Z
|
[
"python",
"django",
"user-registration"
] |
How can I improve this "register" view in Django?
| 664,937
|
<p>I've got a Django-based site that allows users to register (but requires an admin to approve the account before they can view certain parts of the site). I'm basing it off of <code>django.contrib.auth</code>. I require users to register with an email address from a certain domain name, so I've overridden the <code>UserCreationForm</code>'s <code>save()</code> and <code>clean_email()</code> methods.</p>
<p>My registration page uses the following view. I'm interested in hearing about how I might improve this viewâcode improvements or process improvements (or anything else, really).</p>
<pre><code>def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
message = None
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = user.email
# If valid new user account
if (user is not None) and (user.is_active):
login(request, user)
message = "<strong>Congratulations!</strong> You have been registered."
# Send emails
try:
# Admin email
pk = None
try: pk = User.objects.filter(username=username)[0].pk
except: pass
admin_email_template = loader.get_template('accounts/email_notify_admin_of_registration.txt')
admin_email_context = Context({
'first_name': first_name,
'last_name': last_name,
'username': username,
'email': email,
'pk': pk,
})
admin_email_body = admin_email_template.render(admin_email_context)
mail_admins("New User Registration", admin_email_body)
# User email
user_email_template = loader.get_template('accounts/email_registration_success.txt')
user_email_context = Context({
'first_name': form.cleaned_data['first_name'],
'username': username,
'password': password,
})
user_email_body = user_email_template.render(user_email_context)
user.email_user("Successfully Registered at example.com", user_email_body)
except:
message = "There was an error sending you the confirmation email. You should still be able to login normally."
else:
message = "There was an error automatically logging you in. Try <a href=\"/login/\">logging in</a> manually."
# Display success page
return render_to_response('accounts/register_success.html', {
'username': username,
'message': message,
},
context_instance=RequestContext(request)
)
else: # If not POST
form = UserCreationForm()
return render_to_response('accounts/register.html', {
'form': form,
},
context_instance=RequestContext(request)
)
</code></pre>
| 3
|
2009-03-20T03:59:12Z
| 665,153
|
<p>You don't even need this code, but I think the style:</p>
<pre><code>pk = None
try: pk = User.objects.filter(username=username)[0].pk
except: pass
</code></pre>
<p>is more naturally written like:</p>
<pre><code>try:
user = User.objects.get(username=username)
except User.DoesNotExist:
user = None
</code></pre>
<p>and then in your admin notify template use <code>{{ user.id }}</code> instead of <code>{{ pk }}</code>.</p>
<p>But, like I said, you don't need that code at all because you already have a user object from your call to <code>authenticate()</code>.</p>
<p>Generally in Python, it's considered poor practice to have the exception handler in a try/except block be empty. In other words, always capture a specific exception such as <code>User.DoesNotExist</code> for this case.</p>
<p>It's also poor practice to have many lines inside the <code>try</code> part of the try/except block. It is better form to code this way:</p>
<pre><code>try:
... a line of code that can generate exceptions to be handled ...
except SomeException:
... handle this particular exception ...
else:
... the rest of the code to execute if there were no exceptions ...
</code></pre>
<p>A final, minor, recommendation is to not send the email directly in your view because this won't scale if your site starts to see heavy registration requests. It is better add in the <a href="http://code.google.com/p/django-mailer/" rel="nofollow">django-mailer</a> app to offload the work into a queue handled by another process.</p>
| 4
|
2009-03-20T06:16:29Z
|
[
"python",
"django",
"user-registration"
] |
How can I improve this "register" view in Django?
| 664,937
|
<p>I've got a Django-based site that allows users to register (but requires an admin to approve the account before they can view certain parts of the site). I'm basing it off of <code>django.contrib.auth</code>. I require users to register with an email address from a certain domain name, so I've overridden the <code>UserCreationForm</code>'s <code>save()</code> and <code>clean_email()</code> methods.</p>
<p>My registration page uses the following view. I'm interested in hearing about how I might improve this viewâcode improvements or process improvements (or anything else, really).</p>
<pre><code>def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
message = None
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = user.email
# If valid new user account
if (user is not None) and (user.is_active):
login(request, user)
message = "<strong>Congratulations!</strong> You have been registered."
# Send emails
try:
# Admin email
pk = None
try: pk = User.objects.filter(username=username)[0].pk
except: pass
admin_email_template = loader.get_template('accounts/email_notify_admin_of_registration.txt')
admin_email_context = Context({
'first_name': first_name,
'last_name': last_name,
'username': username,
'email': email,
'pk': pk,
})
admin_email_body = admin_email_template.render(admin_email_context)
mail_admins("New User Registration", admin_email_body)
# User email
user_email_template = loader.get_template('accounts/email_registration_success.txt')
user_email_context = Context({
'first_name': form.cleaned_data['first_name'],
'username': username,
'password': password,
})
user_email_body = user_email_template.render(user_email_context)
user.email_user("Successfully Registered at example.com", user_email_body)
except:
message = "There was an error sending you the confirmation email. You should still be able to login normally."
else:
message = "There was an error automatically logging you in. Try <a href=\"/login/\">logging in</a> manually."
# Display success page
return render_to_response('accounts/register_success.html', {
'username': username,
'message': message,
},
context_instance=RequestContext(request)
)
else: # If not POST
form = UserCreationForm()
return render_to_response('accounts/register.html', {
'form': form,
},
context_instance=RequestContext(request)
)
</code></pre>
| 3
|
2009-03-20T03:59:12Z
| 665,546
|
<p>I personally try to put the short branch of an if-else statement first. Especially if it returns. This to avoid getting large branches where its difficult to see what ends where. Many others do like you have done and put a comment at the else statement. But python doesnt always have an end of block statement - like if a form isn't valid for you. </p>
<p>So for example:</p>
<pre><code>def register(request):
if request.method != 'POST':
form = UserCreationForm()
return render_to_response('accounts/register.html',
{ 'form': form, },
context_instance=RequestContext(request)
)
form = UserCreationForm(request.POST)
if not form.is_valid():
return render_to_response('accounts/register.html',
{ 'form': form, },
context_instance=RequestContext(request)
)
...
</code></pre>
| 3
|
2009-03-20T09:59:39Z
|
[
"python",
"django",
"user-registration"
] |
box drawing in python
| 664,991
|
<p>Platform: WinXP SP2, python 2.5.4.3. (activestate distribution)</p>
<p>Has anyone succeded in writing out <a href="http://en.wikipedia.org/wiki/Box%5Fdrawing%5Fcharacters" rel="nofollow">box drawing characters</a> in python?
When I try to run this:</p>
<pre><code>print u'\u2500'
print u'\u2501'
print u'\u2502'
print u'\u2503'
print u'\u2504'
</code></pre>
<p>All tips appreciated. What am I doing wrong ? Does python support full unicode ? Is it possible at all to get those characters to print.</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/637396/default-encoding-for-python-for-stderr">Default encoding for python for stderr?</a></li>
</ul>
| 4
|
2009-03-20T04:31:03Z
| 665,011
|
<p>Printing them will print in the default character encoding, which perhaps is not the right encoding for your terminal.</p>
<p>Have you tried transcoding them to utf-8 first?</p>
<pre><code>print u'\u2500'.encode('utf-8')
print u'\u2501'.encode('utf-8')
print u'\u2502'.encode('utf-8')
print u'\u2503'.encode('utf-8')
print u'\u2504'.encode('utf-8')
</code></pre>
<p>This works for me on linux in a terminal that supports utf-8 encoded data.</p>
| 1
|
2009-03-20T04:44:41Z
|
[
"python",
"windows",
"unicode"
] |
box drawing in python
| 664,991
|
<p>Platform: WinXP SP2, python 2.5.4.3. (activestate distribution)</p>
<p>Has anyone succeded in writing out <a href="http://en.wikipedia.org/wiki/Box%5Fdrawing%5Fcharacters" rel="nofollow">box drawing characters</a> in python?
When I try to run this:</p>
<pre><code>print u'\u2500'
print u'\u2501'
print u'\u2502'
print u'\u2503'
print u'\u2504'
</code></pre>
<p>All tips appreciated. What am I doing wrong ? Does python support full unicode ? Is it possible at all to get those characters to print.</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/637396/default-encoding-for-python-for-stderr">Default encoding for python for stderr?</a></li>
</ul>
| 4
|
2009-03-20T04:31:03Z
| 665,053
|
<p>This varies greatly based on what your terminal supports. If it uses UTF-8, and if Python can detect it, then it works just fine.</p>
<pre><code>>>> print u'\u2500'
â
>>> print u'\u2501'
â
>>> print u'\u2502'
â
>>> print u'\u2503'
â
>>> print u'\u2504'
â
</code></pre>
| 2
|
2009-03-20T05:08:09Z
|
[
"python",
"windows",
"unicode"
] |
box drawing in python
| 664,991
|
<p>Platform: WinXP SP2, python 2.5.4.3. (activestate distribution)</p>
<p>Has anyone succeded in writing out <a href="http://en.wikipedia.org/wiki/Box%5Fdrawing%5Fcharacters" rel="nofollow">box drawing characters</a> in python?
When I try to run this:</p>
<pre><code>print u'\u2500'
print u'\u2501'
print u'\u2502'
print u'\u2503'
print u'\u2504'
</code></pre>
<p>All tips appreciated. What am I doing wrong ? Does python support full unicode ? Is it possible at all to get those characters to print.</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/637396/default-encoding-for-python-for-stderr">Default encoding for python for stderr?</a></li>
</ul>
| 4
|
2009-03-20T04:31:03Z
| 665,377
|
<p>Your problem is not in Python but in cmd.exe. It has to be set to support UTF-8. Unfortunately, it is not very easy to switch windows console (cmd.exe) to UTF-8 "Python-compatible" way.</p>
<p>You can use command (in cmd.exe) to switch to UTF8:</p>
<pre><code>chcp 65001
</code></pre>
<p>but Python (2.5) does not recognize that encoding. Anyway you have to set correct font that support unicode!</p>
<p>For box drawing, I recommend to use old dos codepage 437, so you need to set up it before running python script:</p>
<pre><code>chcp 437
</code></pre>
<p>Then you can print cp437 encoded chars directly to stdout or decode chars to unicode and print unicode, try this script:</p>
<pre><code># -*- coding: utf-8 -*-
for i in range(0xB3, 0xDA):
print chr(i).decode('cp437'),
# without decoding (see comment by J.F.Sebastian)
print ''.join(map(chr, range(0xb3, 0xda)))
</code></pre>
<p>However, you can use box drawing chars, but you cannot use other chars you may need because of limitation of cp437.</p>
| 4
|
2009-03-20T08:51:40Z
|
[
"python",
"windows",
"unicode"
] |
box drawing in python
| 664,991
|
<p>Platform: WinXP SP2, python 2.5.4.3. (activestate distribution)</p>
<p>Has anyone succeded in writing out <a href="http://en.wikipedia.org/wiki/Box%5Fdrawing%5Fcharacters" rel="nofollow">box drawing characters</a> in python?
When I try to run this:</p>
<pre><code>print u'\u2500'
print u'\u2501'
print u'\u2502'
print u'\u2503'
print u'\u2504'
</code></pre>
<p>All tips appreciated. What am I doing wrong ? Does python support full unicode ? Is it possible at all to get those characters to print.</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/637396/default-encoding-for-python-for-stderr">Default encoding for python for stderr?</a></li>
</ul>
| 4
|
2009-03-20T04:31:03Z
| 665,407
|
<p>Python supports Unicode. It is possible to print these characters. </p>
<p>For example, see <a href="http://stackoverflow.com/questions/637396/default-encoding-for-python-for-stderr/638823#638823">my answer</a> to <a href="http://stackoverflow.com/questions/637396/default-encoding-for-python-for-stderr">"Default encoding for python for stderr?"</a> where I've showed how to print Unicode to <code>sys.stderr</code> (replace it by <code>sys.stdout</code> for bare <code>print</code> statements).</p>
| 0
|
2009-03-20T09:04:22Z
|
[
"python",
"windows",
"unicode"
] |
Python: defaultdict became unmarshallable object in 2.6?
| 665,061
|
<p>Did defaultdict's become not marshal'able as of Python 2.6? The following works under 2.5, fails under 2.6 with "ValueError: unmarshallable object" on OS X 1.5.6, python-2.6.1-macosx2008-12-06.dmg from python.org:</p>
<pre><code>from collections import defaultdict
import marshal
dd = defaultdict(list)
marshal.dump(dd, file('/tmp/junk.bin','wb') )
</code></pre>
| 9
|
2009-03-20T05:12:27Z
| 665,283
|
<p><a href="http://svn.python.org/view?view=rev&revision=58893">Marshal was deliberately changed to not support subclasses of built-in types</a>. Marshal was never supposed to handle defaultdicts, but happened to since they are a subclass of dict. <a href="http://docs.python.org/library/marshal.html">Marshal is <strong>not</strong> a general "persistence" module; only None, integers, long integers, floating point numbers, strings, Unicode objects, tuples, lists, sets, dictionaries, and code objects are supported</a>.</p>
<p>Python 2.5:</p>
<pre><code>>>> marshal.dumps(defaultdict(list))
'{0'
>>> marshal.dumps(dict())
'{0'
</code></pre>
<p>If for some reason you really want to marshal a defaultdict you can convert it to a dict first, but odds are you should be using a different serialization mechanism, like <a href="http://docs.python.org/library/pickle.html">pickling</a>.</p>
| 11
|
2009-03-20T07:50:49Z
|
[
"python"
] |
Python: defaultdict became unmarshallable object in 2.6?
| 665,061
|
<p>Did defaultdict's become not marshal'able as of Python 2.6? The following works under 2.5, fails under 2.6 with "ValueError: unmarshallable object" on OS X 1.5.6, python-2.6.1-macosx2008-12-06.dmg from python.org:</p>
<pre><code>from collections import defaultdict
import marshal
dd = defaultdict(list)
marshal.dump(dd, file('/tmp/junk.bin','wb') )
</code></pre>
| 9
|
2009-03-20T05:12:27Z
| 944,344
|
<p>wrt performance issues.. encoding a list of ~600000 dicts, each with 4 key/values, one of the values has a list (around 1-3 length) of 2 key/val dicts:</p>
<pre><code>In [27]: timeit(cjson.encode, data)
4.93589496613
In [28]: timeit(cPickle.dumps, data, -1)
141.412974119
In [30]: timeit(marshal.dumps, data, marshal.version)
1.13546991348
</code></pre>
| 7
|
2009-06-03T12:01:32Z
|
[
"python"
] |
Python: Running all unit tests inside a package
| 665,093
|
<p>I'm trying to hack my through an open source python project (namely: jinja2), </p>
<p>When I say "I'm hacking my way through", I mean I don't really know what I'm doing, so I want to run unittests whenever I change something to make sure I'm not breaking something major!</p>
<p>There's a package full of unit tests (if you want to have a look, <a href="http://dev.pocoo.org/projects/jinja/browser/tests" rel="nofollow">it's here</a>). Basically it's a folder full of python files with the name "test_xxxxxx.py"</p>
<p>How do I run all of these tests in one command?</p>
| 1
|
2009-03-20T05:39:41Z
| 665,095
|
<p>It looks like Jinja uses the <a href="http://codespeak.net/py/dist/test.html" rel="nofollow">py.test testing tool</a>. If so you can run all tests by just running <em>py.test</em> from within the tests subdirectory.</p>
| 1
|
2009-03-20T05:43:48Z
|
[
"python",
"unit-testing",
"jinja2"
] |
Python: Running all unit tests inside a package
| 665,093
|
<p>I'm trying to hack my through an open source python project (namely: jinja2), </p>
<p>When I say "I'm hacking my way through", I mean I don't really know what I'm doing, so I want to run unittests whenever I change something to make sure I'm not breaking something major!</p>
<p>There's a package full of unit tests (if you want to have a look, <a href="http://dev.pocoo.org/projects/jinja/browser/tests" rel="nofollow">it's here</a>). Basically it's a folder full of python files with the name "test_xxxxxx.py"</p>
<p>How do I run all of these tests in one command?</p>
| 1
|
2009-03-20T05:39:41Z
| 665,376
|
<p>Try to 'walk' through the directories and import all from files like "test_xxxxxx.py", then call unittest.main()</p>
| 0
|
2009-03-20T08:51:11Z
|
[
"python",
"unit-testing",
"jinja2"
] |
Python: Running all unit tests inside a package
| 665,093
|
<p>I'm trying to hack my through an open source python project (namely: jinja2), </p>
<p>When I say "I'm hacking my way through", I mean I don't really know what I'm doing, so I want to run unittests whenever I change something to make sure I'm not breaking something major!</p>
<p>There's a package full of unit tests (if you want to have a look, <a href="http://dev.pocoo.org/projects/jinja/browser/tests" rel="nofollow">it's here</a>). Basically it's a folder full of python files with the name "test_xxxxxx.py"</p>
<p>How do I run all of these tests in one command?</p>
| 1
|
2009-03-20T05:39:41Z
| 666,327
|
<p>You could also take a look at <a href="http://somethingaboutorange.com/mrl/projects/nose/" rel="nofollow">nose</a> too. It's supposed to be a py.test evolution.</p>
| 0
|
2009-03-20T14:17:34Z
|
[
"python",
"unit-testing",
"jinja2"
] |
Python: Running all unit tests inside a package
| 665,093
|
<p>I'm trying to hack my through an open source python project (namely: jinja2), </p>
<p>When I say "I'm hacking my way through", I mean I don't really know what I'm doing, so I want to run unittests whenever I change something to make sure I'm not breaking something major!</p>
<p>There's a package full of unit tests (if you want to have a look, <a href="http://dev.pocoo.org/projects/jinja/browser/tests" rel="nofollow">it's here</a>). Basically it's a folder full of python files with the name "test_xxxxxx.py"</p>
<p>How do I run all of these tests in one command?</p>
| 1
|
2009-03-20T05:39:41Z
| 1,936,845
|
<p>Watch out for "test.py" in the Jinja2 package! -- Those are not unit tests! That is a set of utility functions for checking attributes, etc. My testing package is assuming that they are unit tests because of the name "test" -- and returning strange messages.</p>
| 0
|
2009-12-20T20:09:33Z
|
[
"python",
"unit-testing",
"jinja2"
] |
Status of shift and caps lock in Python
| 665,502
|
<p>I'm writing a TkInter application using Python 2.5 and I need to find out the status of the caps lock and shift keys (either true or false). I've searched all over the net but cant find a solution.</p>
| 1
|
2009-03-20T09:43:04Z
| 665,559
|
<p><code>Lock</code> and <code>Shift</code> event modifiers:</p>
<p><a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/event-modifiers.html" rel="nofollow">http://infohost.nmt.edu/tcc/help/pubs/tkinter/event-modifiers.html</a></p>
| 0
|
2009-03-20T10:08:20Z
|
[
"python",
"tkinter"
] |
Status of shift and caps lock in Python
| 665,502
|
<p>I'm writing a TkInter application using Python 2.5 and I need to find out the status of the caps lock and shift keys (either true or false). I've searched all over the net but cant find a solution.</p>
| 1
|
2009-03-20T09:43:04Z
| 665,571
|
<p>I googled and got one..
I am not sure whether it works for you for all keys...</p>
<p><a href="http://www.java2s.com/Code/Python/Event/KeyactionFunctionKeyALtControlShift.htm" rel="nofollow">http://www.java2s.com/Code/Python/Event/KeyactionFunctionKeyALtControlShift.htm</a></p>
| 0
|
2009-03-20T10:11:50Z
|
[
"python",
"tkinter"
] |
Status of shift and caps lock in Python
| 665,502
|
<p>I'm writing a TkInter application using Python 2.5 and I need to find out the status of the caps lock and shift keys (either true or false). I've searched all over the net but cant find a solution.</p>
| 1
|
2009-03-20T09:43:04Z
| 665,583
|
<p>Keyboard events in Tkinter can be tricky.</p>
<p>I suggest you have a look at the following, in order:</p>
<ul>
<li><a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm" rel="nofollow">http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm</a></li>
<li><a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/events.html" rel="nofollow">http://infohost.nmt.edu/tcc/help/pubs/tkinter/events.html</a> (read the whole chapter on events)</li>
<li><a href="http://www.faqts.com/knowledge_base/view.phtml/aid/4281" rel="nofollow">http://www.faqts.com/knowledge_base/view.phtml/aid/4281</a></li>
</ul>
<p>Here is a program that displays the value of the keycode and state event parameters. You can use this to experiment. Click in the window, then hit the keyboard.</p>
<pre><code>from Tkinter import *
root = Tk()
def key(event):
print "Keycode:", event.keycode, "State:", event.state
def callback(event):
frame.focus_set()
print "clicked at", event.x, event.y
frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()
root.mainloop()
</code></pre>
| 2
|
2009-03-20T10:16:34Z
|
[
"python",
"tkinter"
] |
How do I go about writing a program to send and receive sms using python?
| 665,536
|
<p>I have looked all over the net for a good library to use in sending and receiving sms's using python but all in vain!</p>
<p>Are there GSM libraries for python out there?</p>
| 4
|
2009-03-20T09:55:15Z
| 665,561
|
<p>Have you looked at <a href="http://code.google.com/p/py-sms/" rel="nofollow">py-sms</a>?</p>
| 2
|
2009-03-20T10:09:01Z
|
[
"python",
"sms",
"gsm",
"at-command"
] |
How do I go about writing a program to send and receive sms using python?
| 665,536
|
<p>I have looked all over the net for a good library to use in sending and receiving sms's using python but all in vain!</p>
<p>Are there GSM libraries for python out there?</p>
| 4
|
2009-03-20T09:55:15Z
| 665,579
|
<p><a href="http://www.gammu.org/wiki/index.php?title=Gammu:Python-gammu" rel="nofollow">Python-binding</a> for <a href="http://en.wikipedia.org/wiki/Gammu%5F%28software%29" rel="nofollow">Gammu</a> perhaps? </p>
<p>BTW. It's GUI version (<a href="http://en.wikipedia.org/wiki/Wammu" rel="nofollow">Wammu</a>) is written in wxPython.</p>
| 2
|
2009-03-20T10:15:01Z
|
[
"python",
"sms",
"gsm",
"at-command"
] |
How do I go about writing a program to send and receive sms using python?
| 665,536
|
<p>I have looked all over the net for a good library to use in sending and receiving sms's using python but all in vain!</p>
<p>Are there GSM libraries for python out there?</p>
| 4
|
2009-03-20T09:55:15Z
| 665,881
|
<p>I have recently written some code for interacting with Huawei 3G USB modems in python.</p>
<p>My initial prototype used pyserial directly, and then my production code used Twisted's Serial support so I can access the modem asynchronously.</p>
<p>I found that by accessing the modem programatically using the serial port I was able to access all the functionality required to send and receive SMS messages using Hayes AT commands and extensions to the AT command set.</p>
<p>This is the <a href="http://wiki.forum.nokia.com/index.php/AT%5FCommands" rel="nofollow">one of the referneces</a> I was able to find on the topic, it lists these commands:</p>
<pre><code>AT+CMGL List Messages
AT+CMGR Read message
AT+CMGS Send message
AT+CMGW Write message to memory
</code></pre>
<p>They are complicated commands and take arguments and you have to parse the results yourself.</p>
<p><a href="http://www.developershome.com/sms/cmgsCommand.asp" rel="nofollow">There are more references</a> on the internet you can google for that reference these 4 commands that will let you work out how your modem works.</p>
| 2
|
2009-03-20T12:10:32Z
|
[
"python",
"sms",
"gsm",
"at-command"
] |
How do I go about writing a program to send and receive sms using python?
| 665,536
|
<p>I have looked all over the net for a good library to use in sending and receiving sms's using python but all in vain!</p>
<p>Are there GSM libraries for python out there?</p>
| 4
|
2009-03-20T09:55:15Z
| 665,994
|
<p>Also check <a href="http://mobilehacking.org/index.php/PyKannel" rel="nofollow">PyKannel</a>.</p>
<p>There's also a web service for sending and receiving SMS (non-free, of course), but I don't have URL at hand. :(</p>
| 0
|
2009-03-20T12:48:32Z
|
[
"python",
"sms",
"gsm",
"at-command"
] |
How do I go about writing a program to send and receive sms using python?
| 665,536
|
<p>I have looked all over the net for a good library to use in sending and receiving sms's using python but all in vain!</p>
<p>Are there GSM libraries for python out there?</p>
| 4
|
2009-03-20T09:55:15Z
| 1,071,517
|
<p>I provided a detailed answer to a similar question <a href="http://stackoverflow.com/questions/716946/how-do-i-enable-sms-notifications-in-my-web-app/1071496#1071496">here</a>. I mention a Python interface to an SMS gateway provided by TextMagic.</p>
| 1
|
2009-07-01T21:38:08Z
|
[
"python",
"sms",
"gsm",
"at-command"
] |
How do I go about writing a program to send and receive sms using python?
| 665,536
|
<p>I have looked all over the net for a good library to use in sending and receiving sms's using python but all in vain!</p>
<p>Are there GSM libraries for python out there?</p>
| 4
|
2009-03-20T09:55:15Z
| 12,443,201
|
<p>I was at a hackday where we had free access to a few APIs, including <a href="http://www.twilio.com/" rel="nofollow">twillio</a>. It was very easy to use their python library to send and receive SMS, and we built an app around it in about 3 hours (twillio integration was about 15 minutes).</p>
| 0
|
2012-09-15T23:18:47Z
|
[
"python",
"sms",
"gsm",
"at-command"
] |
Redirect command line results to a tkinter GUI
| 665,566
|
<p>I have created a program that prints results on command line.
(It is server and it prints log on command line.)</p>
<p>Now, I want to see the same result to GUI .</p>
<p><strong>How can I redirect command line results to GUI?</strong></p>
<p>Please, suggest a trick to easily transform console application to simple GUI.</p>
<p>Note that it should work on Linux and Windows.</p>
| 11
|
2009-03-20T10:10:19Z
| 665,598
|
<p>You could create a script wrapper that runs your command line program as a sub process, then add the output to something like a text widget.</p>
<pre><code>from tkinter import *
import subprocess as sub
p = sub.Popen('./script',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
root = Tk()
text = Text(root)
text.pack()
text.insert(END, output)
root.mainloop()
</code></pre>
<p>where script is your program. You can obviously print the errors in a different colour, or something like that.</p>
| 9
|
2009-03-20T10:23:53Z
|
[
"python",
"user-interface",
"tkinter"
] |
Redirect command line results to a tkinter GUI
| 665,566
|
<p>I have created a program that prints results on command line.
(It is server and it prints log on command line.)</p>
<p>Now, I want to see the same result to GUI .</p>
<p><strong>How can I redirect command line results to GUI?</strong></p>
<p>Please, suggest a trick to easily transform console application to simple GUI.</p>
<p>Note that it should work on Linux and Windows.</p>
| 11
|
2009-03-20T10:10:19Z
| 665,847
|
<p>Redirecting stdout to a write() method that updates your gui is one way to go, and probably the quickest - although running a subprocess is probably a more elegant solution. </p>
<p>Only redirect stderr once you're really confident it's up and working, though!</p>
<p>Example implimentation (gui file and test script):</p>
<p>test_gui.py:</p>
<pre><code>from Tkinter import *
import sys
sys.path.append("/path/to/script/file/directory/")
class App(Frame):
def run_script(self):
sys.stdout = self
## sys.stderr = self
try:
del(sys.modules["test_script"])
except:
## Yeah, it's a real ugly solution...
pass
import test_script
test_script.HelloWorld()
sys.stdout = sys.__stdout__
## sys.stderr = __stderr__
def build_widgets(self):
self.text1 = Text(self)
self.text1.pack(side=TOP)
self.button = Button(self)
self.button["text"] = "Trigger script"
self.button["command"] = self.run_script
self.button.pack(side=TOP)
def write(self, txt):
self.text1.insert(INSERT, txt)
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.build_widgets()
root = Tk()
app = App(master = root)
app.mainloop()
</code></pre>
<p>test_script.py:</p>
<pre><code>print "Hello world!"
def HelloWorld():
print "HelloWorldFromDef!"
</code></pre>
| 2
|
2009-03-20T12:01:36Z
|
[
"python",
"user-interface",
"tkinter"
] |
Redirect command line results to a tkinter GUI
| 665,566
|
<p>I have created a program that prints results on command line.
(It is server and it prints log on command line.)</p>
<p>Now, I want to see the same result to GUI .</p>
<p><strong>How can I redirect command line results to GUI?</strong></p>
<p>Please, suggest a trick to easily transform console application to simple GUI.</p>
<p>Note that it should work on Linux and Windows.</p>
| 11
|
2009-03-20T10:10:19Z
| 32,682,520
|
<p>To display subprocess' output in a GUI <em>while it is still running</em>, a portable stdlib-only solution that works on both Python 2 and 3 has to use a background thread:</p>
<pre><code>#!/usr/bin/python
"""
- read output from a subprocess in a background thread
- show the output in the GUI
"""
import sys
from itertools import islice
from subprocess import Popen, PIPE
from textwrap import dedent
from threading import Thread
try:
import Tkinter as tk
from Queue import Queue, Empty
except ImportError:
import tkinter as tk # Python 3
from queue import Queue, Empty # Python 3
def iter_except(function, exception):
"""Works like builtin 2-argument `iter()`, but stops on `exception`."""
try:
while True:
yield function()
except exception:
return
class DisplaySubprocessOutputDemo:
def __init__(self, root):
self.root = root
# start dummy subprocess to generate some output
self.process = Popen([sys.executable, "-u", "-c", dedent("""
import itertools, time
for i in itertools.count():
print("%d.%d" % divmod(i, 10))
time.sleep(0.1)
""")], stdout=PIPE)
# launch thread to read the subprocess output
# (put the subprocess output into the queue in a background thread,
# get output from the queue in the GUI thread.
# Output chain: process.readline -> queue -> label)
q = Queue(maxsize=1024) # limit output buffering (may stall subprocess)
t = Thread(target=self.reader_thread, args=[q])
t.daemon = True # close pipe if GUI process exits
t.start()
# show subprocess' stdout in GUI
self.label = tk.Label(root, text=" ", font=(None, 200))
self.label.pack(ipadx=4, padx=4, ipady=4, pady=4, fill='both')
self.update(q) # start update loop
def reader_thread(self, q):
"""Read subprocess output and put it into the queue."""
try:
with self.process.stdout as pipe:
for line in iter(pipe.readline, b''):
q.put(line)
finally:
q.put(None)
def update(self, q):
"""Update GUI with items from the queue."""
for line in iter_except(q.get_nowait, Empty): # display all content
if line is None:
self.quit()
return
else:
self.label['text'] = line # update GUI
break # display no more than one line per 40 milliseconds
self.root.after(40, self.update, q) # schedule next update
def quit(self):
self.process.kill() # exit subprocess if GUI is closed (zombie!)
self.root.destroy()
root = tk.Tk()
app = DisplaySubprocessOutputDemo(root)
root.protocol("WM_DELETE_WINDOW", app.quit)
# center window
root.eval('tk::PlaceWindow %s center' % root.winfo_pathname(root.winfo_id()))
root.mainloop()
</code></pre>
<p>The essence of the solution is:</p>
<ul>
<li>put the subprocess output into the queue in a background thread</li>
<li>get the output from the queue in the GUI thread.</li>
</ul>
<p>i.e., call <code>process.readline()</code> in the background thread -> queue -> update GUI label in the main thread.</p>
| 2
|
2015-09-20T17:55:36Z
|
[
"python",
"user-interface",
"tkinter"
] |
Extract array from list in python
| 665,652
|
<p>If I have a list like this:</p>
<p><code>>>> data = [(1,2),(40,2),(9,80)]</code></p>
<p>how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ?</p>
| 4
|
2009-03-20T10:48:18Z
| 665,662
|
<p>List comprehensions save the day:</p>
<pre><code>first = [x for (x,y) in data]
second = [y for (x,y) in data]
</code></pre>
| 14
|
2009-03-20T10:50:37Z
|
[
"python",
"arrays",
"list"
] |
Extract array from list in python
| 665,652
|
<p>If I have a list like this:</p>
<p><code>>>> data = [(1,2),(40,2),(9,80)]</code></p>
<p>how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ?</p>
| 4
|
2009-03-20T10:48:18Z
| 665,684
|
<p>The unzip operation is:</p>
<pre><code>In [1]: data = [(1,2),(40,2),(9,80)]
In [2]: zip(*data)
Out[2]: [(1, 40, 9), (2, 2, 80)]
</code></pre>
<p>Edit: You can decompose the resulting list on assignment:</p>
<pre><code>In [3]: first_elements, second_elements = zip(*data)
</code></pre>
<p>And if you really need lists as results:</p>
<pre><code>In [4]: first_elements, second_elements = map(list, zip(*data))
</code></pre>
<p>To better understand why this works:</p>
<pre><code>zip(*data)
</code></pre>
<p>is equivalent to</p>
<pre><code>zip((1,2), (40,2), (9,80))
</code></pre>
<p>The two tuples in the result list are built from the first elements of zip()'s arguments and from the second elements of zip()'s arguments.</p>
| 26
|
2009-03-20T10:58:18Z
|
[
"python",
"arrays",
"list"
] |
Extract array from list in python
| 665,652
|
<p>If I have a list like this:</p>
<p><code>>>> data = [(1,2),(40,2),(9,80)]</code></p>
<p>how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ?</p>
| 4
|
2009-03-20T10:48:18Z
| 665,927
|
<p>There is also </p>
<pre><code>In [1]: data = [(1,2),(40,2),(9,80)]
In [2]: x=map(None, *data)
Out[2]: [(1, 40, 9), (2, 2, 80)]
In [3]: map(None,*x)
Out[3]: [(1, 2), (40, 2), (9, 80)]
</code></pre>
| 5
|
2009-03-20T12:27:08Z
|
[
"python",
"arrays",
"list"
] |
Best continuously updated resource about python web "plumbing"
| 665,848
|
<p>I'm a programmer in Python who works on web-applications. I know a fair bit about the application level. But not so much about the underlying "plumbing" which I find myself having to configure or debug.</p>
<p>I'm thinking of everything from using memcached to flup, fcgi, WSGI etc.</p>
<p>When looking for information about these, online, Google typically delivers older-documents (eg. tutorials from before 2007), fragments of problems that may or may not have been resolved etc.</p>
<p>Are there any good comprehensive and up-to-date resources to learn about how to put together a modern, high-performance server? One that explains both principles of the architecture and the actual packages?</p>
| 3
|
2009-03-20T12:02:10Z
| 665,869
|
<p>Buy this. <a href="http://rads.stackoverflow.com/amzn/click/067232699X" rel="nofollow">http://www.amazon.com/Scalable-Internet-Architectures-Developers-Library/dp/067232699X</a></p>
| 1
|
2009-03-20T12:05:30Z
|
[
"python",
"wsgi",
"flup"
] |
Best continuously updated resource about python web "plumbing"
| 665,848
|
<p>I'm a programmer in Python who works on web-applications. I know a fair bit about the application level. But not so much about the underlying "plumbing" which I find myself having to configure or debug.</p>
<p>I'm thinking of everything from using memcached to flup, fcgi, WSGI etc.</p>
<p>When looking for information about these, online, Google typically delivers older-documents (eg. tutorials from before 2007), fragments of problems that may or may not have been resolved etc.</p>
<p>Are there any good comprehensive and up-to-date resources to learn about how to put together a modern, high-performance server? One that explains both principles of the architecture and the actual packages?</p>
| 3
|
2009-03-20T12:02:10Z
| 665,951
|
<p><em>Zope</em> is a still evolving framework, written in <em>Python</em> and is documented online. For a start, see <a href="http://docs.zope.org/zope2/zope2book/source/ZopeArchitecture.html" rel="nofollow">Zope Concepts and Architecture</a>. Like other <em>Python</em> based web frameworks, the <a href="http://www.zope.org/DevHome/Subversion/FrontPage" rel="nofollow">source</a> is your best reference.</p>
<p>Note that <em>Zope</em> is not easy to grasp, and is different from frameworks like <em>Django</em>.</p>
| 0
|
2009-03-20T12:33:53Z
|
[
"python",
"wsgi",
"flup"
] |
Best continuously updated resource about python web "plumbing"
| 665,848
|
<p>I'm a programmer in Python who works on web-applications. I know a fair bit about the application level. But not so much about the underlying "plumbing" which I find myself having to configure or debug.</p>
<p>I'm thinking of everything from using memcached to flup, fcgi, WSGI etc.</p>
<p>When looking for information about these, online, Google typically delivers older-documents (eg. tutorials from before 2007), fragments of problems that may or may not have been resolved etc.</p>
<p>Are there any good comprehensive and up-to-date resources to learn about how to put together a modern, high-performance server? One that explains both principles of the architecture and the actual packages?</p>
| 3
|
2009-03-20T12:02:10Z
| 665,953
|
<ul>
<li>General info about highly efficient web architecture: <a href="http://highscalability.com/" rel="nofollow">http://highscalability.com/</a></li>
<li>Interesting Python related articles: <a href="http://www.onlamp.com/python/" rel="nofollow">http://www.onlamp.com/python/</a> </li>
<li>Printed magazine: <a href="http://pythonmagazine.com/" rel="nofollow">http://pythonmagazine.com/</a></li>
</ul>
| 1
|
2009-03-20T12:35:27Z
|
[
"python",
"wsgi",
"flup"
] |
Best continuously updated resource about python web "plumbing"
| 665,848
|
<p>I'm a programmer in Python who works on web-applications. I know a fair bit about the application level. But not so much about the underlying "plumbing" which I find myself having to configure or debug.</p>
<p>I'm thinking of everything from using memcached to flup, fcgi, WSGI etc.</p>
<p>When looking for information about these, online, Google typically delivers older-documents (eg. tutorials from before 2007), fragments of problems that may or may not have been resolved etc.</p>
<p>Are there any good comprehensive and up-to-date resources to learn about how to put together a modern, high-performance server? One that explains both principles of the architecture and the actual packages?</p>
| 3
|
2009-03-20T12:02:10Z
| 667,316
|
<p>You can use this terminology to limit search results to the past year:</p>
<p><a href="http://www.tech-recipes.com/rx/2860/google_how_to_access_filter_by_date_dropdown_box/" rel="nofollow">http://www.tech-recipes.com/rx/2860/google_how_to_access_filter_by_date_dropdown_box/</a></p>
| 0
|
2009-03-20T18:10:45Z
|
[
"python",
"wsgi",
"flup"
] |
How to write a function that takes a string and prints the letters in decreasing order of frequency?
| 665,942
|
<p>I got this far:</p>
<pre><code>def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
</code></pre>
<p>Returning:</p>
<pre><code>{'a': 2, 'c': 1, 'b': 3}
</code></pre>
<p>Now I need to:</p>
<ol>
<li>reverse the pair</li>
<li>sort by number by decreasing order</li>
<li>only print the letters out</li>
</ol>
<p>Should I convert this dictionary to tuples or list?</p>
| 4
|
2009-03-20T12:32:19Z
| 665,980
|
<p>This should do it nicely.</p>
<pre><code>def frequency_analysis(string):
d = dict()
for key in string:
d[key] = d.get(key, 0) + 1
return d
def letters_in_order_of_frequency(string):
frequencies = frequency_analysis(string)
# frequencies is of bounded size because number of letters is bounded by the dictionary, not the input size
frequency_list = [(freq, letter) for (letter, freq) in frequencies.iteritems()]
frequency_list.sort(reverse=True)
return [letter for freq, letter in frequency_list]
string = 'aabbbc'
print letters_in_order_of_frequency(string)
</code></pre>
| 4
|
2009-03-20T12:44:10Z
|
[
"python"
] |
How to write a function that takes a string and prints the letters in decreasing order of frequency?
| 665,942
|
<p>I got this far:</p>
<pre><code>def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
</code></pre>
<p>Returning:</p>
<pre><code>{'a': 2, 'c': 1, 'b': 3}
</code></pre>
<p>Now I need to:</p>
<ol>
<li>reverse the pair</li>
<li>sort by number by decreasing order</li>
<li>only print the letters out</li>
</ol>
<p>Should I convert this dictionary to tuples or list?</p>
| 4
|
2009-03-20T12:32:19Z
| 665,991
|
<p>Here's a one line answer</p>
<pre><code>sortedLetters = sorted(d.iteritems(), key=lambda (k,v): (v,k))
</code></pre>
| 12
|
2009-03-20T12:47:42Z
|
[
"python"
] |
How to write a function that takes a string and prints the letters in decreasing order of frequency?
| 665,942
|
<p>I got this far:</p>
<pre><code>def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
</code></pre>
<p>Returning:</p>
<pre><code>{'a': 2, 'c': 1, 'b': 3}
</code></pre>
<p>Now I need to:</p>
<ol>
<li>reverse the pair</li>
<li>sort by number by decreasing order</li>
<li>only print the letters out</li>
</ol>
<p>Should I convert this dictionary to tuples or list?</p>
| 4
|
2009-03-20T12:32:19Z
| 665,998
|
<p>Here is something that returns a list of tuples rather than a dictionary:</p>
<pre><code>import operator
if __name__ == '__main__':
test_string = 'cnaa'
string_dict = dict()
for letter in test_string:
if letter not in string_dict:
string_dict[letter] = test_string.count(letter)
# Sort dictionary by values, credits go here http://stackoverflow.com/questions/613183/sort-a-dictionary-in-python-by-the-value/613218#613218
ordered_answer = sorted(string_dict.items(), key=operator.itemgetter(1), reverse=True)
print ordered_answer
</code></pre>
| 3
|
2009-03-20T12:49:48Z
|
[
"python"
] |
How to write a function that takes a string and prints the letters in decreasing order of frequency?
| 665,942
|
<p>I got this far:</p>
<pre><code>def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
</code></pre>
<p>Returning:</p>
<pre><code>{'a': 2, 'c': 1, 'b': 3}
</code></pre>
<p>Now I need to:</p>
<ol>
<li>reverse the pair</li>
<li>sort by number by decreasing order</li>
<li>only print the letters out</li>
</ol>
<p>Should I convert this dictionary to tuples or list?</p>
| 4
|
2009-03-20T12:32:19Z
| 666,045
|
<p>chills42 lambda function wins, I think but as an alternative, how about generating the dictionary with the counts as the keys instead?</p>
<pre><code>def count_chars(string):
distinct = set(string)
dictionary = {}
for s in distinct:
num = len(string.split(s)) - 1
dictionary[num] = s
return dictionary
def print_dict_in_reverse_order(d):
_list = d.keys()
_list.sort()
_list.reverse()
for s in _list:
print d[s]
</code></pre>
| 0
|
2009-03-20T13:04:36Z
|
[
"python"
] |
How to write a function that takes a string and prints the letters in decreasing order of frequency?
| 665,942
|
<p>I got this far:</p>
<pre><code>def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
</code></pre>
<p>Returning:</p>
<pre><code>{'a': 2, 'c': 1, 'b': 3}
</code></pre>
<p>Now I need to:</p>
<ol>
<li>reverse the pair</li>
<li>sort by number by decreasing order</li>
<li>only print the letters out</li>
</ol>
<p>Should I convert this dictionary to tuples or list?</p>
| 4
|
2009-03-20T12:32:19Z
| 666,048
|
<p><strong>EDIT</strong> This will do what you want. I'm stealing <strong>chills42</strong> line and adding another:</p>
<pre><code>sortedLetters = sorted(d.iteritems(), key=lambda (k,v): (v,k))
sortedString = ''.join([c[0] for c in reversed(sortedLetters)])
</code></pre>
<p>------------<em>original answer</em>------------</p>
<p>To print out the sorted string add another line to <strong>chills42</strong> one-liner:</p>
<pre><code>''.join(map(lambda c: str(c[0]*c[1]), reversed(sortedLetters)))
</code></pre>
<p>This prints out 'bbbaac'</p>
<p>If you want single letters, 'bac' use this:</p>
<pre><code>''.join([c[0] for c in reversed(sortedLetters)])
</code></pre>
| 2
|
2009-03-20T13:05:26Z
|
[
"python"
] |
How to write a function that takes a string and prints the letters in decreasing order of frequency?
| 665,942
|
<p>I got this far:</p>
<pre><code>def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
</code></pre>
<p>Returning:</p>
<pre><code>{'a': 2, 'c': 1, 'b': 3}
</code></pre>
<p>Now I need to:</p>
<ol>
<li>reverse the pair</li>
<li>sort by number by decreasing order</li>
<li>only print the letters out</li>
</ol>
<p>Should I convert this dictionary to tuples or list?</p>
| 4
|
2009-03-20T12:32:19Z
| 666,123
|
<pre><code>from collections import defaultdict
def most_frequent(s):
d = defaultdict(int)
for c in s:
d[c] += 1
return "".join([
k for k, v in sorted(
d.iteritems(), reverse=True, key=lambda (k, v): v)
])
</code></pre>
<p><strong>EDIT:</strong></p>
<p>here is my one liner:</p>
<pre><code>def most_frequent(s):
return "".join([
c for frequency, c in sorted(
[(s.count(c), c) for c in set(s)], reverse=True
)
])
</code></pre>
| 2
|
2009-03-20T13:25:24Z
|
[
"python"
] |
How to write a function that takes a string and prints the letters in decreasing order of frequency?
| 665,942
|
<p>I got this far:</p>
<pre><code>def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
</code></pre>
<p>Returning:</p>
<pre><code>{'a': 2, 'c': 1, 'b': 3}
</code></pre>
<p>Now I need to:</p>
<ol>
<li>reverse the pair</li>
<li>sort by number by decreasing order</li>
<li>only print the letters out</li>
</ol>
<p>Should I convert this dictionary to tuples or list?</p>
| 4
|
2009-03-20T12:32:19Z
| 666,155
|
<pre><code>def reversedSortedFrequency(string)
from collections import defaultdict
d = defaultdict(int)
for c in string:
d[c]+=1
return sorted([(v,k) for k,v in d.items()], key=lambda (k,v): -k)
</code></pre>
| 0
|
2009-03-20T13:31:16Z
|
[
"python"
] |
How to write a function that takes a string and prints the letters in decreasing order of frequency?
| 665,942
|
<p>I got this far:</p>
<pre><code>def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
</code></pre>
<p>Returning:</p>
<pre><code>{'a': 2, 'c': 1, 'b': 3}
</code></pre>
<p>Now I need to:</p>
<ol>
<li>reverse the pair</li>
<li>sort by number by decreasing order</li>
<li>only print the letters out</li>
</ol>
<p>Should I convert this dictionary to tuples or list?</p>
| 4
|
2009-03-20T12:32:19Z
| 666,349
|
<p>Here is the <strong>fixed version</strong> (thank you for pointing out bugs)</p>
<pre><code>def frequency(s):
return ''.join(
[k for k, v in
sorted(
reduce(
lambda d, c: d.update([[c, d.get(c, 0) + 1]]) or d,
list(s),
dict()).items(),
lambda a, b: cmp(a[1], b[1]),
reverse=True)])
</code></pre>
<p>I think the use of <code>reduce</code> makes the difference in this sollution compared to the others...</p>
<p>In action:</p>
<pre><code>>>> from frequency import frequency
>>> frequency('abbbccddddxxxyyyyyz')
'ydbxcaz'
</code></pre>
<p>This <strong>includes extracting the keys (and counting them)</strong> as well!!! Another nice property is the initialization of the dictionary on the same line :)</p>
<p>Also: <strong>no includes</strong>, just builtins.</p>
<p>The <code>reduce</code> function is kinda hard to wrap my head around, and setting dictionary values in a <code>lambda</code> is also a bit cumbersome in python, but, ah well, it works!</p>
| 0
|
2009-03-20T14:23:09Z
|
[
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.