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 |
|---|---|---|---|---|---|---|---|---|---|
How to convert strings numbers to integers in a list? | 818,949 | <p>I have a list say:</p>
<pre><code>['batting average', '306', 'ERA', '1710']
</code></pre>
<p>How can I convert the intended numbers without touching the strings?</p>
<p>Thank you for the help.</p>
| 9 | 2009-05-04T06:09:00Z | 818,956 | <pre><code>changed_list = [int(f) if f.isdigit() else f for f in original_list]
</code></pre>
| 41 | 2009-05-04T06:11:33Z | [
"python",
"string",
"integer",
"numbers"
] |
How to convert strings numbers to integers in a list? | 818,949 | <p>I have a list say:</p>
<pre><code>['batting average', '306', 'ERA', '1710']
</code></pre>
<p>How can I convert the intended numbers without touching the strings?</p>
<p>Thank you for the help.</p>
| 9 | 2009-05-04T06:09:00Z | 818,975 | <p>The data looks like you would know in which positions the numbers are supposed to be. In this case it's probably better to explicitly convert the data at these positions instead of just converting anything that looks like a number:</p>
<pre><code>ls = ['batting average', '306', 'ERA', '1710']
ls[1] = int(ls[1])
ls[3] = int(ls[3])
</code></pre>
| 5 | 2009-05-04T06:18:20Z | [
"python",
"string",
"integer",
"numbers"
] |
How to convert strings numbers to integers in a list? | 818,949 | <p>I have a list say:</p>
<pre><code>['batting average', '306', 'ERA', '1710']
</code></pre>
<p>How can I convert the intended numbers without touching the strings?</p>
<p>Thank you for the help.</p>
| 9 | 2009-05-04T06:09:00Z | 819,628 | <p>Try this:</p>
<pre><code>def convert( someList ):
for item in someList:
try:
yield int(item)
except ValueError:
yield item
newList= list( convert( oldList ) )
</code></pre>
| 5 | 2009-05-04T10:40:37Z | [
"python",
"string",
"integer",
"numbers"
] |
How to convert strings numbers to integers in a list? | 818,949 | <p>I have a list say:</p>
<pre><code>['batting average', '306', 'ERA', '1710']
</code></pre>
<p>How can I convert the intended numbers without touching the strings?</p>
<p>Thank you for the help.</p>
| 9 | 2009-05-04T06:09:00Z | 29,850,627 | <pre><code>a= ['batting average', '306', 'ERA', '1710.5']
[f if sum([c.isalpha() for c in f]) else float(f) for f in a ]
</code></pre>
<p>if your list contains float, string and int (as pointed about by @d.putto in the comment)</p>
| 0 | 2015-04-24T14:50:06Z | [
"python",
"string",
"integer",
"numbers"
] |
Is there a way to correctly sort unicode strings in SQLite using Python? | 819,211 | <p>Is there a simple way to order rows with unicode data in SQLite?</p>
| 1 | 2009-05-04T08:05:25Z | 819,248 | <p>There is a library called <a href="http://icu-project.org/" rel="nofollow">ICU</a> that can do proper unicode sorting for you; there's a good description in this other question:</p>
<p><a href="http://stackoverflow.com/questions/611459/how-to-sort-text-in-sqlite3-with-specified-locale">http://stackoverflow.com/questions/611459/how-to-sort-text-in-sqlite3-with-specified-locale</a></p>
| 2 | 2009-05-04T08:19:04Z | [
"python",
"sqlite",
"unicode"
] |
Is there a way to correctly sort unicode strings in SQLite using Python? | 819,211 | <p>Is there a simple way to order rows with unicode data in SQLite?</p>
| 1 | 2009-05-04T08:05:25Z | 819,281 | <p>SQLite has a BYOS (Bring Your Own Sorter) policy. See the FAQ for <a href="http://www.sqlite.org/faq.html#q18" rel="nofollow">more details</a>. They chose not to include (by default) any Unicode-aware sorting algorithm, to keep the SQLite library svelte and easy to statically link in. </p>
<p>However, you can <a href="http://www.sqlite.org/c3ref/create%5Fcollation.html" rel="nofollow">create a collator</a>, that sorts however you please, then tell SQLite to use it. As the other poster hinted at, there are collators in the source tree that do this using <a href="http://site.icu-project.org/" rel="nofollow">ICU</a>. However, you can also use your own, which makes sense if you're using a library like GLib that has its own Unicode-awareness.</p>
| 4 | 2009-05-04T08:34:17Z | [
"python",
"sqlite",
"unicode"
] |
Python, who is calling my python module | 819,217 | <p>I have one Python module that can be called by a CGI script (passing it information from a form) or from the command line (passing it options and arguments from the command line).
Is there a way to establish if the module has been called from the CGI script or from the command line ??</p>
| 3 | 2009-05-04T08:08:10Z | 819,240 | <p>This will do it:</p>
<pre><code>import os
if os.environ.has_key('REQUEST_METHOD'):
# You're being run as a CGI script.
else:
# You're being run from the command line.
</code></pre>
| 9 | 2009-05-04T08:15:38Z | [
"python",
"cgi"
] |
Python, who is calling my python module | 819,217 | <p>I have one Python module that can be called by a CGI script (passing it information from a form) or from the command line (passing it options and arguments from the command line).
Is there a way to establish if the module has been called from the CGI script or from the command line ??</p>
| 3 | 2009-05-04T08:08:10Z | 819,618 | <p>This is a really bad design idea. Your script should be designed to work independently of how it's called. The calling programs should provide a uniform environment.</p>
<p>You'll be happiest if you design your scripts to work in exactly one consistent way. Build things like this.</p>
<ul>
<li><p>myscript.py - the "real work" - defined in functions and classes. </p></li>
<li><p>myscript_cgi.py - a CGI interface that imports myscript and uses the classes and functions.</p></li>
<li><p>myscript_cli.py - the command-line interface that parses the command-line options, imports myscript, and uses the classes and functions.</p></li>
</ul>
<p>A single script that does all three things (real work, cgi interface, cli interface) is usually a mistake.</p>
| 6 | 2009-05-04T10:37:06Z | [
"python",
"cgi"
] |
Working with a QString encoding | 819,310 | <p>Is there a Python library which can detect (and perhaps decode) encoding of the string?</p>
<p>I found <a href="http://pypi.python.org/pypi/chardet" rel="nofollow"><code>chardet</code></a> but it gives me an error, using:</p>
<pre><code>chardet.detect(self.ui.TextFrom.toPlainText())
got: = chardet.detect(self.ui.TextFrom.toPlainText())
File .... u.feed(aBuf) File ....
if self._highBitDetector.search(aBuf):
TypeError: buffer size mismatch
</code></pre>
<p>Also: </p>
<pre><code>print type(self.ui.TextFrom.toPlainText())
# <class 'PyQt4.QtCore.QString'>
</code></pre>
| 1 | 2009-05-04T08:47:22Z | 819,338 | <p>I guess this is another option.</p>
<p><a href="http://cthedot.de/encutils/" rel="nofollow">http://cthedot.de/encutils/</a></p>
<blockquote>
<p>A collection of helper functions to detect encodings of text files (like HTML, XHTML, XML, CSS, etc.) retrieved via HTTP, file or string.</p>
</blockquote>
| 2 | 2009-05-04T08:55:36Z | [
"python",
"encoding"
] |
Working with a QString encoding | 819,310 | <p>Is there a Python library which can detect (and perhaps decode) encoding of the string?</p>
<p>I found <a href="http://pypi.python.org/pypi/chardet" rel="nofollow"><code>chardet</code></a> but it gives me an error, using:</p>
<pre><code>chardet.detect(self.ui.TextFrom.toPlainText())
got: = chardet.detect(self.ui.TextFrom.toPlainText())
File .... u.feed(aBuf) File ....
if self._highBitDetector.search(aBuf):
TypeError: buffer size mismatch
</code></pre>
<p>Also: </p>
<pre><code>print type(self.ui.TextFrom.toPlainText())
# <class 'PyQt4.QtCore.QString'>
</code></pre>
| 1 | 2009-05-04T08:47:22Z | 819,582 | <p>You need to convert your <code>QString</code> to a Python string before passing it to <code>chardet</code>. Change this:</p>
<pre><code>chardet.detect(self.ui.TextFrom.toPlainText())
</code></pre>
<p>to this:</p>
<pre><code>chardet.detect(str(self.ui.TextFrom.toPlainText()))
</code></pre>
| 7 | 2009-05-04T10:18:47Z | [
"python",
"encoding"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 819,371 | <p>I don't know of anything in the standard library, but <a href="http://www.icir.org/robin/pysubnettree/" rel="nofollow">PySubnetTree</a> is a Python library that will do subnet matching.</p>
| 1 | 2009-05-04T09:03:32Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 819,420 | <p><a href="http://code.activestate.com/recipes/66517/">This article</a> shows you can do it with <a href="http://docs.python.org/library/socket.html"><code>socket</code></a> and <a href="http://docs.python.org/library/struct.html"><code>struct</code></a> modules without too much extra effort. I added a little to the article as follows:</p>
<pre><code>import socket,struct
def makeMask(n):
"return a mask of n bits as a long integer"
return (2L<<n-1) - 1
def dottedQuadToNum(ip):
"convert decimal dotted quad string to long integer"
return struct.unpack('L',socket.inet_aton(ip))[0]
def networkMask(ip,bits):
"Convert a network address to a long integer"
return dottedQuadToNum(ip) & makeMask(bits)
def addressInNetwork(ip,net):
"Is an address in a network"
return ip & net == net
address = dottedQuadToNum("192.168.1.1")
networka = networkMask("10.0.0.0",24)
networkb = networkMask("192.168.0.0",24)
print (address,networka,networkb)
print addressInNetwork(address,networka)
print addressInNetwork(address,networkb)
</code></pre>
<p>This outputs:</p>
<pre><code>False
True
</code></pre>
<p>If you just want a single function that takes strings it would look like this:</p>
<pre><code>import socket,struct
def addressInNetwork(ip,net):
"Is an address in a network"
ipaddr = struct.unpack('L',socket.inet_aton(ip))[0]
netaddr,bits = net.split('/')
netmask = struct.unpack('L',socket.inet_aton(netaddr))[0] & ((2L<<int(bits)-1) - 1)
return ipaddr & netmask == netmask
</code></pre>
| 23 | 2009-05-04T09:21:29Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 820,124 | <p>I like to use <a href="http://pypi.python.org/pypi/netaddr">netaddr</a> for that:</p>
<pre><code>from netaddr import CIDR, IP
if IP("192.168.0.1") in CIDR("192.168.0.0/24"):
print "Yay!"
</code></pre>
<p>As arno_v pointed out in the comments, new version of netaddr does it like this:</p>
<pre><code>from netaddr import IPNetwork, IPAddress
if IPAddress("192.168.0.1") in IPNetwork("192.168.0.0/24"):
print "Yay!"
</code></pre>
| 83 | 2009-05-04T13:35:13Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 1,004,527 | <p>Using <a href="http://code.google.com/p/ipaddress-py/">ipaddress</a> (<a href="http://docs.python.org/3.3/library/ipaddress.html">in the stdlib since 3.3</a>, <a href="https://pypi.python.org/pypi/ipaddress">at PyPi for 2.6/2.7</a>):</p>
<pre><code>>>> import ipaddress
>>> ipaddress.ip_address('192.168.0.1') in ipaddress.ip_network('192.168.0.0/24')
True
</code></pre>
<hr/>
<p>If you want to evaluate a <em>lot</em> of IP addresses this way, you'll probably want to calculate the netmask upfront, like</p>
<pre><code>n = ipaddress.ip_network('192.0.0.0/16')
netw = int(n.network_address)
mask = int(n.netmask)
</code></pre>
<p>Then, for each address, calculate the binary representation with one of</p>
<pre><code>a = int(ipaddress.ip_address('192.0.43.10'))
a = struct.unpack('!I', socket.inet_pton(socket.AF_INET, '192.0.43.10'))[0]
a = struct.unpack('!I', socket.inet_aton('192.0.43.10'))[0] # IPv4 only
</code></pre>
<p>Finally, you can simply check:</p>
<pre><code>in_network = (a & mask) == netw
</code></pre>
| 51 | 2009-06-17T00:15:35Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 3,188,535 | <p>Thank you for your script!<br>
I have work quite a long on it to make everything working... So I'm sharing it here</p>
<ul>
<li>Using netaddr Class is 10 times slower than using binary conversion, so if you'd like to use it on a big list of IP, you should consider not using netaddr class</li>
<li><p>makeMask function is not working! Only working for /8,/16,/24 <br>Ex:</p>
<blockquote>
<p>bits = "21" ; socket.inet_ntoa(struct.pack('=L',(2L << int(bits)-1) - 1))<br>
'255.255.31.0' whereas it should be 255.255.248.0</p>
</blockquote>
<p>So I have used another function calcDottedNetmask(mask) from <a href="http://code.activestate.com/recipes/576483-convert-subnetmask-from-cidr-notation-to-dotdecima/" rel="nofollow">http://code.activestate.com/recipes/576483-convert-subnetmask-from-cidr-notation-to-dotdecima/</a> <br>
Ex:</p></li>
</ul>
<pre><code>
#!/usr/bin/python
>>> calcDottedNetmask(21)
>>> '255.255.248.0'
</code></pre>
<ul>
<li>Another problem is the process of matching if an IP belongs to a network! Basic Operation should be to compare (ipaddr & netmask) and (network & netmask).<br>Ex: for the time being, the function is wrong</li>
</ul>
<pre><code>
#!/usr/bin/python
>>> addressInNetwork('188.104.8.64','172.16.0.0/12')
>>>True which is completely WRONG!!
</code></pre>
<p>So my new addressInNetwork function looks-like:</p>
<pre><code>
#!/usr/bin/python
import socket,struct
def addressInNetwork(ip,net):
'''This function allows you to check if on IP belogs to a Network'''
ipaddr = struct.unpack('=L',socket.inet_aton(ip))[0]
netaddr,bits = net.split('/')
netmask = struct.unpack('=L',socket.inet_aton(calcDottedNetmask(bits)))[0]
network = struct.unpack('=L',socket.inet_aton(netaddr))[0] & netmask
return (ipaddr & netmask) == (network & netmask)
def calcDottedNetmask(mask):
bits = 0
for i in xrange(32-int(mask),32):
bits |= (1 > 24, (bits & 0xff0000) >> 16, (bits & 0xff00) >> 8 , (bits & 0xff))
</code></pre>
<p>And now, answer is right!!</p>
<pre><code>
#!/usr/bin/python
>>> addressInNetwork('188.104.8.64','172.16.0.0/12')
False
</code></pre>
<p>I hope that it will help other people, saving time for them!</p>
| 1 | 2010-07-06T17:10:58Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 4,464,961 | <p>This code is working for me on Linux x86. I haven't really given any thought to endianess issues, but I have tested it against the "ipaddr" module using over 200K IP addresses tested against 8 different network strings, and the results of ipaddr are the same as this code.</p>
<pre><code>def addressInNetwork(ip, net):
import socket,struct
ipaddr = int(''.join([ '%02x' % int(x) for x in ip.split('.') ]), 16)
netstr, bits = net.split('/')
netaddr = int(''.join([ '%02x' % int(x) for x in netstr.split('.') ]), 16)
mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
return (ipaddr & mask) == (netaddr & mask)
</code></pre>
<p>Example:</p>
<pre><code>>>> print addressInNetwork('10.9.8.7', '10.9.1.0/16')
True
>>> print addressInNetwork('10.9.8.7', '10.9.1.0/24')
False
</code></pre>
| 7 | 2010-12-16T20:16:55Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 5,467,511 | <p>Marc's code is nearly correct. A complete version of the code is -</p>
<pre><code>def addressInNetwork3(ip,net):
'''This function allows you to check if on IP belogs to a Network'''
ipaddr = struct.unpack('=L',socket.inet_aton(ip))[0]
netaddr,bits = net.split('/')
netmask = struct.unpack('=L',socket.inet_aton(calcDottedNetmask(int(bits))))[0]
network = struct.unpack('=L',socket.inet_aton(netaddr))[0] & netmask
return (ipaddr & netmask) == (network & netmask)
def calcDottedNetmask(mask):
bits = 0
for i in xrange(32-mask,32):
bits |= (1 << i)
return "%d.%d.%d.%d" % ((bits & 0xff000000) >> 24, (bits & 0xff0000) >> 16, (bits & 0xff00) >> 8 , (bits & 0xff))
</code></pre>
<p>Obviously from the same sources as above...</p>
<p>A very Important note is that the first code has a small glitch - The IP address 255.255.255.255 also shows up as a Valid IP for any subnet. I had a heck of time getting this code to work and thanks to Marc for the correct answer.</p>
| 4 | 2011-03-29T03:13:52Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 7,323,817 | <h1>from netaddr import all_matching_cidrs</h1>
<pre><code>>>> from netaddr import all_matching_cidrs
>>> all_matching_cidrs("212.11.70.34", ["192.168.0.0/24","212.11.64.0/19"] )
[IPNetwork('212.11.64.0/19')]
</code></pre>
<p>Here is the usage for this method:</p>
<pre><code>>>> help(all_matching_cidrs)
Help on function all_matching_cidrs in module netaddr.ip:
all_matching_cidrs(ip, cidrs)
Matches an IP address or subnet against a given sequence of IP addresses and subnets.
@param ip: a single IP address or subnet.
@param cidrs: a sequence of IP addresses and/or subnets.
@return: all matching IPAddress and/or IPNetwork objects from the provided
sequence, an empty list if there was no match.
</code></pre>
<p>Basically you provide an ip address as the first argument and a list of cidrs as the second argument. A list of hits are returned.</p>
| 1 | 2011-09-06T17:33:34Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 10,053,031 | <pre>
#This works properly without the weird byte by byte handling
def addressInNetwork(ip,net):
'''Is an address in a network'''
# Convert addresses to host order, so shifts actually make sense
ip = struct.unpack('>L',socket.inet_aton(ip))[0]
netaddr,bits = net.split('/')
netaddr = struct.unpack('>L',socket.inet_aton(netaddr))[0]
# Must shift left an all ones value, /32 = zero shift, /0 = 32 shift left
netmask = (0xffffffff << (32-int(bits))) & 0xffffffff
# There's no need to mask the network address, as long as its a proper network address
return (ip & netmask) == netaddr
</pre>
| 2 | 2012-04-07T08:36:07Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 10,534,496 | <p>I tried Dave Webb's solution but hit some problems:</p>
<p>Most fundamentally - a match should be checked by ANDing the IP address with the mask, then checking the result matched the Network address exactly. Not ANDing the IP address with the Network address as was done.</p>
<p>I also noticed that just ignoring the Endian behaviour assuming that consistency will save you will only work for masks on octet boundaries (/24, /16). In order to get other masks (/23, /21) working correctly I added a "greater than" to the struct commands and changed the code for creating the binary mask to start with all "1" and shift left by (32-mask). </p>
<p>Finally, I added a simple check that the network address is valid for the mask and just print a warning if it is not.</p>
<p>Here's the result:</p>
<pre><code>def addressInNetwork(ip,net):
"Is an address in a network"
ipaddr = struct.unpack('>L',socket.inet_aton(ip))[0]
netaddr,bits = net.split('/')
netmask = struct.unpack('>L',socket.inet_aton(netaddr))[0]
ipaddr_masked = ipaddr & (4294967295<<(32-int(bits))) # Logical AND of IP address and mask will equal the network address if it matches
if netmask == netmask & (4294967295<<(32-int(bits))): # Validate network address is valid for mask
return ipaddr_masked == netmask
else:
print "***WARNING*** Network",netaddr,"not valid with mask /"+bits
return ipaddr_masked == netmask
</code></pre>
| 6 | 2012-05-10T12:57:30Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 14,280,401 | <p>Relating to all of the above, I think socket.inet_aton() returns bytes in network order, so the correct way to unpack them is probably</p>
<pre><code>struct.unpack('!L', ... )
</code></pre>
| 1 | 2013-01-11T14:39:56Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 18,006,400 | <p>Here is a class I wrote for longest prefix matching:</p>
<pre><code>#!/usr/bin/env python
class Node:
def __init__(self):
self.left_child = None
self.right_child = None
self.data = "-"
def setData(self, data): self.data = data
def setLeft(self, pointer): self.left_child = pointer
def setRight(self, pointer): self.right_child = pointer
def getData(self): return self.data
def getLeft(self): return self.left_child
def getRight(self): return self.right_child
def __str__(self):
return "LC: %s RC: %s data: %s" % (self.left_child, self.right_child, self.data)
class LPMTrie:
def __init__(self):
self.nodes = [Node()]
self.curr_node_ind = 0
def addPrefix(self, prefix):
self.curr_node_ind = 0
prefix_bits = ''.join([bin(int(x)+256)[3:] for x in prefix.split('/')[0].split('.')])
prefix_length = int(prefix.split('/')[1])
for i in xrange(0, prefix_length):
if (prefix_bits[i] == '1'):
if (self.nodes[self.curr_node_ind].getRight()):
self.curr_node_ind = self.nodes[self.curr_node_ind].getRight()
else:
tmp = Node()
self.nodes[self.curr_node_ind].setRight(len(self.nodes))
tmp.setData(self.nodes[self.curr_node_ind].getData());
self.curr_node_ind = len(self.nodes)
self.nodes.append(tmp)
else:
if (self.nodes[self.curr_node_ind].getLeft()):
self.curr_node_ind = self.nodes[self.curr_node_ind].getLeft()
else:
tmp = Node()
self.nodes[self.curr_node_ind].setLeft(len(self.nodes))
tmp.setData(self.nodes[self.curr_node_ind].getData());
self.curr_node_ind = len(self.nodes)
self.nodes.append(tmp)
if i == prefix_length - 1 :
self.nodes[self.curr_node_ind].setData(prefix)
def searchPrefix(self, ip):
self.curr_node_ind = 0
ip_bits = ''.join([bin(int(x)+256)[3:] for x in ip.split('.')])
for i in xrange(0, 32):
if (ip_bits[i] == '1'):
if (self.nodes[self.curr_node_ind].getRight()):
self.curr_node_ind = self.nodes[self.curr_node_ind].getRight()
else:
return self.nodes[self.curr_node_ind].getData()
else:
if (self.nodes[self.curr_node_ind].getLeft()):
self.curr_node_ind = self.nodes[self.curr_node_ind].getLeft()
else:
return self.nodes[self.curr_node_ind].getData()
return ""
def triePrint(self):
n = 1
for i in self.nodes:
print n, ':'
print i
n += 1
</code></pre>
<p>And here is a test program:</p>
<pre><code>n=LPMTrie()
n.addPrefix('10.25.63.0/24')
n.addPrefix('10.25.63.0/16')
n.addPrefix('100.25.63.2/8')
n.addPrefix('100.25.0.3/16')
print n.searchPrefix('10.25.63.152')
print n.searchPrefix('100.25.63.200')
#10.25.63.0/24
#100.25.0.3/16
</code></pre>
| 0 | 2013-08-01T23:34:27Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 19,015,668 | <p>Not in the Standard library for 2.5, but ipaddr makes this very easy. I believe it is in 3.3 under the name ipaddress. </p>
<pre><code>import ipaddr
a = ipaddr.IPAddress('192.168.0.1')
n = ipaddr.IPNetwork('192.168.0.0/24')
#This will return True
n.Contains(a)
</code></pre>
| 2 | 2013-09-25T21:42:39Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 21,527,753 | <p><strong>previous solution have a bug in ip & net == net. Correct ip lookup is ip & netmask = net</strong></p>
<p>bugfixed code:</p>
<pre><code>import socket
import struct
def makeMask(n):
"return a mask of n bits as a long integer"
return (2L<<n-1) - 1
def dottedQuadToNum(ip):
"convert decimal dotted quad string to long integer"
return struct.unpack('L',socket.inet_aton(ip))[0]
def addressInNetwork(ip,net,netmask):
"Is an address in a network"
print "IP "+str(ip) + " NET "+str(net) + " MASK "+str(netmask)+" AND "+str(ip & netmask)
return ip & netmask == net
def humannetcheck(ip,net):
address=dottedQuadToNum(ip)
netaddr=dottedQuadToNum(net.split("/")[0])
netmask=makeMask(long(net.split("/")[1]))
return addressInNetwork(address,netaddr,netmask)
print humannetcheck("192.168.0.1","192.168.0.0/24");
print humannetcheck("192.169.0.1","192.168.0.0/24");
</code></pre>
| 1 | 2014-02-03T12:43:04Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 23,230,273 | <p>The choosen answer has a bug.</p>
<p>Following is the correct code:</p>
<pre><code>def addressInNetwork(ip, net_n_bits):
ipaddr = struct.unpack('<L', socket.inet_aton(ip))[0]
net, bits = net_n_bits.split('/')
netaddr = struct.unpack('<L', socket.inet_aton(net))[0]
netmask = ((1L << int(bits)) - 1)
return ipaddr & netmask == netaddr & netmask
</code></pre>
<p>Note: <code>ipaddr & netmask == netaddr & netmask</code> instead of <code>ipaddr & netmask == netmask</code>. </p>
<p>I also replace <code>((2L<<int(bits)-1) - 1)</code> with <code>((1L << int(bits)) - 1)</code>, as the latter seems more understandable.</p>
| 1 | 2014-04-22T21:11:31Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 29,950,808 | <p>I'm not a fan of using modules when they are not needed. This job only requires simple math, so here is my simple function to do the job:</p>
<pre><code>def ipToInt(ip):
o = map(int, ip.split('.'))
res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
return res
def isIpInSubnet(ip, ipNetwork, maskLength):
ipInt = ipToInt(ip)#my test ip, in int form
maskLengthFromRight = 32 - maskLength
ipNetworkInt = ipToInt(ipNetwork) #convert the ip network into integer form
binString = "{0:b}".format(ipNetworkInt) #convert that into into binary (string format)
chopAmount = 0 #find out how much of that int I need to cut off
for i in range(maskLengthFromRight):
if i < len(binString):
chopAmount += int(binString[len(binString)-1-i]) * 2**i
minVal = ipNetworkInt-chopAmount
maxVal = minVal+2**maskLengthFromRight -1
return minVal <= ipInt and ipInt <= maxVal
</code></pre>
<p>Then to use it:</p>
<pre><code>>>> print isIpInSubnet('66.151.97.0', '66.151.97.192',24)
True
>>> print isIpInSubnet('66.151.97.193', '66.151.97.192',29)
True
>>> print isIpInSubnet('66.151.96.0', '66.151.97.192',24)
False
>>> print isIpInSubnet('66.151.97.0', '66.151.97.192',29)
</code></pre>
<p>That's it, this is much faster than the solutions above with the included modules.</p>
| 5 | 2015-04-29T17:41:51Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 30,676,234 | <p>The accepted answer doesn't work ... which is making me angry. Mask is backwards and doesn't work with any bits that are not a simple 8 bit block (eg /24). I adapted the answer, and it works nicely.</p>
<pre><code> import socket,struct
def addressInNetwork(ip, net_n_bits):
ipaddr = struct.unpack('!L', socket.inet_aton(ip))[0]
net, bits = net_n_bits.split('/')
netaddr = struct.unpack('!L', socket.inet_aton(net))[0]
netmask = (0xFFFFFFFF >> int(bits)) ^ 0xFFFFFFFF
return ipaddr & netmask == netaddr
</code></pre>
<p>here is a function that returns a dotted binary string to help visualize the masking.. kind of like <code>ipcalc</code> output.</p>
<pre><code> def bb(i):
def s = '{:032b}'.format(i)
def return s[0:8]+"."+s[8:16]+"."+s[16:24]+"."+s[24:32]
</code></pre>
<p>eg:</p>
<p><img src="http://i.stack.imgur.com/TU1Bm.png" alt="screen shot of python"></p>
| 1 | 2015-06-05T21:38:55Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 32,127,904 | <p>From various sources above, and from my own research, this is how I got subnet and address calculation working. These pieces are enough to solve the question and other related questions.</p>
<pre><code>class iptools:
@staticmethod
def dottedQuadToNum(ip):
"convert decimal dotted quad string to long integer"
return struct.unpack('>L', socket.inet_aton(ip))[0]
@staticmethod
def numToDottedQuad(n):
"convert long int to dotted quad string"
return socket.inet_ntoa(struct.pack('>L', n))
@staticmethod
def makeNetmask(mask):
bits = 0
for i in xrange(32-int(mask), 32):
bits |= (1 << i)
return bits
@staticmethod
def ipToNetAndHost(ip, maskbits):
"returns tuple (network, host) dotted-quad addresses given"
" IP and mask size"
# (by Greg Jorgensen)
n = iptools.dottedQuadToNum(ip)
m = iptools.makeMask(maskbits)
net = n & m
host = n - mask
return iptools.numToDottedQuad(net), iptools.numToDottedQuad(host)
</code></pre>
| 0 | 2015-08-20T20:35:25Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 33,264,320 | <p>There is an API that's called SubnetTree available in python that do this job very well.
This is a simple example : </p>
<pre><code>import SubnetTree
t = SubnetTree.SubnetTree()
t.insert("10.0.1.3/32")
print("10.0.1.3" in t)
</code></pre>
<p><a href="https://www.bro.org/sphinx/components/pysubnettree/README.html" rel="nofollow">This is the link</a></p>
| 1 | 2015-10-21T16:14:38Z | [
"python",
"networking",
"ip-address"
] |
How can I check if an ip is in a network in python | 819,355 | <p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p>
<p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.</p>
| 55 | 2009-05-04T08:59:20Z | 35,459,972 | <pre><code>import socket,struct
def addressInNetwork(ip,net):
"Is an address in a network"
ipaddr = struct.unpack('!L',socket.inet_aton(ip))[0]
netaddr,bits = net.split('/')
netaddr = struct.unpack('!L',socket.inet_aton(netaddr))[0]
netmask = ((1<<(32-int(bits))) - 1)^0xffffffff
return ipaddr & netmask == netaddr & netmask
print addressInNetwork('10.10.10.110','10.10.10.128/25')
print addressInNetwork('10.10.10.110','10.10.10.0/25')
print addressInNetwork('10.10.10.110','10.20.10.128/25')
</code></pre>
<p>$ python check-subnet.py<br>
False<br>
True<br>
False</p>
| 0 | 2016-02-17T14:50:57Z | [
"python",
"networking",
"ip-address"
] |
Best way for Parsing ANSI and UTF-16LE files using Python 2/3? | 819,396 | <p>I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.</p>
<p>Is there a straightforward way to open up the files using the correct file encoding?</p>
| 0 | 2009-05-04T09:12:42Z | 819,432 | <p>Use the <a href="http://chardet.feedparser.org/" rel="nofollow">chardet</a> library to detect the encoding.</p>
| 4 | 2009-05-04T09:26:14Z | [
"python",
"encoding",
"ansi",
"utf-16"
] |
Best way for Parsing ANSI and UTF-16LE files using Python 2/3? | 819,396 | <p>I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.</p>
<p>Is there a straightforward way to open up the files using the correct file encoding?</p>
| 0 | 2009-05-04T09:12:42Z | 819,439 | <p>You can check for the <a href="http://en.wikipedia.org/wiki/Byte-order%5Fmark" rel="nofollow" title="BOM">BOM</a> at the beginning of the file to check whether it's UTF.</p>
<p>Then <a href="http://docs.python.org/library/stdtypes.html#str.decode" rel="nofollow">unicode.decode</a> accordingly (using one of the <a href="http://docs.python.org/library/codecs.html#standard-encodings" rel="nofollow">standard encodings</a>).</p>
<p><strong>EDIT</strong>
Or, maybe, try s.decode('ascii') your string (given s is the variable name). If it throws UnicodeDecodeError, then decode it as 'utf_16_le'.</p>
| 0 | 2009-05-04T09:27:06Z | [
"python",
"encoding",
"ansi",
"utf-16"
] |
Best way for Parsing ANSI and UTF-16LE files using Python 2/3? | 819,396 | <p>I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.</p>
<p>Is there a straightforward way to open up the files using the correct file encoding?</p>
| 0 | 2009-05-04T09:12:42Z | 824,579 | <p>What's in the files? If it's plain text in a Latin-based alphabet, almost every other byte the UTF-16LE files will be zero. In the windows-1252 files, on the other hand, I wouldn't expect to see any zeros at all. For example, here's <code>âHelloâ</code> in windows-1252:</p>
<pre><code>93 48 65 6C 6C 6F 94
</code></pre>
<p>...and in UTF-16LE:</p>
<pre><code>1C 20 48 00 65 00 6C 00 6C 00 6F 00 1D 20
</code></pre>
<p>Aside from the curly quotes, each character maps to the same value, with the addition of a trailing zero byte. In fact, that's true for every character in the ISO-8859-1 character set (windows-1252 extends ISO-8859-1 to add mappings for several printing charactersâlike curly quotesâto replace the control characters in the range <code>0x80..0x9F</code>).</p>
<p>If you know all the files are either windows-1252 or UTF-16LE, a quick scan for zeroes should be all you need to figure out which is which. There's a good reason why chardet is so slow and complex, but in this case I think you can get away with quick and dirty. </p>
| 0 | 2009-05-05T12:09:00Z | [
"python",
"encoding",
"ansi",
"utf-16"
] |
How do I handle exceptions when using threading and Queue? | 820,111 | <p>If I have a program that uses threading and Queue, how do I get exceptions to stop execution? Here is an example program, which is not possible to stop with ctrl-c (basically ripped from the python docs).</p>
<pre><code>from threading import Thread
from Queue import Queue
from time import sleep
def do_work(item):
sleep(0.5)
print "working" , item
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
num_worker_threads = 10
for i in range(num_worker_threads):
t = Thread(target=worker)
# t.setDaemon(True)
t.start()
for item in range(1, 10000):
q.put(item)
q.join() # block until all tasks are done
</code></pre>
| 8 | 2009-05-04T13:31:47Z | 820,121 | <p>The simplest way is to start all the worker threads as daemon threads, then just have your main loop be</p>
<pre><code>while True:
sleep(1)
</code></pre>
<p>Hitting Ctrl+C will throw an exception in your main thread, and all of the daemon threads will exit when the interpreter exits. This assumes you don't want to perform cleanup in all of those threads before they exit.</p>
<p>A more complex way is to have a global <code>stopped</code> <a href="http://docs.python.org/2/library/threading.html#event-objects" rel="nofollow">Event</a>:</p>
<pre><code>stopped = Event()
def worker():
while not stopped.is_set():
try:
item = q.get_nowait()
do_work(item)
except Empty: # import the Empty exception from the Queue module
stopped.wait(1)
</code></pre>
<p>Then your main loop can set the <code>stopped</code> Event to <code>False</code> when it gets a <code>KeyboardInterrupt</code></p>
<pre><code>try:
while not stopped.is_set():
stopped.wait(1)
except KeyboardInterrupt:
stopped.set()
</code></pre>
<p>This lets your worker threads finish what they're doing you want instead of just having every worker thread be a daemon and exit in the middle of execution. You can also do whatever cleanup you want.</p>
<p>Note that this example doesn't make use of <code>q.join()</code> - this makes things more complex, though you can still use it. If you do then your best bet is to use signal handlers instead of exceptions to detect <code>KeyboardInterrupt</code>s. For example:</p>
<pre><code>from signal import signal, SIGINT
def stop(signum, frame):
stopped.set()
signal(SIGINT, stop)
</code></pre>
<p>This lets you define what happens when you hit Ctrl+C without affecting whatever your main loop is in the middle of. So you can keep doing <code>q.join()</code> without worrying about being interrupted by a Ctrl+C. Of course, with my above examples, you don't need to be joining, but you might have some other reason for doing so.</p>
| 4 | 2009-05-04T13:34:45Z | [
"python",
"multithreading",
"exception"
] |
How do I handle exceptions when using threading and Queue? | 820,111 | <p>If I have a program that uses threading and Queue, how do I get exceptions to stop execution? Here is an example program, which is not possible to stop with ctrl-c (basically ripped from the python docs).</p>
<pre><code>from threading import Thread
from Queue import Queue
from time import sleep
def do_work(item):
sleep(0.5)
print "working" , item
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
num_worker_threads = 10
for i in range(num_worker_threads):
t = Thread(target=worker)
# t.setDaemon(True)
t.start()
for item in range(1, 10000):
q.put(item)
q.join() # block until all tasks are done
</code></pre>
| 8 | 2009-05-04T13:31:47Z | 820,247 | <p>A (possibly) offtopic note:</p>
<pre><code>(...)
for item in range(1, 10000):
q.put(item)
(...)
</code></pre>
<p>You could use xrange instead of range here (unless You use python3000). You will save some cpu and memory by doing so. More on xrange can be found <a href="http://docs.python.org/library/functions.html" rel="nofollow">here</a>.</p>
| 1 | 2009-05-04T14:03:19Z | [
"python",
"multithreading",
"exception"
] |
Render PyCairo onto PyOpenGL surface? | 820,221 | <p>I've recently started playing with pycairo - is it easy enough to render this to an pyopengl surface (e.g. on the side of a cube?)... my opengl is really non-existant so I'm not sure the best way to go about this.</p>
| 3 | 2009-05-04T13:57:53Z | 927,479 | <p>This procedure might work:</p>
<ol>
<li>Do your drawing in pycairo like normal.</li>
<li>Export the image to a file (or get a handle to it in memory).</li>
<li>Load the image into opengl texture memory.</li>
<li>Draw your cube in opengl using the texture.</li>
</ol>
<p>Steps 1&2 are in cairo, which I'm not familiar with. Steps 3&4 would be done in opengl. There's a tutorial on <a href="http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=06." rel="nofollow">drawing textured surfaces</a> at NeHe with a link to a python version at the bottom.</p>
| 0 | 2009-05-29T18:31:56Z | [
"python",
"opengl",
"cairo"
] |
How can I make a change to a module without restarting python interpreter? | 820,431 | <p>I am testing code in the python interpreter and editing in a separate window. I currently need to restart python whenever I make a change to the module I am testing.</p>
<p>Is there an easier way to do this?</p>
<p>Thanks,</p>
<p>Charlie</p>
| 1 | 2009-05-04T14:49:29Z | 820,446 | <p>The built-in function <a href="http://docs.python.org/library/functions.html#reload" rel="nofollow"><code>reload</code></a> is what you're looking for.</p>
| 10 | 2009-05-04T14:52:25Z | [
"python"
] |
How can I make a change to a module without restarting python interpreter? | 820,431 | <p>I am testing code in the python interpreter and editing in a separate window. I currently need to restart python whenever I make a change to the module I am testing.</p>
<p>Is there an easier way to do this?</p>
<p>Thanks,</p>
<p>Charlie</p>
| 1 | 2009-05-04T14:49:29Z | 820,469 | <p>It sounds like you want to reload the module, for which there is a <a href="http://docs.python.org/library/functions.html#reload" rel="nofollow">built-in function reload(module)</a>. That said, when I looked it up just now (to make sure I had my reference right, Google returned a <a href="http://pyunit.sourceforge.net/notes/reloading.html" rel="nofollow">couple of</a> <a href="http://mail.python.org/pipermail/python-list/2002-October/166262.html" rel="nofollow">discussions</a> (granted they are several years old) pointing out problems using reload(). You might want to review those if reload() causes you headaches.</p>
| 3 | 2009-05-04T14:56:22Z | [
"python"
] |
How can I make a change to a module without restarting python interpreter? | 820,431 | <p>I am testing code in the python interpreter and editing in a separate window. I currently need to restart python whenever I make a change to the module I am testing.</p>
<p>Is there an easier way to do this?</p>
<p>Thanks,</p>
<p>Charlie</p>
| 1 | 2009-05-04T14:49:29Z | 824,001 | <p>Have a look at IPython <a href="http://ipython.scipy.org" rel="nofollow">http://ipython.scipy.org</a>. It has various features that make working with Python code interactively easier.</p>
<p>Some <a href="http://ipython.scipy.org/screenshots/index.html" rel="nofollow">screenshots</a> and <a href="http://ipython.scipy.org/doc/manual/html/interactive/tutorial.html" rel="nofollow">tips</a>.</p>
| 1 | 2009-05-05T09:08:35Z | [
"python"
] |
rules for slugs and unicode | 820,496 | <p>After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles.</p>
<p>url encoding is very restrictive. See <a href="http://www.blooberry.com/indexdot/html/topics/urlencoding.htm" rel="nofollow">http://www.blooberry.com/indexdot/html/topics/urlencoding.htm</a></p>
<p>So, for example how do folks deal with for title slugs for things like</p>
<p>"Una lágrima cayó en la arena"</p>
<p>One can come up with a reasonable table for indo european languages, ie. things that can be encoded via ISO-8859-1. For example, a conversion table would translate 'á' => 'a', so the slug would be</p>
<p>"una-lagrima-cayo-en-la-arena"</p>
<p>However, I'm using unicode (in particular using UTF-8 encoding), so no guaranties about what sort code points I'm going to get (I have to prepare for things that can't be ISO-8859-1 encoded.</p>
<p>I a nushell. How do deal with this? Should I come up with a conversion table for chars in the ISO_8859-1 range (<255) and drop everything else? </p>
<p><strong>EDIT</strong>: To give a bit more context, a priori, I don't really expect to slugify data in non indo european languages, but I'd like to have a plan if I encounter such data.
A conversion table for the extended ASCII would be nice. Any pointers?</p>
<p>Also, since people are asking, I'm using python, running on Google App Engine</p>
| 10 | 2009-05-04T15:04:38Z | 822,848 | <p>If all else fails, you could use a conversion table, but there might be a better performing solution available. What server side language are you using?</p>
| 1 | 2009-05-05T01:01:42Z | [
"python",
"google-app-engine",
"url",
"unicode",
"friendly-url"
] |
rules for slugs and unicode | 820,496 | <p>After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles.</p>
<p>url encoding is very restrictive. See <a href="http://www.blooberry.com/indexdot/html/topics/urlencoding.htm" rel="nofollow">http://www.blooberry.com/indexdot/html/topics/urlencoding.htm</a></p>
<p>So, for example how do folks deal with for title slugs for things like</p>
<p>"Una lágrima cayó en la arena"</p>
<p>One can come up with a reasonable table for indo european languages, ie. things that can be encoded via ISO-8859-1. For example, a conversion table would translate 'á' => 'a', so the slug would be</p>
<p>"una-lagrima-cayo-en-la-arena"</p>
<p>However, I'm using unicode (in particular using UTF-8 encoding), so no guaranties about what sort code points I'm going to get (I have to prepare for things that can't be ISO-8859-1 encoded.</p>
<p>I a nushell. How do deal with this? Should I come up with a conversion table for chars in the ISO_8859-1 range (<255) and drop everything else? </p>
<p><strong>EDIT</strong>: To give a bit more context, a priori, I don't really expect to slugify data in non indo european languages, but I'd like to have a plan if I encounter such data.
A conversion table for the extended ASCII would be nice. Any pointers?</p>
<p>Also, since people are asking, I'm using python, running on Google App Engine</p>
| 10 | 2009-05-04T15:04:38Z | 822,917 | <p>In general this is going to depend on the language you expect to get. If your primary userbase is Japanese, dropping everything but ISO-8859-1 characters is unlikely to go over well.</p>
<p>That said, one option might be to use transliteration mode, if your character set conversion library supports it. For example, with GNU iconv, one can do:</p>
<pre><code>] echo Una lágrima cayó en la arena|iconv -f utf8 -t ascii//TRANSLIT
Una lagrima cayo en la arena
</code></pre>
<p>As you can see, the accented characters were automatically converted to something in the ASCII range. How to translate this to code will of course depend on the language you're using, but if your language is based on GNU iconv for charset conversion (and if it's on linux, it probably is), this trick can probably be applied directly by simply specifying "ascii//TRANSLIT" as the convert-to character set.</p>
<p>One thing to note with this, however, is it's only effective with characters that "look like" something in ASCII. For example:</p>
<pre><code>] echo æè¼©ã¯ç«ã§ãããååã¯ã¾ã ãªãã|iconv -f utf8 -t ascii//TRANSLIT
????????????????
</code></pre>
<p>As you can see, it's not much help for Japanese, and needs further processing afterward to remove characters not suitable for URLs.</p>
| 2 | 2009-05-05T01:27:51Z | [
"python",
"google-app-engine",
"url",
"unicode",
"friendly-url"
] |
rules for slugs and unicode | 820,496 | <p>After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles.</p>
<p>url encoding is very restrictive. See <a href="http://www.blooberry.com/indexdot/html/topics/urlencoding.htm" rel="nofollow">http://www.blooberry.com/indexdot/html/topics/urlencoding.htm</a></p>
<p>So, for example how do folks deal with for title slugs for things like</p>
<p>"Una lágrima cayó en la arena"</p>
<p>One can come up with a reasonable table for indo european languages, ie. things that can be encoded via ISO-8859-1. For example, a conversion table would translate 'á' => 'a', so the slug would be</p>
<p>"una-lagrima-cayo-en-la-arena"</p>
<p>However, I'm using unicode (in particular using UTF-8 encoding), so no guaranties about what sort code points I'm going to get (I have to prepare for things that can't be ISO-8859-1 encoded.</p>
<p>I a nushell. How do deal with this? Should I come up with a conversion table for chars in the ISO_8859-1 range (<255) and drop everything else? </p>
<p><strong>EDIT</strong>: To give a bit more context, a priori, I don't really expect to slugify data in non indo european languages, but I'd like to have a plan if I encounter such data.
A conversion table for the extended ASCII would be nice. Any pointers?</p>
<p>Also, since people are asking, I'm using python, running on Google App Engine</p>
| 10 | 2009-05-04T15:04:38Z | 824,170 | <p>I simply use utf-8 for URL paths. As long as the domain is non-IDN FF3, IE works fine with this. Google reads and displays them correctly. The <a href="http://www.ietf.org/rfc/rfc3987" rel="nofollow">IRI RFC</a> allows Unicode. Just make sure you parse the incoming urls correctly.</p>
| 4 | 2009-05-05T09:58:39Z | [
"python",
"google-app-engine",
"url",
"unicode",
"friendly-url"
] |
rules for slugs and unicode | 820,496 | <p>After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles.</p>
<p>url encoding is very restrictive. See <a href="http://www.blooberry.com/indexdot/html/topics/urlencoding.htm" rel="nofollow">http://www.blooberry.com/indexdot/html/topics/urlencoding.htm</a></p>
<p>So, for example how do folks deal with for title slugs for things like</p>
<p>"Una lágrima cayó en la arena"</p>
<p>One can come up with a reasonable table for indo european languages, ie. things that can be encoded via ISO-8859-1. For example, a conversion table would translate 'á' => 'a', so the slug would be</p>
<p>"una-lagrima-cayo-en-la-arena"</p>
<p>However, I'm using unicode (in particular using UTF-8 encoding), so no guaranties about what sort code points I'm going to get (I have to prepare for things that can't be ISO-8859-1 encoded.</p>
<p>I a nushell. How do deal with this? Should I come up with a conversion table for chars in the ISO_8859-1 range (<255) and drop everything else? </p>
<p><strong>EDIT</strong>: To give a bit more context, a priori, I don't really expect to slugify data in non indo european languages, but I'd like to have a plan if I encounter such data.
A conversion table for the extended ASCII would be nice. Any pointers?</p>
<p>Also, since people are asking, I'm using python, running on Google App Engine</p>
| 10 | 2009-05-04T15:04:38Z | 824,829 | <p>Nearly-complete transliteration table (for latin, greek and cyrillic character sets) can be found in <a href="http://trac.django-fr.org/browser/site/trunk/project/links/slughifi.py?rev=47">slughifi library</a>. It is geared towards Django, but can be easily modified to fit general needs (I use it with Werkzeug-based app on AppEngine).</p>
| 8 | 2009-05-05T13:21:26Z | [
"python",
"google-app-engine",
"url",
"unicode",
"friendly-url"
] |
python, __slots__, and "attribute is read-only" | 820,671 | <p>I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:</p>
<pre><code>class MyClass( object ) :
m = None # my attribute
__slots__ = ( "m" ) # ensure that object has no _m etc
a = MyClass() # create one
a.m = "?" # here is a PROBLEM
</code></pre>
<p>But after running this simple code, I get a very strange error:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 8, in <module>
a.m = "?"
AttributeError: 'test' object attribute 'm' is read-only
</code></pre>
<p>Is there any wise programmer who can spare a bit of their time and enlighten me about "read-only" errors?</p>
| 15 | 2009-05-04T15:50:36Z | 820,710 | <p><code>__slots__</code> works with instance variables, whereas what you have there is a class variable. This is how you should be doing it:</p>
<pre><code>class MyClass( object ) :
__slots__ = ( "m", )
def __init__(self):
self.m = None
a = MyClass()
a.m = "?" # No error
</code></pre>
| 7 | 2009-05-04T16:02:54Z | [
"python",
"exception",
"descriptor",
"readonlyattribute"
] |
python, __slots__, and "attribute is read-only" | 820,671 | <p>I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:</p>
<pre><code>class MyClass( object ) :
m = None # my attribute
__slots__ = ( "m" ) # ensure that object has no _m etc
a = MyClass() # create one
a.m = "?" # here is a PROBLEM
</code></pre>
<p>But after running this simple code, I get a very strange error:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 8, in <module>
a.m = "?"
AttributeError: 'test' object attribute 'm' is read-only
</code></pre>
<p>Is there any wise programmer who can spare a bit of their time and enlighten me about "read-only" errors?</p>
| 15 | 2009-05-04T15:50:36Z | 820,730 | <p>When you declare instance variables using <code>__slots__</code>, Python creates a <a href="http://www.python.org/doc/2.5.1/ref/descriptors.html#descriptors">descriptor object</a> as a class variable with the same name. In your case, this descriptor is overwritten by the class variable <code>m</code> that you are defining at the following line:</p>
<pre><code> m = None # my attribute
</code></pre>
<p>Here is what you need to do: Do not define a class variable called <code>m</code>, and initialize the instance variable <code>m</code> in the <code>__init__</code> method.</p>
<pre><code>class MyClass(object):
__slots__ = ("m",)
def __init__(self):
self.m = None
a = MyClass()
a.m = "?"
</code></pre>
<p>As a side note, tuples with single elements need a comma after the element. Both work in your code because <code>__slots__</code> accepts a single string or an iterable/sequence of strings. In general, to define a tuple containing the element <code>1</code>, use <code>(1,)</code> or <code>1,</code> and not <code>(1)</code>.</p>
| 34 | 2009-05-04T16:07:51Z | [
"python",
"exception",
"descriptor",
"readonlyattribute"
] |
python, __slots__, and "attribute is read-only" | 820,671 | <p>I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:</p>
<pre><code>class MyClass( object ) :
m = None # my attribute
__slots__ = ( "m" ) # ensure that object has no _m etc
a = MyClass() # create one
a.m = "?" # here is a PROBLEM
</code></pre>
<p>But after running this simple code, I get a very strange error:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 8, in <module>
a.m = "?"
AttributeError: 'test' object attribute 'm' is read-only
</code></pre>
<p>Is there any wise programmer who can spare a bit of their time and enlighten me about "read-only" errors?</p>
| 15 | 2009-05-04T15:50:36Z | 820,968 | <p>Consider this.</p>
<pre><code>class SuperSafe( object ):
allowed= ( "this", "that" )
def __init__( self ):
self.this= None
self.that= None
def __setattr__( self, attr, value ):
if attr not in self.allowed:
raise Exception( "No such attribute: %s" % (attr,) )
super( SuperSafe, self ).__setattr__( attr, value )
</code></pre>
<p>A better approach is to use unit tests for this kind of checking. This is a fair amount of run-time overhead.</p>
| 4 | 2009-05-04T17:06:55Z | [
"python",
"exception",
"descriptor",
"readonlyattribute"
] |
python, __slots__, and "attribute is read-only" | 820,671 | <p>I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:</p>
<pre><code>class MyClass( object ) :
m = None # my attribute
__slots__ = ( "m" ) # ensure that object has no _m etc
a = MyClass() # create one
a.m = "?" # here is a PROBLEM
</code></pre>
<p>But after running this simple code, I get a very strange error:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 8, in <module>
a.m = "?"
AttributeError: 'test' object attribute 'm' is read-only
</code></pre>
<p>Is there any wise programmer who can spare a bit of their time and enlighten me about "read-only" errors?</p>
| 15 | 2009-05-04T15:50:36Z | 821,773 | <p>You are completely misusing <code>__slots__</code>. It prevents the creation of <code>__dict__</code> for the instances. This only makes sense if you run into memory problems with many small objects, because getting rid of <code>__dict__</code> can reduce the footprint. This is a hardcore optimization that is not needed in 99.9% of all cases.</p>
<p>If you need the kind of safety you described then Python really is the wrong language. Better use something strict like Java (instead of trying to write Java in Python).</p>
<p>If you couldn't figure out yourself why the class attributes caused these problems in your code then maybe you should think twice about introducing language hacks like this. It would probably be wiser to become more familiar with the language first.</p>
<p>Just for completeness, here is the <a href="https://docs.python.org/2/reference/datamodel.html#slots" rel="nofollow">documentation link for slots</a>.</p>
| 13 | 2009-05-04T20:05:24Z | [
"python",
"exception",
"descriptor",
"readonlyattribute"
] |
python, __slots__, and "attribute is read-only" | 820,671 | <p>I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:</p>
<pre><code>class MyClass( object ) :
m = None # my attribute
__slots__ = ( "m" ) # ensure that object has no _m etc
a = MyClass() # create one
a.m = "?" # here is a PROBLEM
</code></pre>
<p>But after running this simple code, I get a very strange error:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 8, in <module>
a.m = "?"
AttributeError: 'test' object attribute 'm' is read-only
</code></pre>
<p>Is there any wise programmer who can spare a bit of their time and enlighten me about "read-only" errors?</p>
| 15 | 2009-05-04T15:50:36Z | 26,469,796 | <pre><code>class MyClass( object ) :
m = None # my attribute
</code></pre>
<p>The <code>m</code> here is the class attributes, rather than the instance attribute. You need to connect it with your instance by self in <code>__init__</code>.</p>
| 0 | 2014-10-20T15:51:31Z | [
"python",
"exception",
"descriptor",
"readonlyattribute"
] |
Why is Maya 2009 TreeView control giving a syntax error on drag? | 820,697 | <p>I'm using the TreeView control in Maya 2009 but I'm getting a syntax error on drag and drop. My code is as follows (simplified for brevity):</p>
<pre><code> class View(event.Dispatcher):
def __init__(self):
self.window = cmds.window()
tree_view = cmds.treeView(
numberOfButtons=1,
allowReparenting=True,
dragAndDropCommand=self.tree_view_onDrag
)
cmds.showWindow(self.window)
def tree_view_onDrag(self, dropped_items, old_parents, old_indexes, new_parent, new_indexes, item_before, item_after, *args):
print "worked"
</code></pre>
<p>When I drag and drop and element I get the following command is executed in the console:</p>
<pre><code><bound method View.tree_view_onDrag of {"layer 3"} {""} {1} "layer 1" {0} "" "layer 2";
</code></pre>
<p>And get the following error:</p>
<pre><code>// Error: <bound method View.tree_view_onDrag of {"layer 3"} {""} {1} "layer 1" {0}⬠//
// Error: Line 1.1: Syntax error //
</code></pre>
<p><strong>EDIT:</strong> It turns out that the issues I was having were due to the treeView still implementing MEL function calls on most of its event callbacks. The errors above are being thrown by the MEL interpreter as it attempts to feed arguments to a command name.</p>
| 1 | 2009-05-04T15:59:26Z | 821,857 | <p>See <a href="http://download.autodesk.com/us/maya/2009help/CommandsPython/treeView.html" rel="nofollow">http://download.autodesk.com/us/maya/2009help/CommandsPython/treeView.html</a>: dragAndDropCommand is a STRING -- you're passing a bound method, Maya's using its repr. I'm not sure, but I suspect that string should name a top-level (module-level) function, not a bound method.</p>
| 1 | 2009-05-04T20:21:38Z | [
"python",
"treeview",
"syntax-error",
"maya"
] |
Why is Maya 2009 TreeView control giving a syntax error on drag? | 820,697 | <p>I'm using the TreeView control in Maya 2009 but I'm getting a syntax error on drag and drop. My code is as follows (simplified for brevity):</p>
<pre><code> class View(event.Dispatcher):
def __init__(self):
self.window = cmds.window()
tree_view = cmds.treeView(
numberOfButtons=1,
allowReparenting=True,
dragAndDropCommand=self.tree_view_onDrag
)
cmds.showWindow(self.window)
def tree_view_onDrag(self, dropped_items, old_parents, old_indexes, new_parent, new_indexes, item_before, item_after, *args):
print "worked"
</code></pre>
<p>When I drag and drop and element I get the following command is executed in the console:</p>
<pre><code><bound method View.tree_view_onDrag of {"layer 3"} {""} {1} "layer 1" {0} "" "layer 2";
</code></pre>
<p>And get the following error:</p>
<pre><code>// Error: <bound method View.tree_view_onDrag of {"layer 3"} {""} {1} "layer 1" {0}⬠//
// Error: Line 1.1: Syntax error //
</code></pre>
<p><strong>EDIT:</strong> It turns out that the issues I was having were due to the treeView still implementing MEL function calls on most of its event callbacks. The errors above are being thrown by the MEL interpreter as it attempts to feed arguments to a command name.</p>
| 1 | 2009-05-04T15:59:26Z | 1,704,535 | <p>As of Maya 2010 the treeView widget appears to still require a string name of a mel procedure to be used for some of its callbacks, but not for others. For example, the dragCallback and dropCallback do work as expected, but the selectCommand and others don't. Many other widgets do accept a python function for their callbacks. Even though the docs list the arguments for some treeView callbacks as strings, it isn't stated that the string must be a mel procedure name, and it is certainly inconsistent.</p>
| 0 | 2009-11-09T22:57:03Z | [
"python",
"treeview",
"syntax-error",
"maya"
] |
How to bestow string-ness on my class? | 820,742 | <p>I want a string with one additional attribute, let's say whether to print it in red or green.</p>
<p>Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.</p>
<p>Can multiple inheritence help? I never used that.</p>
<p>Inheriting only object and using self.value=str means I have to implement all string-ness messages (like strip) myself.</p>
<p>Or is there a way to forward them, like Ruby's missing_method?</p>
<p>I think using a class-level dictionary indexed by instance to store the color could work. Too ugly?</p>
| 6 | 2009-05-04T16:11:14Z | 820,750 | <p>Perhaps a custom class that <strong>contains</strong> a string would be a better approach. Do you really need to pass all string methods through to the underlying string? Why not expose the string via a property and allow consumers of the class to do whatever they wish to it?</p>
| 2 | 2009-05-04T16:13:22Z | [
"python",
"string",
"multiple-inheritance",
"immutability"
] |
How to bestow string-ness on my class? | 820,742 | <p>I want a string with one additional attribute, let's say whether to print it in red or green.</p>
<p>Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.</p>
<p>Can multiple inheritence help? I never used that.</p>
<p>Inheriting only object and using self.value=str means I have to implement all string-ness messages (like strip) myself.</p>
<p>Or is there a way to forward them, like Ruby's missing_method?</p>
<p>I think using a class-level dictionary indexed by instance to store the color could work. Too ugly?</p>
| 6 | 2009-05-04T16:11:14Z | 820,767 | <p>You need all of string's methods, so extend string and add your extra details. So what if string is immutable? Just make your class immutable, too. Then you're creating new objects anyway so you won't accidentally mess up thinking that it's a mutable object.</p>
<p>Or, if Python has one, extend a mutable variant of string. I'm not familiar enough with Python to know if such a structure exists.</p>
| 0 | 2009-05-04T16:17:39Z | [
"python",
"string",
"multiple-inheritance",
"immutability"
] |
How to bestow string-ness on my class? | 820,742 | <p>I want a string with one additional attribute, let's say whether to print it in red or green.</p>
<p>Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.</p>
<p>Can multiple inheritence help? I never used that.</p>
<p>Inheriting only object and using self.value=str means I have to implement all string-ness messages (like strip) myself.</p>
<p>Or is there a way to forward them, like Ruby's missing_method?</p>
<p>I think using a class-level dictionary indexed by instance to store the color could work. Too ugly?</p>
| 6 | 2009-05-04T16:11:14Z | 820,849 | <p>str can be inherited unless you are using a very old python version, for example :</p>
<pre><code>>>> class A(str):
... def __new__(cls, color, *args, **kwargs):
... newobj = str.__new__(cls, *args, **kwargs)
... newobj.color = color
... return newobj
>>> a = A("#fff", "horse")
>>> a.color
'#fff'
>>> a
'horse'
>>> a.startswith("h")
True
</code></pre>
| 5 | 2009-05-04T16:38:51Z | [
"python",
"string",
"multiple-inheritance",
"immutability"
] |
How to bestow string-ness on my class? | 820,742 | <p>I want a string with one additional attribute, let's say whether to print it in red or green.</p>
<p>Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.</p>
<p>Can multiple inheritence help? I never used that.</p>
<p>Inheriting only object and using self.value=str means I have to implement all string-ness messages (like strip) myself.</p>
<p>Or is there a way to forward them, like Ruby's missing_method?</p>
<p>I think using a class-level dictionary indexed by instance to store the color could work. Too ugly?</p>
| 6 | 2009-05-04T16:11:14Z | 820,852 | <pre><code>import UserString
class mystr(UserString.MutableString):
...
</code></pre>
<p>It's generally best to use immutable strings & subclasses thereof, but if you need a mutable one this is the simplest way to get it.</p>
| 2 | 2009-05-04T16:39:07Z | [
"python",
"string",
"multiple-inheritance",
"immutability"
] |
How to bestow string-ness on my class? | 820,742 | <p>I want a string with one additional attribute, let's say whether to print it in red or green.</p>
<p>Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.</p>
<p>Can multiple inheritence help? I never used that.</p>
<p>Inheriting only object and using self.value=str means I have to implement all string-ness messages (like strip) myself.</p>
<p>Or is there a way to forward them, like Ruby's missing_method?</p>
<p>I think using a class-level dictionary indexed by instance to store the color could work. Too ugly?</p>
| 6 | 2009-05-04T16:11:14Z | 11,801,438 | <p>You could try using the <code>stringlike</code> module in <a href="http://pypi.python.org/pypi/stringlike" rel="nofollow">PyPI</a>. Here's <a href="http://developer.covenanteyes.com/stringlike-in-python/" rel="nofollow">an example</a>.</p>
| 0 | 2012-08-03T18:38:05Z | [
"python",
"string",
"multiple-inheritance",
"immutability"
] |
SyntaxError in finally (Django) | 820,778 | <p>I'm using Django, and I have the following error:</p>
<blockquote>
<p>Exception Type: SyntaxError
Exception Value: invalid syntax (views.py, <strong>line 115</strong>)</p>
</blockquote>
<p>My viws.py code looks like this:</p>
<pre><code>def myview(request):
try:
[...]
except MyExceptionClass, e:
[...]
finally:
render_to_response('template.html', {}, context_instance = RequestContext(request))
</code></pre>
<p>Where MyExceptionClass is a class extending Exception, and <strong>line 115</strong> is the 'finally' clause line. If I remove finally clause, (lines 115-116), works fine. Any idea?</p>
<p>Thanks a lot!</p>
| 4 | 2009-05-04T16:20:23Z | 820,792 | <p>In Python 3, should be:</p>
<pre><code>except MyExceptionClass as e:
[....]
</code></pre>
<p>In your case, this is not the case.</p>
| 0 | 2009-05-04T16:24:39Z | [
"python",
"django"
] |
SyntaxError in finally (Django) | 820,778 | <p>I'm using Django, and I have the following error:</p>
<blockquote>
<p>Exception Type: SyntaxError
Exception Value: invalid syntax (views.py, <strong>line 115</strong>)</p>
</blockquote>
<p>My viws.py code looks like this:</p>
<pre><code>def myview(request):
try:
[...]
except MyExceptionClass, e:
[...]
finally:
render_to_response('template.html', {}, context_instance = RequestContext(request))
</code></pre>
<p>Where MyExceptionClass is a class extending Exception, and <strong>line 115</strong> is the 'finally' clause line. If I remove finally clause, (lines 115-116), works fine. Any idea?</p>
<p>Thanks a lot!</p>
| 4 | 2009-05-04T16:20:23Z | 820,799 | <p>What version of python are you using? Prior to 2.5 you can't have both an except clause and a finally clause in the same try block.</p>
<p>You can work around this by nesting try blocks.</p>
<pre><code>def myview(request):
try:
try:
[...]
except MyExceptionClass, e:
[...]
finally:
render_to_response(
'template.html', {}, context_instance = RequestContext(request)
)
</code></pre>
| 13 | 2009-05-04T16:25:56Z | [
"python",
"django"
] |
SyntaxError in finally (Django) | 820,778 | <p>I'm using Django, and I have the following error:</p>
<blockquote>
<p>Exception Type: SyntaxError
Exception Value: invalid syntax (views.py, <strong>line 115</strong>)</p>
</blockquote>
<p>My viws.py code looks like this:</p>
<pre><code>def myview(request):
try:
[...]
except MyExceptionClass, e:
[...]
finally:
render_to_response('template.html', {}, context_instance = RequestContext(request))
</code></pre>
<p>Where MyExceptionClass is a class extending Exception, and <strong>line 115</strong> is the 'finally' clause line. If I remove finally clause, (lines 115-116), works fine. Any idea?</p>
<p>Thanks a lot!</p>
| 4 | 2009-05-04T16:20:23Z | 820,813 | <p>Nadia is right, so if you're stuck with Python 2.4 or earlier, use <em>two</em> try blocks:</p>
<pre><code>try:
try:
[...]
except MyExceptionClass, e:
[...]
finally:
render_to_response(...)
</code></pre>
| 2 | 2009-05-04T16:31:20Z | [
"python",
"django"
] |
Where can I find some "hello world"-simple Beautiful Soup examples? | 821,173 | <p>I'd like to do a very simple replacement using Beautiful Soup. Let's say I want to visit all A tags in a page and append "?foo" to their href. Can someone post or link to an example of how to do something simple like that?</p>
| 7 | 2009-05-04T17:53:51Z | 821,238 | <pre><code>from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('''
<html>
<head><title>Testing</title></head>
<body>
<a href="http://foo.com/">foo</a>
<a href="http://bar.com/bar">Bar</a>
</body>
</html>''')
for link in soup.findAll('a'): # find all links
link['href'] = link['href'] + '?foo'
print soup
</code></pre>
<p>That prints:</p>
<pre><code><html>
<head><title>Testing</title></head>
<body>
<a href="http://foo.com/?foo">foo</a>
<a href="http://bar.com/bar?foo">Bar</a>
</body>
</html>
</code></pre>
<p>The <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html">documentation</a> also has some <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Changing%20attribute%20values">examples for changing attributes</a>. It is an extensive tutorial that covers all common aspects of BeautifulSoup. I don't know what is missing from the documentation, maybe you should clarify.</p>
| 14 | 2009-05-04T18:09:56Z | [
"python",
"beautifulsoup"
] |
Where can I find some "hello world"-simple Beautiful Soup examples? | 821,173 | <p>I'd like to do a very simple replacement using Beautiful Soup. Let's say I want to visit all A tags in a page and append "?foo" to their href. Can someone post or link to an example of how to do something simple like that?</p>
| 7 | 2009-05-04T17:53:51Z | 2,264,956 | <p>my example:</p>
<pre><code>HEADERS = {"User-Agent" : "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5",
"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language" : "ru,en-us;q=0.7,en;q=0.3",
"Accept-Charset" : "windows-1251,utf-8;q=0.7,*;q=0.7",
"Accept-Encoding" : "identity, *;q=0",
"Connection" : "Keep-Alive"}
PROXY=None
timeout=60
def parse_manuf_page_about(page_str_about):
slovar={}
global timeout
socket.setdefaulttimeout(timeout)
if PROXY is not None:
proxy_handler = urllib2.ProxyHandler( { "http": "http://"+PROXY+"/" } )
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)
page_request = urllib2.Request(url=page_str_about, headers=HEADERS)
try:
#print "Page reading ... %s" %page_str
page_zapr = urllib2.urlopen(url=page_request)
page=page_zapr.read()
except Exception ,error:
print str(error)
res=False
return res,slovar
soup = BeautifulSoup(page)
select_pod=soup.findAll('div', {"class":"win aboutUs"})
promeg= select_pod[0].findAll("p")[0]
zerro_br= promeg.findAll(text=True)
Company_Info=" ".join(zerro_br).strip(" \t\n")
select =soup.findAll('div', {"class":"win"})
cells_tabl= select[0].findAll("tr")
for yach in cells_tabl:
text_zag=yach.findAll("th")
for zn_yach in text_zag:
if len(zn_yach)>0:
txt_zn_yach="".join(zn_yach.findAll(text=True)).strip(" \t\n")
else:
txt_zn_yach= zn_yach.contents[0].strip(" \t\n")
#print txt_zn_yach
text_znach_td=yach.findAll("td")
for zn_yach_td in text_znach_td:
if len(zn_yach_td)>0:
txt_zn_yach_td="".join(zn_yach_td.findAll(text=True)).strip(" \t\n")
else:
txt_zn_yach_td= zn_yach.contents[0].strip(" \t\n")
#print txt_zn_yach_td
# Ðелаем Ð·Ð°Ð¼ÐµÐ½Ñ Ð½ÐµÑгоднÑÑ
Ñимволов / Replase browsers char
if "&nbsp" in txt_zn_yach_td:
while txt_zn_yach_td.find("nbsp;")>0:
pos_gavna=txt_zn_yach_td.find("&nbsp;")
txt_zn_yach_td=txt_zn_yach_td[:pos_gavna]+txt_zn_yach_td[pos_gavna+6:]
if "&quot" in txt_zn_yach_td:
while txt_zn_yach_td.find("quot;")>0:
pos_gavna=txt_zn_yach_td.find("&quot;")
txt_zn_yach_td=txt_zn_yach_td[:pos_gavna]+'"'+txt_zn_yach_td[pos_gavna+6:]
if "&amp;" in txt_zn_yach_td:
while txt_zn_yach_td.find("&amp;")>0:
pos_gavna=txt_zn_yach_td.find("&amp;")
txt_zn_yach_td=txt_zn_yach_td[:pos_gavna]+'&'+txt_zn_yach_td[pos_gavna+6:]
slovar[str(txt_zn_yach)]=txt_zn_yach_td
slovar["Company_Info"]=Company_Info
# ÑазбиÑаем нижнÑÑ ÑаблиÑÑ Ñ ÐºÐ¾Ð½ÑакÑом и вÑÑаÑкиваем оÑÑÑда Ð¸Ð¼Ñ ÐºÐ¾Ð½ÑакÑа | get name contacts
select_contact=soup.findAll('a', {"class":"member-name"})
for contact_person in select_contact:
slovar["Contact_Person"]= contact_person.contents[0]
# полÑÑаем ÑÑаÑÑÑ Ð³Ð¾Ð»Ð´ паÑÑнеÑа по налиÑÐ¸Ñ ÑаблиÑки в левом веÑÑ
нем ÑÐ³Ð»Ñ | get Gold status
select_gold_part=soup.findAll('a', {"class":"memberLogo"})
if len(select_gold_part)==0:
slovar["Gold member"]="N"
else:
slovar["Gold member"]="Y"
res=True
return res,slovar
</code></pre>
<p>This code parsing one page of manufactury on Alibaba.com. You can see it page - <a href="http://xmxinhuafeng.en.alibaba.com/aboutus.html" rel="nofollow">http://xmxinhuafeng.en.alibaba.com/aboutus.html</a></p>
| 1 | 2010-02-15T09:35:59Z | [
"python",
"beautifulsoup"
] |
SQL TOP 1 analog for lists in Python | 821,416 | <p>Here is an example of my input csv file:</p>
<pre><code>...
0.7,0.5,0.35,14.4,0.521838919218
0.7,0.5,0.35,14.4,0.521893472678
0.7,0.5,0.35,14.4,0.521948026139
0.7,0.5,0.35,14.4,0.522002579599
...
</code></pre>
<p>I need to select the top row where the last float > random number. My current implementation is very slow (script has a lot of iterations of this and outer cycles):</p>
<pre><code>for line in foo:
if float(line[-1]) > random.random():
res = line
break
...
</code></pre>
<p>How can I make this better and faster?</p>
<h3>EDIT:</h3>
<p>I was advised to use bisect for this task, but I don't know how to do it.</p>
| 1 | 2009-05-04T18:59:51Z | 821,464 | <p>The fastest approach is to use bisect (assuming the float list is ordered). You can do it like this:</p>
<pre><code>import bisect
float_list = [line[-1] for line in foo]
index = bisect.bisect(float_list, random.random())
if index < len(float_list)
result = foo[index]
else:
result = None # None exists
</code></pre>
<p>The float list has to be ordered for this to work.</p>
| 3 | 2009-05-04T19:07:34Z | [
"python",
"tsql"
] |
SQL TOP 1 analog for lists in Python | 821,416 | <p>Here is an example of my input csv file:</p>
<pre><code>...
0.7,0.5,0.35,14.4,0.521838919218
0.7,0.5,0.35,14.4,0.521893472678
0.7,0.5,0.35,14.4,0.521948026139
0.7,0.5,0.35,14.4,0.522002579599
...
</code></pre>
<p>I need to select the top row where the last float > random number. My current implementation is very slow (script has a lot of iterations of this and outer cycles):</p>
<pre><code>for line in foo:
if float(line[-1]) > random.random():
res = line
break
...
</code></pre>
<p>How can I make this better and faster?</p>
<h3>EDIT:</h3>
<p>I was advised to use bisect for this task, but I don't know how to do it.</p>
| 1 | 2009-05-04T18:59:51Z | 821,529 | <p>You might actually be able to use the appropriate SQL command if you <a href="http://www.sqlite.org/cvstrac/wiki?p=ImportingFiles" rel="nofollow">import the CSV file into SQLite</a>. Python has a <a href="http://docs.python.org/library/sqlite3.html" rel="nofollow">built-in sqlite library</a> you can use to query the database.</p>
| 1 | 2009-05-04T19:19:46Z | [
"python",
"tsql"
] |
what python feature is illustrated in this code? | 821,855 | <p>I read Storm ORM's tutorial at <a href="https://storm.canonical.com/Tutorial" rel="nofollow">https://storm.canonical.com/Tutorial</a>, and I stumbled upon the following piece of code :</p>
<pre><code>
store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie")
</code></pre>
<p>I'm not sure that the second argument of the <b>find</b> method will be evaluated to True/False. I think it will be interpreted as a lambda. If that is true, how can I achieve the same effect in my functions ?</p>
| 5 | 2009-05-04T20:21:03Z | 821,900 | <p>since I'm a Java programmer... I'm guessing...
it is operator overloading? Person.name == is an operator overloaded that instead do comparison... it produces a SQL query</p>
<p>my 0.02$</p>
| 0 | 2009-05-04T20:28:12Z | [
"python",
"language-features"
] |
what python feature is illustrated in this code? | 821,855 | <p>I read Storm ORM's tutorial at <a href="https://storm.canonical.com/Tutorial" rel="nofollow">https://storm.canonical.com/Tutorial</a>, and I stumbled upon the following piece of code :</p>
<pre><code>
store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie")
</code></pre>
<p>I'm not sure that the second argument of the <b>find</b> method will be evaluated to True/False. I think it will be interpreted as a lambda. If that is true, how can I achieve the same effect in my functions ?</p>
| 5 | 2009-05-04T20:21:03Z | 821,912 | <p>It does not look like a python lambda to me. I did not read the code for Storm but Miles is probably right in that it uses a lazy evaluation schema.</p>
<p>To learn more about python lambda functions read the excellent <a href="http://www.diveintopython.org/power%5Fof%5Fintrospection/lambda%5Ffunctions.html" rel="nofollow">chapter</a> of <a href="http://www.diveintopython.org/index.html" rel="nofollow">Dive Into Python</a>.</p>
| 1 | 2009-05-04T20:31:02Z | [
"python",
"language-features"
] |
what python feature is illustrated in this code? | 821,855 | <p>I read Storm ORM's tutorial at <a href="https://storm.canonical.com/Tutorial" rel="nofollow">https://storm.canonical.com/Tutorial</a>, and I stumbled upon the following piece of code :</p>
<pre><code>
store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie")
</code></pre>
<p>I'm not sure that the second argument of the <b>find</b> method will be evaluated to True/False. I think it will be interpreted as a lambda. If that is true, how can I achieve the same effect in my functions ?</p>
| 5 | 2009-05-04T20:21:03Z | 821,926 | <p><code>Person.name</code> has a overloaded <code>__eq__</code> method that returns not a boolean value but an object that stores both sides of the expression; that object can be examined by the <code>find()</code> method to obtain the attribute and value that it will use for filtering. I would describe this as a type of lazy evaluation pattern.</p>
<p>In Storm, it is implemented with the <a href="http://bazaar.launchpad.net/%7Estorm/storm/trunk/annotate/head%3A/storm/expr.py#L380" rel="nofollow"><code>Comparable</code> object</a>.</p>
| 22 | 2009-05-04T20:33:48Z | [
"python",
"language-features"
] |
what python feature is illustrated in this code? | 821,855 | <p>I read Storm ORM's tutorial at <a href="https://storm.canonical.com/Tutorial" rel="nofollow">https://storm.canonical.com/Tutorial</a>, and I stumbled upon the following piece of code :</p>
<pre><code>
store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie")
</code></pre>
<p>I'm not sure that the second argument of the <b>find</b> method will be evaluated to True/False. I think it will be interpreted as a lambda. If that is true, how can I achieve the same effect in my functions ?</p>
| 5 | 2009-05-04T20:21:03Z | 821,941 | <p>The magic is in the Person.name property, which results in a type that overloads <code>__eq__</code> (&c) to return non-bools. Storm's sources are online for you to browse (and CAUTIOUSLY imitate;-) at <a href="http://bazaar.launchpad.net/~storm/storm/trunk/files/head%3A/storm/" rel="nofollow">http://bazaar.launchpad.net/~storm/storm/trunk/files/head%3A/storm/</a> -- as you'll see, they don't go light on the "black magic";-)</p>
| 8 | 2009-05-04T20:36:00Z | [
"python",
"language-features"
] |
what python feature is illustrated in this code? | 821,855 | <p>I read Storm ORM's tutorial at <a href="https://storm.canonical.com/Tutorial" rel="nofollow">https://storm.canonical.com/Tutorial</a>, and I stumbled upon the following piece of code :</p>
<pre><code>
store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie")
</code></pre>
<p>I'm not sure that the second argument of the <b>find</b> method will be evaluated to True/False. I think it will be interpreted as a lambda. If that is true, how can I achieve the same effect in my functions ?</p>
| 5 | 2009-05-04T20:21:03Z | 822,115 | <p><code>Person.name</code> is an instance of some type with a custom <code>__eq__</code> method. While <code>__eq__</code> normally returns a boolean(ish) value, it can actually return whatever you want, including a lambda. See <a href="http://docs.python.org/reference/datamodel.html#special-method-names" rel="nofollow">Python special method names</a> for more on this and related methods.</p>
<p>Probably the most confusing/misleading part of this (especially if you're used to other OO languages like Java) is that <code>Person.name</code> and <code>person.name</code> (where <code>person</code> is an instance of <code>Person</code>) don't have to have any relationship to each other. For example:</p>
<pre><code>class Person(object):
name = "name of class"
def __init__(self):
self.name = "name of instance"
person = Person()
print Person.name
print person.name
</code></pre>
<p>This will print:</p>
<blockquote>
<pre><code>name of class
name of instance
</code></pre>
</blockquote>
<p>Note that the class property is just set in the class body, while the instance property is set in the <code>__init__</code> method.</p>
<p>In your case, you'd set <code>Person.name</code> to the object with the custom <code>__eq__</code> method that returns a lambda, something like this:</p>
<pre><code>class LambdaThingy(object):
def __init__(self, attrname):
self.__attrname = attrname
def __eq__(self, other):
return lambda x: getattr(x, self.__attrname) == other
class Person(object):
name = LambdaThingy('name')
def __init__(self, name):
self.name = name
equals_fred = Person.name == "Fred"
equals_barney = Person.name == "Barney"
fred = Person("Fred")
print equals_fred(fred)
print equals_barney(fred)
</code></pre>
<p>This prints:</p>
<pre><code>True
False
</code></pre>
<p>This is certainly skirting the edge of being "too clever", so I'd be very cautious about using this in production code. An explicit lambda would probably be a lot clearer to future maintainers, even if it is a bit more verbose.</p>
| 9 | 2009-05-04T21:19:20Z | [
"python",
"language-features"
] |
Python sockets buffering | 822,001 | <p>Let's say I want to read a line from a socket, using the standard <code>socket</code> module:</p>
<pre><code>def read_line(s):
ret = ''
while True:
c = s.recv(1)
if c == '\n' or c == '':
break
else:
ret += c
return ret
</code></pre>
<p>What exactly happens in <code>s.recv(1)</code>? Will it issue a system call each time? I guess I should add some buffering, anyway:</p>
<blockquote>
<p>For best match with hardware and network realities, the value of <em>bufsize</em> should be a relatively small power of 2, for example, 4096.</p>
</blockquote>
<p><a href="http://docs.python.org/library/socket.html#socket.socket.recv">http://docs.python.org/library/socket.html#socket.socket.recv</a></p>
<p>But it doesn't seem easy to write efficient and thread-safe buffering. What if I use <code>file.readline()</code>?</p>
<pre><code># does this work well, is it efficiently buffered?
s.makefile().readline()
</code></pre>
| 13 | 2009-05-04T20:50:59Z | 822,057 | <p>The <code>recv()</code> call is handled directly by calling the C library function.</p>
<p>It will block waiting for the socket to have data. In reality it will just let the <code>recv()</code> system call block.</p>
<p><code>file.readline()</code> is an efficient buffered implementation. It is not threadsafe, because it presumes it's the only one reading the file. (For example by buffering upcoming input.)</p>
<p>If you are using the file object, every time <code>read()</code> is called with a positive argument, the underlying code will <code>recv()</code> only the amount of data requested, unless it's already buffered.</p>
<p>It would be buffered if:</p>
<ul>
<li><p>you had called readline(), which reads a full buffer</p></li>
<li><p>the end of the line was before the end of the buffer</p></li>
</ul>
<p>Thus leaving data in the buffer. Otherwise the buffer is generally not overfilled.</p>
<p>The goal of the question is not clear. if you need to see if data is available before reading, you can <code>select()</code> or set the socket to nonblocking mode with <code>s.setblocking(False)</code>. Then, reads will return empty, rather than blocking, if there is no waiting data.</p>
<p>Are you reading one file or socket with multiple threads? I would put a single worker on reading the socket and feeding received items into a queue for handling by other threads.</p>
<p>Suggest consulting <a href="http://svn.python.org/view/python/tags/r262/Lib/socket.py?revision=71601&view=markup#readline">Python Socket Module source</a> and <a href="http://svn.python.org/view/python/tags/r262/Modules/socketmodule.c?revision=71601&view=markup">C Source that makes the system calls</a>.</p>
| 18 | 2009-05-04T21:05:08Z | [
"python",
"sockets",
"buffering"
] |
Python sockets buffering | 822,001 | <p>Let's say I want to read a line from a socket, using the standard <code>socket</code> module:</p>
<pre><code>def read_line(s):
ret = ''
while True:
c = s.recv(1)
if c == '\n' or c == '':
break
else:
ret += c
return ret
</code></pre>
<p>What exactly happens in <code>s.recv(1)</code>? Will it issue a system call each time? I guess I should add some buffering, anyway:</p>
<blockquote>
<p>For best match with hardware and network realities, the value of <em>bufsize</em> should be a relatively small power of 2, for example, 4096.</p>
</blockquote>
<p><a href="http://docs.python.org/library/socket.html#socket.socket.recv">http://docs.python.org/library/socket.html#socket.socket.recv</a></p>
<p>But it doesn't seem easy to write efficient and thread-safe buffering. What if I use <code>file.readline()</code>?</p>
<pre><code># does this work well, is it efficiently buffered?
s.makefile().readline()
</code></pre>
| 13 | 2009-05-04T20:50:59Z | 822,788 | <p>If you are concerned with performance and control the socket completely
(you are not passing it into a library for example) then try implementing
your own buffering in Python -- Python string.find and string.split and such can
be amazingly fast.</p>
<pre><code>def linesplit(socket):
buffer = socket.recv(4096)
buffering = True
while buffering:
if "\n" in buffer:
(line, buffer) = buffer.split("\n", 1)
yield line + "\n"
else:
more = socket.recv(4096)
if not more:
buffering = False
else:
buffer += more
if buffer:
yield buffer
</code></pre>
<p>If you expect the payload to consist of lines
that are not too huge, that should run pretty fast,
and avoid jumping through too many layers of function
calls unnecessarily. I'd be interesting in knowing
how this compares to file.readline() or using socket.recv(1).</p>
| 20 | 2009-05-05T00:38:27Z | [
"python",
"sockets",
"buffering"
] |
Python sockets buffering | 822,001 | <p>Let's say I want to read a line from a socket, using the standard <code>socket</code> module:</p>
<pre><code>def read_line(s):
ret = ''
while True:
c = s.recv(1)
if c == '\n' or c == '':
break
else:
ret += c
return ret
</code></pre>
<p>What exactly happens in <code>s.recv(1)</code>? Will it issue a system call each time? I guess I should add some buffering, anyway:</p>
<blockquote>
<p>For best match with hardware and network realities, the value of <em>bufsize</em> should be a relatively small power of 2, for example, 4096.</p>
</blockquote>
<p><a href="http://docs.python.org/library/socket.html#socket.socket.recv">http://docs.python.org/library/socket.html#socket.socket.recv</a></p>
<p>But it doesn't seem easy to write efficient and thread-safe buffering. What if I use <code>file.readline()</code>?</p>
<pre><code># does this work well, is it efficiently buffered?
s.makefile().readline()
</code></pre>
| 13 | 2009-05-04T20:50:59Z | 11,348,929 | <pre><code>def buffered_readlines(pull_next_chunk, buf_size=4096):
"""
pull_next_chunk is callable that should accept one positional argument max_len,
i.e. socket.recv or file().read and returns string of up to max_len long or
empty one when nothing left to read.
>>> for line in buffered_readlines(socket.recv, 16384):
... print line
...
>>> # the following code won't read whole file into memory
... # before splitting it into lines like .readlines method
... # of file does. Also it won't block until FIFO-file is closed
...
>>> for line in buffered_readlines(open('huge_file').read):
... # process it on per-line basis
...
>>>
"""
chunks = []
while True:
chunk = pull_next_chunk(buf_size)
if not chunk:
if chunks:
yield ''.join(chunks)
break
if not '\n' in chunk:
chunks.append(chunk)
continue
chunk = chunk.split('\n')
if chunks:
yield ''.join(chunks + [chunk[0]])
else:
yield chunk[0]
for line in chunk[1:-1]:
yield line
if chunk[-1]:
chunks = [chunk[-1]]
else:
chunks = []
</code></pre>
| 6 | 2012-07-05T16:49:27Z | [
"python",
"sockets",
"buffering"
] |
How to separate content from a file that is a container for binary and other forms of content | 822,161 | <p>I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the children files. However I am having trouble writing the binary content back out as a binary file (say a gif or jpg). In the simplest case the container might have an embedded html file followed by a graphic that is called by the html. I am assuming that my problem is because I am reading the original .txt file using open(filename,'r'). But that seems the only option to find the sgml tags to split the file. </p>
<p>I would appreciate any help to identify some relevant reading material.</p>
<p>I appreciate the suggestions but I am still struggling with the most basic questions. For example when I open the file with wordpad and scroll down to the section tagged as a gif I see this:</p>
<pre><code><FILENAME>h65803h6580301.gif
<DESCRIPTION>GRAPHIC
<TEXT>
begin 644 h65803h6580301.gif
M1TE&.#EA(P)I`=4@`("`@,#`P$!`0+^_OW]_?_#P\*"@H.#@X-#0T&!@8!`0
M$+"PL"`@('!P<)"0D#`P,%!04#\_/^_O[Y^?GZ^OK]_?WX^/C\_/SV]O;U]?
</code></pre>
<p>I can handle finding the section easily enough but where does the gif file begin. Does the header start with 644, the blanks after the word begin or the line beginning with MITE?</p>
<p>Next, when the file is read into python does it do anything to the binary code that has to be undone when it is read back out? </p>
<p>I can find the lines where the graphics begin:</p>
<pre><code>filerefbin=file('myfile.txt','rb')
wholeFile=filerefbin.read()
import re
graphicReg=re.compile('<DESCRIPTION>GRAPHIC')
locationGraphics=graphicReg.finditer(wholeFile)
graphicsTags=[]
for match in locationGraphics:
graphicsTags.append(match.span())
</code></pre>
<p>I can easily use the same process to get to the word begin, or to identify the filename and get to the end of the filename in the 'first' line. I have also successefully gotten to the end of the embedded gif file. But I can't seem to write out the correct combination of things so when I double click on h65803h6580301.gif when it has been isolated and saved I get to see the graphic. </p>
<p>Interestingly, when I open the file in rb, the line endings appear to still be present even though they don't seem to have any effect in notebpad. So that is clearly one of my problems I might need to readlines and join the lines together after stripping out the \n</p>
<p>I love this site and I love PYTHON</p>
<p>This was too easy once I read bendin's post. I just had to snip the section that began with the word begin and save that in a txt file and then run the following command:</p>
<pre><code>import uu
uu.decode(r'c:\test2.txt',r'c:\test.gif')
</code></pre>
<p>I have to work with some other stuff for the rest of the day but I will post more here as I look at this more closely. The first thing I need to discover is how to use something other than a file, that is since I read the whole .txt file into memory and clipped out the section that has the image I need to work with the clipped section instead of writing it out to test2.txt. I am sure that can be done its just figuring out how to do it.</p>
| 2 | 2009-05-04T21:32:00Z | 822,192 | <p>You definitely need to be reading in binary mode if the content includes JPEG images.</p>
<p>As well, Python includes an SGML parser, <a href="http://docs.python.org/library/sgmllib.html" rel="nofollow">http://docs.python.org/library/sgmllib.html</a> .</p>
<p>There is no example there, but all you need to do is setup do_ methods to handle the sgml tags you wish.</p>
| 2 | 2009-05-04T21:39:13Z | [
"python",
"text",
"encoding",
"file",
"binary"
] |
How to separate content from a file that is a container for binary and other forms of content | 822,161 | <p>I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the children files. However I am having trouble writing the binary content back out as a binary file (say a gif or jpg). In the simplest case the container might have an embedded html file followed by a graphic that is called by the html. I am assuming that my problem is because I am reading the original .txt file using open(filename,'r'). But that seems the only option to find the sgml tags to split the file. </p>
<p>I would appreciate any help to identify some relevant reading material.</p>
<p>I appreciate the suggestions but I am still struggling with the most basic questions. For example when I open the file with wordpad and scroll down to the section tagged as a gif I see this:</p>
<pre><code><FILENAME>h65803h6580301.gif
<DESCRIPTION>GRAPHIC
<TEXT>
begin 644 h65803h6580301.gif
M1TE&.#EA(P)I`=4@`("`@,#`P$!`0+^_OW]_?_#P\*"@H.#@X-#0T&!@8!`0
M$+"PL"`@('!P<)"0D#`P,%!04#\_/^_O[Y^?GZ^OK]_?WX^/C\_/SV]O;U]?
</code></pre>
<p>I can handle finding the section easily enough but where does the gif file begin. Does the header start with 644, the blanks after the word begin or the line beginning with MITE?</p>
<p>Next, when the file is read into python does it do anything to the binary code that has to be undone when it is read back out? </p>
<p>I can find the lines where the graphics begin:</p>
<pre><code>filerefbin=file('myfile.txt','rb')
wholeFile=filerefbin.read()
import re
graphicReg=re.compile('<DESCRIPTION>GRAPHIC')
locationGraphics=graphicReg.finditer(wholeFile)
graphicsTags=[]
for match in locationGraphics:
graphicsTags.append(match.span())
</code></pre>
<p>I can easily use the same process to get to the word begin, or to identify the filename and get to the end of the filename in the 'first' line. I have also successefully gotten to the end of the embedded gif file. But I can't seem to write out the correct combination of things so when I double click on h65803h6580301.gif when it has been isolated and saved I get to see the graphic. </p>
<p>Interestingly, when I open the file in rb, the line endings appear to still be present even though they don't seem to have any effect in notebpad. So that is clearly one of my problems I might need to readlines and join the lines together after stripping out the \n</p>
<p>I love this site and I love PYTHON</p>
<p>This was too easy once I read bendin's post. I just had to snip the section that began with the word begin and save that in a txt file and then run the following command:</p>
<pre><code>import uu
uu.decode(r'c:\test2.txt',r'c:\test.gif')
</code></pre>
<p>I have to work with some other stuff for the rest of the day but I will post more here as I look at this more closely. The first thing I need to discover is how to use something other than a file, that is since I read the whole .txt file into memory and clipped out the section that has the image I need to work with the clipped section instead of writing it out to test2.txt. I am sure that can be done its just figuring out how to do it.</p>
| 2 | 2009-05-04T21:32:00Z | 822,398 | <p>You need to <code>open(filename,'rb')</code> to open the file in binary mode. Be aware that this will cause python to give You confusing, two-byte line endings on some operating systems.</p>
| 0 | 2009-05-04T22:27:41Z | [
"python",
"text",
"encoding",
"file",
"binary"
] |
How to separate content from a file that is a container for binary and other forms of content | 822,161 | <p>I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the children files. However I am having trouble writing the binary content back out as a binary file (say a gif or jpg). In the simplest case the container might have an embedded html file followed by a graphic that is called by the html. I am assuming that my problem is because I am reading the original .txt file using open(filename,'r'). But that seems the only option to find the sgml tags to split the file. </p>
<p>I would appreciate any help to identify some relevant reading material.</p>
<p>I appreciate the suggestions but I am still struggling with the most basic questions. For example when I open the file with wordpad and scroll down to the section tagged as a gif I see this:</p>
<pre><code><FILENAME>h65803h6580301.gif
<DESCRIPTION>GRAPHIC
<TEXT>
begin 644 h65803h6580301.gif
M1TE&.#EA(P)I`=4@`("`@,#`P$!`0+^_OW]_?_#P\*"@H.#@X-#0T&!@8!`0
M$+"PL"`@('!P<)"0D#`P,%!04#\_/^_O[Y^?GZ^OK]_?WX^/C\_/SV]O;U]?
</code></pre>
<p>I can handle finding the section easily enough but where does the gif file begin. Does the header start with 644, the blanks after the word begin or the line beginning with MITE?</p>
<p>Next, when the file is read into python does it do anything to the binary code that has to be undone when it is read back out? </p>
<p>I can find the lines where the graphics begin:</p>
<pre><code>filerefbin=file('myfile.txt','rb')
wholeFile=filerefbin.read()
import re
graphicReg=re.compile('<DESCRIPTION>GRAPHIC')
locationGraphics=graphicReg.finditer(wholeFile)
graphicsTags=[]
for match in locationGraphics:
graphicsTags.append(match.span())
</code></pre>
<p>I can easily use the same process to get to the word begin, or to identify the filename and get to the end of the filename in the 'first' line. I have also successefully gotten to the end of the embedded gif file. But I can't seem to write out the correct combination of things so when I double click on h65803h6580301.gif when it has been isolated and saved I get to see the graphic. </p>
<p>Interestingly, when I open the file in rb, the line endings appear to still be present even though they don't seem to have any effect in notebpad. So that is clearly one of my problems I might need to readlines and join the lines together after stripping out the \n</p>
<p>I love this site and I love PYTHON</p>
<p>This was too easy once I read bendin's post. I just had to snip the section that began with the word begin and save that in a txt file and then run the following command:</p>
<pre><code>import uu
uu.decode(r'c:\test2.txt',r'c:\test.gif')
</code></pre>
<p>I have to work with some other stuff for the rest of the day but I will post more here as I look at this more closely. The first thing I need to discover is how to use something other than a file, that is since I read the whole .txt file into memory and clipped out the section that has the image I need to work with the clipped section instead of writing it out to test2.txt. I am sure that can be done its just figuring out how to do it.</p>
| 2 | 2009-05-04T21:32:00Z | 826,277 | <p>What you're looking at isn't "binary", it's <strong><a href="http://en.wikipedia.org/wiki/Uuencode" rel="nofollow">uuencoded</a></strong>. Python's standard library includes the module <a href="http://docs.python.org/library/uu.html#module-uu" rel="nofollow">uu</a>, to handle uuencoded data.</p>
<p>The module <a href="http://docs.python.org/library/uu.html#module-uu" rel="nofollow">uu</a> requires the use of temporary files for encoding and decoding. You can accomplish this without resorting to temporary files by using Python's <a href="http://docs.python.org/library/codecs.html" rel="nofollow">codecs</a> module like this:</p>
<pre><code>import codecs
data = "Let's just pretend that this is binary data, ok?"
uuencode = codecs.getencoder("uu")
data_uu, n = uuencode(data)
uudecode = codecs.getdecoder("uu")
decoded, m = uudecode(data_uu)
print """* The initial input:
%(data)s
* Encoding these %(n)d bytes produces:
%(data_uu)s
* When we decode these %(m)d bytes, we get the original data back:
%(decoded)s""" % globals()
</code></pre>
| 3 | 2009-05-05T18:27:56Z | [
"python",
"text",
"encoding",
"file",
"binary"
] |
Emacs Pabbrev and Python | 822,195 | <p>Normally when you hit tab on an empty line in emacs python mode it will cycle through the available tab indentations. When I hit tab when the point is at the deepest indent level I get the pabbrev buffer containing the last best match options. Does anyone else have this problem, is there an easy way around it without writing any elisp?</p>
<p>EDIT:
Trey, I want to keep pabbrev working in python mode not turn it off.</p>
<p>So lets say there are 2 indent levels, either none, or 1 level normally if it hit tab 3 times the first would put the point at 4 spaces in (or whatever indent is set to), the second back to 0 spaces, and the third back to 4 spaces.</p>
<p>With pabbrev mode on one indent puts the mark 4 spaces, the second brings up a buffer for autocomplete. This should not happen if there is no letters to the left of my point.
Does that make any more sense?</p>
| 3 | 2009-05-04T21:39:58Z | 822,273 | <p>No elisp? Sure:</p>
<pre><code>M-x pabbrev-mode
</code></pre>
<p>should toggle it off. But, if you don't mind cutting/pasting elisp, you can turn off pabbrev mode in python buffers:</p>
<pre><code>(add-hook 'python-mode (lambda () (pabbrev-mode -1)))
</code></pre>
| 0 | 2009-05-04T21:54:38Z | [
"python",
"emacs",
"pabbrev"
] |
Emacs Pabbrev and Python | 822,195 | <p>Normally when you hit tab on an empty line in emacs python mode it will cycle through the available tab indentations. When I hit tab when the point is at the deepest indent level I get the pabbrev buffer containing the last best match options. Does anyone else have this problem, is there an easy way around it without writing any elisp?</p>
<p>EDIT:
Trey, I want to keep pabbrev working in python mode not turn it off.</p>
<p>So lets say there are 2 indent levels, either none, or 1 level normally if it hit tab 3 times the first would put the point at 4 spaces in (or whatever indent is set to), the second back to 0 spaces, and the third back to 4 spaces.</p>
<p>With pabbrev mode on one indent puts the mark 4 spaces, the second brings up a buffer for autocomplete. This should not happen if there is no letters to the left of my point.
Does that make any more sense?</p>
| 3 | 2009-05-04T21:39:58Z | 823,395 | <p>In light of the clarified requirements, you need something along the lines of this. I'm pretty sure you can't get away w/out writing some elisp. What's nice (IMO) is that this should work for all modes, not just python mode.</p>
<pre><code>(defadvice pabbrev-expand-maybe (around pabbrev-expand-maybe-when-not-after-whitespace activate)
"prevent expansion when only whitespace between point and beginning of line"
(if (save-match-data
(save-excursion
(let ((p (point)))
(string-match "^\\s-*$" (buffer-substring-no-properties (progn (beginning-of-line) (point)) p)))))
(let ((last-command (if (eq last-command this-command) (pabbrev-get-previous-binding) last-command))
(this-command (pabbrev-get-previous-binding)))
(pabbrev-call-previous-tab-binding))
ad-do-it))
</code></pre>
| 3 | 2009-05-05T04:48:39Z | [
"python",
"emacs",
"pabbrev"
] |
Emacs Pabbrev and Python | 822,195 | <p>Normally when you hit tab on an empty line in emacs python mode it will cycle through the available tab indentations. When I hit tab when the point is at the deepest indent level I get the pabbrev buffer containing the last best match options. Does anyone else have this problem, is there an easy way around it without writing any elisp?</p>
<p>EDIT:
Trey, I want to keep pabbrev working in python mode not turn it off.</p>
<p>So lets say there are 2 indent levels, either none, or 1 level normally if it hit tab 3 times the first would put the point at 4 spaces in (or whatever indent is set to), the second back to 0 spaces, and the third back to 4 spaces.</p>
<p>With pabbrev mode on one indent puts the mark 4 spaces, the second brings up a buffer for autocomplete. This should not happen if there is no letters to the left of my point.
Does that make any more sense?</p>
| 3 | 2009-05-04T21:39:58Z | 14,367,349 | <p>How is this for a late response? </p>
<p>This should work out of the box now, thanks to a patch from Trey. Binding tab in the way that pabbrev.el is somewhat naughty, but what are you to do if you want rapid expansion. </p>
| 1 | 2013-01-16T20:35:42Z | [
"python",
"emacs",
"pabbrev"
] |
I need a regex for the href attribute for an mp3 file url in python | 822,260 | <p>Based on a previous stack overflow question and contribution by cgoldberg, I came up with this regex using the python re module:</p>
<pre><code>import re
urls = re.finditer('http://(.*?).mp3', htmlcode)
</code></pre>
<p>The variable urls is an iterable object and I can use a loop to access each mp3 file url individually if there is more than one :</p>
<pre><code>for url in urls:
mp3fileurl = url.group(0)
</code></pre>
<p>This technique, however, only works sometimes. I realize regular expressions will not be as reliable as a fully fledged parser module. But, sometimes, this is not reliable for the same page.</p>
<p>I sometimes receive everything before http for some url entries. </p>
<p>I am relatively new to regular expressions. So, I am just wondering if there is a more reliable way to go about it.</p>
<p>Thanks in advance.
New to stackoverflow and looking forward to contributing some answers as well.</p>
| 2 | 2009-05-04T21:52:19Z | 822,341 | <p>First, yeah, you should probably be using an HTML parser. Here's some sample code using the HTMLParser module that comes with Python:</p>
<pre><code>from HTMLParser import HTMLParser
class ImgSrcHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.srcs = []
def handle_starttag(self, tag, attrs):
if tag == 'img':
self.srcs.append(dict(attrs).get('src'))
parser = ImgSrcHTMLParser()
parser.feed(html)
for src in parser.srcs:
print src
</code></pre>
<p>This collects the src from img tags. It should be pretty easy to adapt it to your purposes assuming you want the href of 'a' tags that end in '.mp3'.</p>
<p>Assuming you really want to use a regex, there are some issues with your regex. You aren't delimiting the URL and you're using dot inside the URL. The worst side-effect of this is that a non-mp3 URL followed by an mp3-URL will be treated as one long URL. eg: "http://foo/bar.gif snarf snarf <a href="http://baz/quux.mp3" rel="nofollow">http://baz/quux.mp3</a>". You probably want to require some kind of delimiter (spaces, quotes, depends on what you're doing) and disallow some characters inside URLs (probably the same characters and/or any characters that aren't allowed in URLs). Also, you forgot to escape the "." in ".mp3". So "http://foo/mp3icon.gif" will match as "http://foo/mp3".</p>
| 2 | 2009-05-04T22:12:26Z | [
"python",
"regex"
] |
I need a regex for the href attribute for an mp3 file url in python | 822,260 | <p>Based on a previous stack overflow question and contribution by cgoldberg, I came up with this regex using the python re module:</p>
<pre><code>import re
urls = re.finditer('http://(.*?).mp3', htmlcode)
</code></pre>
<p>The variable urls is an iterable object and I can use a loop to access each mp3 file url individually if there is more than one :</p>
<pre><code>for url in urls:
mp3fileurl = url.group(0)
</code></pre>
<p>This technique, however, only works sometimes. I realize regular expressions will not be as reliable as a fully fledged parser module. But, sometimes, this is not reliable for the same page.</p>
<p>I sometimes receive everything before http for some url entries. </p>
<p>I am relatively new to regular expressions. So, I am just wondering if there is a more reliable way to go about it.</p>
<p>Thanks in advance.
New to stackoverflow and looking forward to contributing some answers as well.</p>
| 2 | 2009-05-04T21:52:19Z | 822,416 | <p>As always I suggest using a html parser like <a href="http://codespeak.net/lxml/lxmlhtml.html" rel="nofollow">lxml.html</a> instead of regular expressions to extract informations from html files:</p>
<pre><code>import lxml.html
tree = lxml.html.fromstring(htmlcode)
for link in tree.findall(".//a"):
url = link.get("href")
if url.endswith(".mp3"):
print url
</code></pre>
| 2 | 2009-05-04T22:31:59Z | [
"python",
"regex"
] |
I need a regex for the href attribute for an mp3 file url in python | 822,260 | <p>Based on a previous stack overflow question and contribution by cgoldberg, I came up with this regex using the python re module:</p>
<pre><code>import re
urls = re.finditer('http://(.*?).mp3', htmlcode)
</code></pre>
<p>The variable urls is an iterable object and I can use a loop to access each mp3 file url individually if there is more than one :</p>
<pre><code>for url in urls:
mp3fileurl = url.group(0)
</code></pre>
<p>This technique, however, only works sometimes. I realize regular expressions will not be as reliable as a fully fledged parser module. But, sometimes, this is not reliable for the same page.</p>
<p>I sometimes receive everything before http for some url entries. </p>
<p>I am relatively new to regular expressions. So, I am just wondering if there is a more reliable way to go about it.</p>
<p>Thanks in advance.
New to stackoverflow and looking forward to contributing some answers as well.</p>
| 2 | 2009-05-04T21:52:19Z | 822,523 | <p>As pointed out by the other answers, using regular expressions to parse HTML = bad, bad idea.</p>
<p>With that in mind, I will add in code of my favorite parser: <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(htmlcode)
links = soup.findAll('a', href=True)
mp3s = [l for l in links if l['href'].endswith('.mp3')]
for song in mp3s:
print link['href']
</code></pre>
| 3 | 2009-05-04T22:56:19Z | [
"python",
"regex"
] |
How do I iterate over the HTML attributes of a Beautiful Soup element? | 822,571 | <p>How do I iterate over the HTML attributes of a Beautiful Soup element?</p>
<p>Like, given:</p>
<pre><code><foo bar="asdf" blah="123">xyz</foo>
</code></pre>
<p>I want "bar" and "blah".</p>
| 17 | 2009-05-04T23:14:02Z | 822,601 | <pre><code>from BeautifulSoup import BeautifulSoup
page = BeautifulSoup('<foo bar="asdf" blah="123">xyz</foo>')
for attr, value in page.find('foo').attrs:
print attr, "=", value
# Prints:
# bar = asdf
# blah = 123
</code></pre>
| 28 | 2009-05-04T23:24:13Z | [
"python",
"beautifulsoup"
] |
logging in mod_python/apache | 822,875 | <p>What is the standard way to make python's logging module work with apache/modpython?</p>
<p>I want to call mylog.warn('whatever') and have that result in a call to req.log_error() where req is the modpython request.</p>
<p>Is there an easy way to set this up?</p>
| 2 | 2009-05-05T01:08:11Z | 823,126 | <p>I've never done it, but it seems that writing a subclass of <a href="http://docs.python.org/library/logging.html#handlers" rel="nofollow"><code>logging.Handler</code></a> shouldn't be that hard. Something like this should do the trick. I can't say that I have actually tried this since I don't have mod_python installed currently but you should be able to call <code>logging.root.addHandler(ApacheLogHandler())</code> somewhere and get it to work out. YMMV.</p>
<pre><code>import logging
import apache
class ApacheLogHandler(logging.Handler):
LEVEL_MAP = {
logging.DEBUG: apache.APLOG_DEBUG,
logging.INFO: apache.APLOG_INFO,
logging.WARNING: apache.APLOG_WARNING,
logging.ERROR: apache.APLOG_ERR,
logging.CRITICAL: apache.APLOG_CRIT,
}
def __init__(self, request=None):
self.log_error = apache.log_error
if request is not None:
self.log_error = request.log_error
def emit(self,record):
apacheLevel = apache.APLOG_DEBUG
if record.levelno in ApacheLogHandler.LEVEL_MAP:
apacheLevel = ApacheLogHandler.LEVEL_MAP[record.levelno]
self.log_error(record.getMessage(), apacheLevel)
</code></pre>
| 2 | 2009-05-05T03:02:26Z | [
"python",
"apache",
"logging",
"mod-python"
] |
logging in mod_python/apache | 822,875 | <p>What is the standard way to make python's logging module work with apache/modpython?</p>
<p>I want to call mylog.warn('whatever') and have that result in a call to req.log_error() where req is the modpython request.</p>
<p>Is there an easy way to set this up?</p>
| 2 | 2009-05-05T01:08:11Z | 824,236 | <p>We use the following. It's documented completely <a href="http://docs.python.org/library/logging.html#module-logging" rel="nofollow">here</a>.</p>
<ol>
<li><p>We use <a href="http://docs.python.org/library/logging.html#logging.fileConfig" rel="nofollow">logging.fileConfig</a> with a logging.ini file.</p></li>
<li><p>Each module uses <code>logger= logging.getLogger(__name__)</code></p></li>
<li><p>Then we can do logger.error("blah blah blah") throughout our application.</p></li>
</ol>
<p>It works perfectly. The logging.ini file defines where the log file goes so that we can keep it with other log files for our web app.</p>
| 0 | 2009-05-05T10:18:14Z | [
"python",
"apache",
"logging",
"mod-python"
] |
Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings? | 823,030 | <p>I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically:</p>
<p>I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So:</p>
<pre><code>>>> type(myDict)
<type 'dict'>
>>> type(myDict[u'myKey'])
<type 'dict'>
>>> type(myDict[u'myKey'][u'myKey2'])
<type 'list'>
>>> type(myDict[u'myKey'][u'myKey2'][0])
<type 'unicode'>
</code></pre>
<p>I want to go through and make every string in it lowercase, i.e. every key and every string in every list. </p>
<p>How would you do this?</p>
| 3 | 2009-05-05T02:25:32Z | 823,057 | <p>The following works for your example input:</p>
<pre><code>>>> myDict = {'myKey': {'myKey2': [u'Abc']}}
>>> newDict = dict([
(k1.lower(), dict([
(k2.lower(), [x.lower() for x in myDict[k1][k2]])
for k2 in myDict[k1].keys()
])) for k1 in myDict.keys()
])
>>> newDict
{'mykey': {'mykey2': [u'abc']}}
</code></pre>
| 1 | 2009-05-05T02:31:44Z | [
"python"
] |
Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings? | 823,030 | <p>I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically:</p>
<p>I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So:</p>
<pre><code>>>> type(myDict)
<type 'dict'>
>>> type(myDict[u'myKey'])
<type 'dict'>
>>> type(myDict[u'myKey'][u'myKey2'])
<type 'list'>
>>> type(myDict[u'myKey'][u'myKey2'][0])
<type 'unicode'>
</code></pre>
<p>I want to go through and make every string in it lowercase, i.e. every key and every string in every list. </p>
<p>How would you do this?</p>
| 3 | 2009-05-05T02:25:32Z | 823,072 | <p>A recursive variant:</p>
<pre><code>def make_lowercase(obj):
if hasattr(obj,'iteritems'):
# dictionary
ret = {}
for k,v in obj.iteritems():
ret[make_lowercase(k)] = make_lowercase(v)
return ret
elif isinstance(obj,basestring):
# string
return obj.lower()
elif hasattr(obj,'__iter__'):
# list (or the like)
ret = []
for item in obj:
ret.append(make_lowercase(item))
return ret
else:
# anything else
return obj
</code></pre>
<p>Example:</p>
<pre><code>>>> make_lowercase({'Foo': [{1: 'Baz', 'Bar': 2}]})
{'foo': [{1: 'baz', 'bar': 2}]}
</code></pre>
| 3 | 2009-05-05T02:37:34Z | [
"python"
] |
Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings? | 823,030 | <p>I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically:</p>
<p>I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So:</p>
<pre><code>>>> type(myDict)
<type 'dict'>
>>> type(myDict[u'myKey'])
<type 'dict'>
>>> type(myDict[u'myKey'][u'myKey2'])
<type 'list'>
>>> type(myDict[u'myKey'][u'myKey2'][0])
<type 'unicode'>
</code></pre>
<p>I want to go through and make every string in it lowercase, i.e. every key and every string in every list. </p>
<p>How would you do this?</p>
| 3 | 2009-05-05T02:25:32Z | 823,077 | <p>Really simple way, though I'm not sure you'd call it Pythonic:</p>
<pre><code>newDict = eval(repr(myDict).lower())
</code></pre>
<p>Saner way:</p>
<pre><code>newDict = dict((k1.lower(),
dict((k2.lower(),
[s.lower() for s in v2]) for k2, v2 in v1.iteritems()))
for k1, v1 in myDict.iteritems())
</code></pre>
| 18 | 2009-05-05T02:39:37Z | [
"python"
] |
Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings? | 823,030 | <p>I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically:</p>
<p>I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So:</p>
<pre><code>>>> type(myDict)
<type 'dict'>
>>> type(myDict[u'myKey'])
<type 'dict'>
>>> type(myDict[u'myKey'][u'myKey2'])
<type 'list'>
>>> type(myDict[u'myKey'][u'myKey2'][0])
<type 'unicode'>
</code></pre>
<p>I want to go through and make every string in it lowercase, i.e. every key and every string in every list. </p>
<p>How would you do this?</p>
| 3 | 2009-05-05T02:25:32Z | 823,079 | <p>If you don't mind modifying your input:</p>
<pre><code>def make_lower(x):
try:
return x.lower() # x is a string
except AttributeError:
# assume x is a dict of the appropriate form
for key in x.keys():
x[key.lower()] = make_lower(x[key])
if key != key.lower():
del x[key]
return x
make_lower(myDict)
</code></pre>
| 0 | 2009-05-05T02:40:48Z | [
"python"
] |
What's the best way to record the type of every variable assignment in a Python program? | 823,103 | <p>Python is so dynamic that it's not always clear what's going on in a large program, and looking at a tiny bit of source code does not always help. To make matters worse, editors tend to have poor support for navigating to the definitions of tokens or import statements in a Python file.</p>
<p>One way to compensate might be to write a special profiler that, instead of timing the program, would record the runtime types and paths of objects of the program and expose this data to the editor.</p>
<p>This might be implemented with sys.settrace() which sets a callback for each line of code and is how pdb is implemented, or by using the ast module and an import hook to instrument the code, or is there a better strategy? How would you write something like this without making it impossibly slow, and without runnning afoul of extreme dynamism e.g side affects on property access?</p>
| 3 | 2009-05-05T02:52:08Z | 823,111 | <p>I don't think you can help making it slow, but it should be possible to detect the address of each variable when you encounter a STORE_FAST STORE_NAME STORE_* opcode.</p>
<p>Whether or not this has been done before, I do not know.</p>
<p>If you need debugging, look at <a href="http://docs.python.org/library/pdb.html" rel="nofollow">PDB</a>, this will allow you to step through your code and access any variables.</p>
<pre><code>import pdb
def test():
print 1
pdb.set_trace() # you will enter an interpreter here
print 2
</code></pre>
| 3 | 2009-05-05T02:56:25Z | [
"python",
"profiling"
] |
What's the best way to record the type of every variable assignment in a Python program? | 823,103 | <p>Python is so dynamic that it's not always clear what's going on in a large program, and looking at a tiny bit of source code does not always help. To make matters worse, editors tend to have poor support for navigating to the definitions of tokens or import statements in a Python file.</p>
<p>One way to compensate might be to write a special profiler that, instead of timing the program, would record the runtime types and paths of objects of the program and expose this data to the editor.</p>
<p>This might be implemented with sys.settrace() which sets a callback for each line of code and is how pdb is implemented, or by using the ast module and an import hook to instrument the code, or is there a better strategy? How would you write something like this without making it impossibly slow, and without runnning afoul of extreme dynamism e.g side affects on property access?</p>
| 3 | 2009-05-05T02:52:08Z | 823,117 | <p>What if you monkey-patched <code>object</code>'s class or another prototypical object?</p>
<p>This might not be the easiest if you're not using new-style classes.</p>
| 1 | 2009-05-05T02:57:22Z | [
"python",
"profiling"
] |
What's the best way to record the type of every variable assignment in a Python program? | 823,103 | <p>Python is so dynamic that it's not always clear what's going on in a large program, and looking at a tiny bit of source code does not always help. To make matters worse, editors tend to have poor support for navigating to the definitions of tokens or import statements in a Python file.</p>
<p>One way to compensate might be to write a special profiler that, instead of timing the program, would record the runtime types and paths of objects of the program and expose this data to the editor.</p>
<p>This might be implemented with sys.settrace() which sets a callback for each line of code and is how pdb is implemented, or by using the ast module and an import hook to instrument the code, or is there a better strategy? How would you write something like this without making it impossibly slow, and without runnning afoul of extreme dynamism e.g side affects on property access?</p>
| 3 | 2009-05-05T02:52:08Z | 823,179 | <p>You might want to check out <a href="http://pychecker.sourceforge.net/" rel="nofollow">PyChecker</a>'s code - it does (i think) what you are looking to do.</p>
| 1 | 2009-05-05T03:23:50Z | [
"python",
"profiling"
] |
What's the best way to record the type of every variable assignment in a Python program? | 823,103 | <p>Python is so dynamic that it's not always clear what's going on in a large program, and looking at a tiny bit of source code does not always help. To make matters worse, editors tend to have poor support for navigating to the definitions of tokens or import statements in a Python file.</p>
<p>One way to compensate might be to write a special profiler that, instead of timing the program, would record the runtime types and paths of objects of the program and expose this data to the editor.</p>
<p>This might be implemented with sys.settrace() which sets a callback for each line of code and is how pdb is implemented, or by using the ast module and an import hook to instrument the code, or is there a better strategy? How would you write something like this without making it impossibly slow, and without runnning afoul of extreme dynamism e.g side affects on property access?</p>
| 3 | 2009-05-05T02:52:08Z | 2,449,127 | <p><a href="http://pythoscope.org" rel="nofollow">Pythoscope</a> does something very similar to what you describe and it uses a combination of static information in a form of AST and dynamic information through <code>sys.settrace</code>.</p>
<p>BTW, if you have problems refactoring your project, give Pythoscope a try.</p>
| 1 | 2010-03-15T17:30:32Z | [
"python",
"profiling"
] |
Why is this recursive statement wrong? | 823,141 | <p>This is a bank simulation that takes into account 20 different serving lines with a single queue, customers arrive following an exponential rate and they are served during a time that follows a normal probability distribution with mean 40 and standard deviation 20. </p>
<p>Things were working just fine till I decided to exclude the negative values given by the normal distribution using this method: </p>
<pre><code>def getNormal(self):
normal = normalvariate(40,20)
if (normal>=1):
return normal
else:
getNormal(self)
</code></pre>
<p>Which has caused the program to give me this screen every now and then:
<a href="http://yfrog.com/2qrecursionp" rel="nofollow">SCREEN</a></p>
<p>Am I screwing up the recursive call? I don't get why it wouldn't work. I have changed the getNormal() method to:</p>
<pre><code>def getNormal(self):
normal = normalvariate(40,20)
while (normal <=1):
normal = normalvariate (40,20)
return normal
</code></pre>
<p>But I'm curious on why the previous recursive statement gets busted.</p>
<p>This is the complete source code, in case you're interested.</p>
<pre><code>""" bank21: One counter with impatient customers """
from SimPy.SimulationTrace import *
from random import *
## Model components ------------------------
class Source(Process):
""" Source generates customers randomly """
def generate(self,number):
for i in range(number):
c = Customer(name = "Customer%02d"%(i,))
activate(c,c.visit(tiempoDeUso=15.0))
validateTime=now()
if validateTime<=600:
interval = getLambda(self)
t = expovariate(interval)
yield hold,self,t #esta es la rata de generación
else:
detenerGeneracion=999
yield hold,self,detenerGeneracion
class Customer(Process):
""" Customer arrives, is served and leaves """
def visit(self,tiempoDeUso=0):
arrive = now() # arrival time
print "%8.3f %s: Here I am "%(now(),self.name)
yield (request,self,counter),(hold,self,maxWaitTime)
wait = now()-arrive # waiting time
if self.acquired(counter):
print "%8.3f %s: Waited %6.3f"%(now(),self.name,wait)
tiempoDeUso=getNormal(self)
yield hold,self,tiempoDeUso
yield release,self,counter
print "%8.3f %s: Completed"%(now(),self.name)
else:
print "%8.3f %s: Waited %6.3f. I am off"%(now(),self.name,wait)
## Experiment data -------------------------
maxTime = 60*10.5 # minutes
maxWaitTime = 12.0 # minutes. maximum time to wait
## Model ----------------------------------
def model():
global counter
#seed(98989)
counter = Resource(name="Las maquinas",capacity=20)
initialize()
source = Source('Source')
firstArrival= expovariate(20.0/60.0) #chequear el expovariate
activate(source,
source.generate(number=99999),at=firstArrival)
simulate(until=maxTime)
def getNormal(self):
normal = normalvariate(40,20)
if (normal>=1):
return normal
else:
getNormal(self)
def getLambda (self):
actualTime=now()
if (actualTime <=60):
return 20.0/60.0
if (actualTime>60)and (actualTime<=120):
return 25.0/60.0
if (actualTime>120)and (actualTime<=180):
return 40.0/60.0
if (actualTime>180)and (actualTime<=240):
return 30.0/60.0
if (actualTime>240)and (actualTime<=300):
return 35.0/60.0
if (actualTime>300)and (actualTime<=360):
return 42.0/60.0
if (actualTime>360)and (actualTime<=420):
return 50.0/60.0
if (actualTime>420)and (actualTime<=480):
return 55.0/60.0
if (actualTime>480)and (actualTime<=540):
return 45.0/60.0
if (actualTime>540)and (actualTime<=600):
return 10.0/60.0
## Experiment ----------------------------------
model()
</code></pre>
| 0 | 2009-05-05T03:08:00Z | 823,149 | <p>I think you want </p>
<pre><code>return getnormal(self)
</code></pre>
<p>instead of</p>
<pre><code>getnormal(self)
</code></pre>
<p>If the function exits without hitting a return statement, then it returns the special value None, which is a NoneType object - that's why Python complains about a 'NoneType.' The abs() function wants a number, and it doesn't know what to do with a None.</p>
<p>Also, you could avoid recursion (and the cost of creating a new stack frame) by using</p>
<pre><code>def getNormal(self):
normal = 0
while normal < 1:
normal = normalvariate(40,20)
return normal
</code></pre>
| 8 | 2009-05-05T03:12:39Z | [
"python",
"recursion",
"simpy"
] |
Why is this recursive statement wrong? | 823,141 | <p>This is a bank simulation that takes into account 20 different serving lines with a single queue, customers arrive following an exponential rate and they are served during a time that follows a normal probability distribution with mean 40 and standard deviation 20. </p>
<p>Things were working just fine till I decided to exclude the negative values given by the normal distribution using this method: </p>
<pre><code>def getNormal(self):
normal = normalvariate(40,20)
if (normal>=1):
return normal
else:
getNormal(self)
</code></pre>
<p>Which has caused the program to give me this screen every now and then:
<a href="http://yfrog.com/2qrecursionp" rel="nofollow">SCREEN</a></p>
<p>Am I screwing up the recursive call? I don't get why it wouldn't work. I have changed the getNormal() method to:</p>
<pre><code>def getNormal(self):
normal = normalvariate(40,20)
while (normal <=1):
normal = normalvariate (40,20)
return normal
</code></pre>
<p>But I'm curious on why the previous recursive statement gets busted.</p>
<p>This is the complete source code, in case you're interested.</p>
<pre><code>""" bank21: One counter with impatient customers """
from SimPy.SimulationTrace import *
from random import *
## Model components ------------------------
class Source(Process):
""" Source generates customers randomly """
def generate(self,number):
for i in range(number):
c = Customer(name = "Customer%02d"%(i,))
activate(c,c.visit(tiempoDeUso=15.0))
validateTime=now()
if validateTime<=600:
interval = getLambda(self)
t = expovariate(interval)
yield hold,self,t #esta es la rata de generación
else:
detenerGeneracion=999
yield hold,self,detenerGeneracion
class Customer(Process):
""" Customer arrives, is served and leaves """
def visit(self,tiempoDeUso=0):
arrive = now() # arrival time
print "%8.3f %s: Here I am "%(now(),self.name)
yield (request,self,counter),(hold,self,maxWaitTime)
wait = now()-arrive # waiting time
if self.acquired(counter):
print "%8.3f %s: Waited %6.3f"%(now(),self.name,wait)
tiempoDeUso=getNormal(self)
yield hold,self,tiempoDeUso
yield release,self,counter
print "%8.3f %s: Completed"%(now(),self.name)
else:
print "%8.3f %s: Waited %6.3f. I am off"%(now(),self.name,wait)
## Experiment data -------------------------
maxTime = 60*10.5 # minutes
maxWaitTime = 12.0 # minutes. maximum time to wait
## Model ----------------------------------
def model():
global counter
#seed(98989)
counter = Resource(name="Las maquinas",capacity=20)
initialize()
source = Source('Source')
firstArrival= expovariate(20.0/60.0) #chequear el expovariate
activate(source,
source.generate(number=99999),at=firstArrival)
simulate(until=maxTime)
def getNormal(self):
normal = normalvariate(40,20)
if (normal>=1):
return normal
else:
getNormal(self)
def getLambda (self):
actualTime=now()
if (actualTime <=60):
return 20.0/60.0
if (actualTime>60)and (actualTime<=120):
return 25.0/60.0
if (actualTime>120)and (actualTime<=180):
return 40.0/60.0
if (actualTime>180)and (actualTime<=240):
return 30.0/60.0
if (actualTime>240)and (actualTime<=300):
return 35.0/60.0
if (actualTime>300)and (actualTime<=360):
return 42.0/60.0
if (actualTime>360)and (actualTime<=420):
return 50.0/60.0
if (actualTime>420)and (actualTime<=480):
return 55.0/60.0
if (actualTime>480)and (actualTime<=540):
return 45.0/60.0
if (actualTime>540)and (actualTime<=600):
return 10.0/60.0
## Experiment ----------------------------------
model()
</code></pre>
| 0 | 2009-05-05T03:08:00Z | 823,150 | <p>You need to have:</p>
<pre><code>return getNormal(self)
</code></pre>
<p>instead of</p>
<pre><code>getNormal(self)
</code></pre>
<p>Really though, there's no need for recursion:</p>
<pre><code>def getNormal(self):
normal = 0
while normal < 1:
normal = normalvariate(40,20)
return normal
</code></pre>
| 1 | 2009-05-05T03:13:04Z | [
"python",
"recursion",
"simpy"
] |
Why is this recursive statement wrong? | 823,141 | <p>This is a bank simulation that takes into account 20 different serving lines with a single queue, customers arrive following an exponential rate and they are served during a time that follows a normal probability distribution with mean 40 and standard deviation 20. </p>
<p>Things were working just fine till I decided to exclude the negative values given by the normal distribution using this method: </p>
<pre><code>def getNormal(self):
normal = normalvariate(40,20)
if (normal>=1):
return normal
else:
getNormal(self)
</code></pre>
<p>Which has caused the program to give me this screen every now and then:
<a href="http://yfrog.com/2qrecursionp" rel="nofollow">SCREEN</a></p>
<p>Am I screwing up the recursive call? I don't get why it wouldn't work. I have changed the getNormal() method to:</p>
<pre><code>def getNormal(self):
normal = normalvariate(40,20)
while (normal <=1):
normal = normalvariate (40,20)
return normal
</code></pre>
<p>But I'm curious on why the previous recursive statement gets busted.</p>
<p>This is the complete source code, in case you're interested.</p>
<pre><code>""" bank21: One counter with impatient customers """
from SimPy.SimulationTrace import *
from random import *
## Model components ------------------------
class Source(Process):
""" Source generates customers randomly """
def generate(self,number):
for i in range(number):
c = Customer(name = "Customer%02d"%(i,))
activate(c,c.visit(tiempoDeUso=15.0))
validateTime=now()
if validateTime<=600:
interval = getLambda(self)
t = expovariate(interval)
yield hold,self,t #esta es la rata de generación
else:
detenerGeneracion=999
yield hold,self,detenerGeneracion
class Customer(Process):
""" Customer arrives, is served and leaves """
def visit(self,tiempoDeUso=0):
arrive = now() # arrival time
print "%8.3f %s: Here I am "%(now(),self.name)
yield (request,self,counter),(hold,self,maxWaitTime)
wait = now()-arrive # waiting time
if self.acquired(counter):
print "%8.3f %s: Waited %6.3f"%(now(),self.name,wait)
tiempoDeUso=getNormal(self)
yield hold,self,tiempoDeUso
yield release,self,counter
print "%8.3f %s: Completed"%(now(),self.name)
else:
print "%8.3f %s: Waited %6.3f. I am off"%(now(),self.name,wait)
## Experiment data -------------------------
maxTime = 60*10.5 # minutes
maxWaitTime = 12.0 # minutes. maximum time to wait
## Model ----------------------------------
def model():
global counter
#seed(98989)
counter = Resource(name="Las maquinas",capacity=20)
initialize()
source = Source('Source')
firstArrival= expovariate(20.0/60.0) #chequear el expovariate
activate(source,
source.generate(number=99999),at=firstArrival)
simulate(until=maxTime)
def getNormal(self):
normal = normalvariate(40,20)
if (normal>=1):
return normal
else:
getNormal(self)
def getLambda (self):
actualTime=now()
if (actualTime <=60):
return 20.0/60.0
if (actualTime>60)and (actualTime<=120):
return 25.0/60.0
if (actualTime>120)and (actualTime<=180):
return 40.0/60.0
if (actualTime>180)and (actualTime<=240):
return 30.0/60.0
if (actualTime>240)and (actualTime<=300):
return 35.0/60.0
if (actualTime>300)and (actualTime<=360):
return 42.0/60.0
if (actualTime>360)and (actualTime<=420):
return 50.0/60.0
if (actualTime>420)and (actualTime<=480):
return 55.0/60.0
if (actualTime>480)and (actualTime<=540):
return 45.0/60.0
if (actualTime>540)and (actualTime<=600):
return 10.0/60.0
## Experiment ----------------------------------
model()
</code></pre>
| 0 | 2009-05-05T03:08:00Z | 823,160 | <p>I am not entirely sure, but I think you need to change your method to the following:</p>
<pre><code>def getNormal(self):
normal = normalvariate(40,20)
if (normal>=1):
return normal
else:
return getNormal(self)
</code></pre>
| 1 | 2009-05-05T03:17:38Z | [
"python",
"recursion",
"simpy"
] |
Yaml merge in Python | 823,196 | <p>So I'm toying around with the idea of making myself (and anyone who cares to use it of course) a little boilerplate library in Python for Pygame. I would like a system where settings for the application are provided with a yaml file. </p>
<p>So I was thinking it would be useful if the library provided a default yaml tree and merged it with a user supplied one. For usability sake I wonder if possible there are any out there who can divine a routine where:</p>
<p>In any case in the tree where the user supplied yaml overlaps the default, the user supplied branches replace the library supplied ones.</p>
<p>In any case where the user supplied yaml does not overlap the default tree, the default tree persists.</p>
<p>Any superflous branches in the tree provided by the user supplied yaml are appended.</p>
<p>I know this explanation was verbose as it is probably clear what I'm asking for. I wonder if it is a bit much to get for free.</p>
| 11 | 2009-05-05T03:31:41Z | 823,240 | <p>You could use <a href="http://pyyaml.org/">PyYAML</a> for parsing the files, and then the following function to merge two trees:</p>
<pre><code>def merge(user, default):
if isinstance(user,dict) and isinstance(default,dict):
for k,v in default.iteritems():
if k not in user:
user[k] = v
else:
user[k] = merge(user[k],v)
return user
</code></pre>
<p>Optionally, you could do a <a href="http://docs.python.org/library/copy.html">deep-copy</a> of the user-tree before calling this function.</p>
| 17 | 2009-05-05T03:46:17Z | [
"python",
"configuration",
"yaml"
] |
What does += mean in Python? | 823,561 | <p>I see code like this for example in Python:</p>
<pre><code> if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
</code></pre>
<p>What does the <code>+=</code> mean?</p>
| 9 | 2009-05-05T06:10:26Z | 823,567 | <pre><code>a += b
</code></pre>
<p>is <em>in this case</em> the same as</p>
<pre><code>a = a + b
</code></pre>
<p>In this case cnt += 1 means that cnt is increased by one.</p>
<p>Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.</p>
<p><strong>Edit</strong>: quote <a href="http://stackoverflow.com/users/3207/carl-meyer">Carl Meyer</a>: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see <a href="http://stackoverflow.com/questions/823561/what-does-mean-in-python/823878#823878">Bastien's answer</a>.''.</p>
| 22 | 2009-05-05T06:11:25Z | [
"python",
"syntax"
] |
What does += mean in Python? | 823,561 | <p>I see code like this for example in Python:</p>
<pre><code> if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
</code></pre>
<p>What does the <code>+=</code> mean?</p>
| 9 | 2009-05-05T06:10:26Z | 823,576 | <p>it means "append "THIS" to the current value"</p>
<p>example:</p>
<p>a = "hello";
a += " world";</p>
<p>printing a now will output: "hello world"</p>
| -3 | 2009-05-05T06:14:40Z | [
"python",
"syntax"
] |
What does += mean in Python? | 823,561 | <p>I see code like this for example in Python:</p>
<pre><code> if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
</code></pre>
<p>What does the <code>+=</code> mean?</p>
| 9 | 2009-05-05T06:10:26Z | 823,580 | <p>FYI: it looks like you might have an infinite loop in your example...</p>
<pre><code>if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
</code></pre>
<ul>
<li>a condition of entering the loop is that <code>cnt</code> is greater than 0</li>
<li>the loop continues to run as long as <code>cnt</code> is greater than 0</li>
<li>each iteration of the loop increments <code>cnt</code> by 1</li>
</ul>
<p>The net result is that <code>cnt</code> will <em>always</em> be greater than 0 and the loop will never exit.</p>
| 1 | 2009-05-05T06:15:34Z | [
"python",
"syntax"
] |
What does += mean in Python? | 823,561 | <p>I see code like this for example in Python:</p>
<pre><code> if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
</code></pre>
<p>What does the <code>+=</code> mean?</p>
| 9 | 2009-05-05T06:10:26Z | 823,583 | <p>Google 'python += operator' leads you to <a href="http://docs.python.org/library/operator.html" rel="nofollow">http://docs.python.org/library/operator.html</a></p>
<p>Search for += once the page loads up for a more detailed answer.</p>
| 7 | 2009-05-05T06:16:56Z | [
"python",
"syntax"
] |
What does += mean in Python? | 823,561 | <p>I see code like this for example in Python:</p>
<pre><code> if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
</code></pre>
<p>What does the <code>+=</code> mean?</p>
| 9 | 2009-05-05T06:10:26Z | 823,878 | <p><code>a += b</code> is essentially the same as <code>a = a + b</code>, except that:</p>
<ul>
<li><code>+</code> always returns a newly allocated object, but <code>+=</code> should (but doesn't have to) modify the object in-place if it's mutable (e.g. <code>list</code> or <code>dict</code>, but <code>int</code> and <code>str</code> are immutable).</li>
<li>In <code>a = a + b</code>, <code>a</code> is evaluated twice.</li>
</ul>
<p><a href="http://docs.python.org/reference/simple_stmts.html#augmented-assignment-statements">http://docs.python.org/reference/simple_stmts.html#augmented-assignment-statements</a></p>
<p><hr /></p>
<p>If this is the first time you encounter the <code>+=</code> operator, you may wonder why it matters that it may modify the object in-place instead of building a new one. Here is an example:</p>
<pre><code># two variables referring to the same list
>>> list1 = []
>>> list2 = list1
# += modifies the object pointed to by list1 and list2
>>> list1 += [0]
>>> list1, list2
([0], [0])
# + creates a new, independent object
>>> list1 = []
>>> list2 = list1
>>> list1 = list1 + [0]
>>> list1, list2
([0], [])
</code></pre>
| 63 | 2009-05-05T08:28:49Z | [
"python",
"syntax"
] |
What does += mean in Python? | 823,561 | <p>I see code like this for example in Python:</p>
<pre><code> if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
</code></pre>
<p>What does the <code>+=</code> mean?</p>
| 9 | 2009-05-05T06:10:26Z | 825,505 | <p><code>+=</code> is the <a href="http://docs.python.org/library/operator.html#operator.iadd" rel="nofollow">in-place addition operator</a>.</p>
<p>It's the same as doing <code>cnt = cnt + 1</code>. For example:</p>
<pre><code>>>> cnt = 0
>>> cnt += 2
>>> print cnt
2
>>> cnt += 42
>>> print cnt
44
</code></pre>
<p>The operator is often used in a similar fashion to the <code>++</code> operator in C-ish languages, to increment a variable by one in a loop (<code>i += 1</code>)</p>
<p>There are similar operator for subtraction/multiplication/division/power and others:</p>
<pre><code>i -= 1 # same as i = i - 1
i *= 2 # i = i * 2
i /= 3 # i = i / 3
i **= 4 # i = i ** 4
</code></pre>
<p>The <code>+=</code> operator also works on strings, for example:</p>
<pre><code>>>> s = "Hi"
>>> s += " there"
>>> print s
Hi there
</code></pre>
<p>People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the <a href="http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange" rel="nofollow">"Sequence Types" docs</a>:</p>
<blockquote>
<ol>
<li>If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.</li>
</ol>
</blockquote>
<p>The str.join() method refers to doing the following:</p>
<pre><code>mysentence = []
for x in range(100):
mysentence.append("test")
" ".join(mysentence)
</code></pre>
<p>..instead of the more obvious:</p>
<pre><code>mysentence = ""
for x in range(100):
mysentence += " test"
</code></pre>
<p>The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)</p>
<p>If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then <code>"".join()</code>'ing it.</p>
| 0 | 2009-05-05T15:43:55Z | [
"python",
"syntax"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.