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
sequence |
---|---|---|---|---|---|---|---|---|---|
Short Integers in Python | 120,250 | <p>Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. </p>
<p>So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?</p>
| 10 | 2008-09-23T10:35:09Z | 120,449 | <p>Thanks to Armin for pointing out the 'array' module. I also found the 'struct' module that packs c-style structs in a string:</p>
<p>From the documentation (<a href="https://docs.python.org/library/struct.html" rel="nofollow">https://docs.python.org/library/struct.html</a>):</p>
<pre><code>>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('hhl')
8
</code></pre>
| 5 | 2008-09-23T11:34:37Z | [
"python",
"memory-management",
"short"
] |
Short Integers in Python | 120,250 | <p>Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. </p>
<p>So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?</p>
| 10 | 2008-09-23T10:35:09Z | 120,454 | <p>Armin's suggestion of the array module is probably best. Two possible alternatives:</p>
<ul>
<li>You can create an extension module yourself that provides the data structure that you're after. If it's really just something like a collection of shorts, then
that's pretty simple to do.</li>
<li>You can
cheat and manipulate bits, so that
you're storing one number in the
lower half of the Python int, and
another one in the upper half.
You'd write some utility functions
to convert to/from these within your
data structure. Ugly, but it can be made to work.</li>
</ul>
<p>It's also worth realising that a Python integer object is not 4 bytes - there is additional overhead. So if you have a really large number of shorts, then you can save more than two bytes per number by using a C short in some way (e.g. the array module).</p>
<p>I had to keep a large set of integers in memory a while ago, and a dictionary with integer keys and values was too large (I had 1GB available for the data structure IIRC). I switched to using a IIBTree (from ZODB) and managed to fit it. (The ints in a IIBTree are real C ints, not Python integers, and I hacked up an automatic switch to a IOBTree when the number was larger than 32 bits).</p>
| 2 | 2008-09-23T11:35:15Z | [
"python",
"memory-management",
"short"
] |
Short Integers in Python | 120,250 | <p>Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. </p>
<p>So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?</p>
| 10 | 2008-09-23T10:35:09Z | 120,469 | <p>@<a href="#120256" rel="nofollow">Armin</a>: how come? The Python documentation said the minimum size for that array of short integer is 2 bytes and </p>
<blockquote>
<p>The actual representation of values is
determined by the machine architecture
(strictly speaking, by the C
implementation). The actual size can
be accessed through the itemsize
attribute.</p>
</blockquote>
<p>@<a href="#120449" rel="nofollow">Arnav</a>: I suggest that your code should check the size of each Type code and choose the corresponding 2-byte type that is specific to the underlying system. </p>
| 0 | 2008-09-23T11:38:59Z | [
"python",
"memory-management",
"short"
] |
Short Integers in Python | 120,250 | <p>Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. </p>
<p>So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?</p>
| 10 | 2008-09-23T10:35:09Z | 120,924 | <p>If you're doing any sort of manipulation of this huge dataset, you'll probably want to use <a href="http://numpy.scipy.org/" rel="nofollow" title="Numpy Home Page">Numpy</a>, which has support for a wide variety of numeric types, and efficient operations on arrays of them.</p>
| 4 | 2008-09-23T13:20:30Z | [
"python",
"memory-management",
"short"
] |
SVG rendering in a PyGame application | 120,584 | <p>In a <a href="http://www.pygame.org/">pyGame</a> application, I would like to render resolution-free GUI widgets described in SVG.</p>
<p>What tool and/or library can I use to reach this goal ?</p>
<p>(I like the <a href="http://ocemp.sourceforge.net/gui.html">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)</p>
| 17 | 2008-09-23T12:13:14Z | 120,794 | <p>You can use <a href="http://www.cairographics.org/" rel="nofollow">Cairo</a> (with PyCairo), which has support for rendering SVGs. The PyGame webpage has a <a href="http://www.pygame.org/wiki/CairoPygame" rel="nofollow">HOWTO</a> for rendering into a buffer with a Cairo, and using that buffer directly with PyGame.</p>
| 3 | 2008-09-23T12:52:32Z | [
"python",
"svg",
"widget",
"pygame"
] |
SVG rendering in a PyGame application | 120,584 | <p>In a <a href="http://www.pygame.org/">pyGame</a> application, I would like to render resolution-free GUI widgets described in SVG.</p>
<p>What tool and/or library can I use to reach this goal ?</p>
<p>(I like the <a href="http://ocemp.sourceforge.net/gui.html">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)</p>
| 17 | 2008-09-23T12:13:14Z | 121,651 | <p>I realise this doesn't exactly answer your question, but there's a library called <a href="http://www.supereffective.org/?p=14" rel="nofollow">Squirtle</a> that will render SVG files using either Pyglet or PyOpenGL.</p>
| 3 | 2008-09-23T15:16:51Z | [
"python",
"svg",
"widget",
"pygame"
] |
SVG rendering in a PyGame application | 120,584 | <p>In a <a href="http://www.pygame.org/">pyGame</a> application, I would like to render resolution-free GUI widgets described in SVG.</p>
<p>What tool and/or library can I use to reach this goal ?</p>
<p>(I like the <a href="http://ocemp.sourceforge.net/gui.html">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)</p>
| 17 | 2008-09-23T12:13:14Z | 121,653 | <p>Cairo cannot render SVG out of the box.
It seems we have to use librsvg.</p>
<p>Just found those two pages:</p>
<ul>
<li><a href="http://www.cairographics.org/cookbook/librsvgpython/" rel="nofollow">Rendering SVG with libRSVG,Python and c-types</a> </li>
<li><a href="http://www.cairographics.org/pyrsvg/" rel="nofollow">How to use librsvg from Python</a></li>
</ul>
<p>Something like this should probably work (render <strong>test.svg</strong> to <strong>test.png</strong>):</p>
<pre><code>import cairo
import rsvg
WIDTH, HEIGHT = 256, 256
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
ctx = cairo.Context (surface)
svg = rsvg.Handle(file="test.svg")
svg.render_cairo(ctx)
surface.write_to_png("test.png")
</code></pre>
| 2 | 2008-09-23T15:17:06Z | [
"python",
"svg",
"widget",
"pygame"
] |
SVG rendering in a PyGame application | 120,584 | <p>In a <a href="http://www.pygame.org/">pyGame</a> application, I would like to render resolution-free GUI widgets described in SVG.</p>
<p>What tool and/or library can I use to reach this goal ?</p>
<p>(I like the <a href="http://ocemp.sourceforge.net/gui.html">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)</p>
| 17 | 2008-09-23T12:13:14Z | 152,222 | <p><a href="http://paul.giannaros.org/sandbox_pygamesvg" rel="nofollow">pygamesvg</a> seems to do what you want (though I haven't tried it).</p>
| 3 | 2008-09-30T08:24:24Z | [
"python",
"svg",
"widget",
"pygame"
] |
SVG rendering in a PyGame application | 120,584 | <p>In a <a href="http://www.pygame.org/">pyGame</a> application, I would like to render resolution-free GUI widgets described in SVG.</p>
<p>What tool and/or library can I use to reach this goal ?</p>
<p>(I like the <a href="http://ocemp.sourceforge.net/gui.html">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)</p>
| 17 | 2008-09-23T12:13:14Z | 341,742 | <p>This is a complete example which combines hints by other people here.
It should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0.</p>
<pre><code>#!/usr/bin/python
import array
import math
import cairo
import pygame
import rsvg
WIDTH = 512
HEIGHT = 512
data = array.array('c', chr(0) * WIDTH * HEIGHT * 4)
surface = cairo.ImageSurface.create_for_data(
data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
svg = rsvg.Handle(file="test.svg")
ctx = cairo.Context(surface)
svg.render_cairo(ctx)
screen = pygame.display.get_surface()
image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB")
screen.blit(image, (0, 0))
pygame.display.flip()
clock = pygame.time.Clock()
while True:
clock.tick(15)
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit
</code></pre>
| 11 | 2008-12-04T19:23:54Z | [
"python",
"svg",
"widget",
"pygame"
] |
SVG rendering in a PyGame application | 120,584 | <p>In a <a href="http://www.pygame.org/">pyGame</a> application, I would like to render resolution-free GUI widgets described in SVG.</p>
<p>What tool and/or library can I use to reach this goal ?</p>
<p>(I like the <a href="http://ocemp.sourceforge.net/gui.html">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)</p>
| 17 | 2008-09-23T12:13:14Z | 4,950,448 | <p>The last comment crashed when I ran it because svg.render_cairo() is expecting a cairo context and not a cairo surface. I created and tested the following function and it seems to run fine on my system.</p>
<pre><code>import array,cairo, pygame,rsvg
def loadsvg(filename,surface,position):
WIDTH = surface.get_width()
HEIGHT = surface.get_height()
data = array.array('c', chr(0) * WIDTH * HEIGHT * 4)
cairosurface = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)
svg = rsvg.Handle(filename)
svg.render_cairo(cairo.Context(cairosurface))
image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB")
surface.blit(image, position)
WIDTH = 800
HEIGHT = 600
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
screen = pygame.display.get_surface()
loadsvg("test.svg",screen,(0,0))
pygame.display.flip()
clock = pygame.time.Clock()
while True:
clock.tick(15)
event = pygame.event.get()
for e in event:
if e.type == 12:
raise SystemExit
</code></pre>
| 1 | 2011-02-09T21:06:29Z | [
"python",
"svg",
"widget",
"pygame"
] |
SVG rendering in a PyGame application | 120,584 | <p>In a <a href="http://www.pygame.org/">pyGame</a> application, I would like to render resolution-free GUI widgets described in SVG.</p>
<p>What tool and/or library can I use to reach this goal ?</p>
<p>(I like the <a href="http://ocemp.sourceforge.net/gui.html">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)</p>
| 17 | 2008-09-23T12:13:14Z | 26,188,526 | <p>Based on other answers, here's a function to read a SVG file into a pygame image - including correcting color channel order and scaling:</p>
<pre><code>def pygame_svg( svg_file, scale=1 ):
svg = rsvg.Handle(file=svg_file)
width, height= map(svg.get_property, ("width", "height"))
width*=scale; height*=scale
data = array.array('c', chr(0) * width * height * 4)
surface = cairo.ImageSurface.create_for_data( data, cairo.FORMAT_ARGB32, width, height, width*4)
ctx = cairo.Context(surface)
ctx.scale(scale, scale)
svg.render_cairo(ctx)
#seemingly, cairo and pygame expect channels in a different order...
#if colors/alpha are funny, mess with the next lines
import numpy
data= numpy.fromstring(data, dtype='uint8')
data.shape= (height, width, 4)
c= data.copy()
data[::,::,0]=c[::,::,1]
data[::,::,1]=c[::,::,0]
data[::,::,2]=c[::,::,3]
data[::,::,3]=c[::,::,2]
image = pygame.image.frombuffer(data.tostring(), (width, height),"ARGB")
return image
</code></pre>
| 0 | 2014-10-04T00:43:37Z | [
"python",
"svg",
"widget",
"pygame"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 120,676 | <p>You can use</p>
<pre><code>os.listdir(path)
</code></pre>
<p>For reference and more os functions look here:</p>
<ul>
<li>Python 2 docs: <a href="https://docs.python.org/2/library/os.html#os.listdir">https://docs.python.org/2/library/os.html#os.listdir</a></li>
<li>Python 3 docs: <a href="https://docs.python.org/3.4/library/os.html#os.listdir">https://docs.python.org/3.4/library/os.html#os.listdir</a></li>
</ul>
| 370 | 2008-09-23T12:32:00Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 120,692 | <pre><code>import os
for filename in os.listdir("C:\\temp"):
print filename
</code></pre>
| 74 | 2008-09-23T12:34:07Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 120,695 | <p>Try this:</p>
<pre><code>import os
for top, dirs, files in os.walk('./'):
for nm in files:
print os.path.join(top, nm)
</code></pre>
| 9 | 2008-09-23T12:34:34Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 120,701 | <p>This is a way to traverse every file and directory in a directory tree:</p>
<pre><code>import os
for dirname, dirnames, filenames in os.walk('.'):
# print path to all subdirectories first.
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# print path to all filenames.
for filename in filenames:
print(os.path.join(dirname, filename))
# Advanced usage:
# editing the 'dirnames' list will stop os.walk() from recursing into there.
if '.git' in dirnames:
# don't go into any .git directories.
dirnames.remove('.git')
</code></pre>
| 503 | 2008-09-23T12:35:46Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 120,948 | <p>Here's a helper function I use quite often:</p>
<pre><code>import os
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
</code></pre>
| 63 | 2008-09-23T13:23:29Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 11,753,937 | <p>I wrote a long version, with all the options I might need: <a href="http://sam.nipl.net/code/python/find.py" rel="nofollow">http://sam.nipl.net/code/python/find.py</a></p>
<p>I guess it will fit here too:</p>
<pre><code>#!/usr/bin/env python
import os
import sys
def ls(dir, hidden=False, relative=True):
nodes = []
for nm in os.listdir(dir):
if not hidden and nm.startswith('.'):
continue
if not relative:
nm = os.path.join(dir, nm)
nodes.append(nm)
nodes.sort()
return nodes
def find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True):
root = os.path.join(root, '') # add slash if not there
for parent, ldirs, lfiles in os.walk(root, topdown=topdown):
if relative:
parent = parent[len(root):]
if dirs and parent:
yield os.path.join(parent, '')
if not hidden:
lfiles = [nm for nm in lfiles if not nm.startswith('.')]
ldirs[:] = [nm for nm in ldirs if not nm.startswith('.')] # in place
if files:
lfiles.sort()
for nm in lfiles:
nm = os.path.join(parent, nm)
yield nm
def test(root):
print "* directory listing, with hidden files:"
print ls(root, hidden=True)
print
print "* recursive listing, with dirs, but no hidden files:"
for f in find(root, dirs=True):
print f
print
if __name__ == "__main__":
test(*sys.argv[1:])
</code></pre>
| 2 | 2012-08-01T06:47:52Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 12,572,822 | <p>If you need globbing abilities, there's a module for that as well. For example:</p>
<pre><code>import glob
glob.glob('./[0-9].*')
</code></pre>
<p>will return something like:</p>
<pre><code>['./1.gif', './2.txt']
</code></pre>
<p>See the documentation <a href="http://docs.python.org/library/glob.html">here</a>.</p>
| 10 | 2012-09-24T20:58:14Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 13,528,334 | <pre><code>#import modules
import os
_CURRENT_DIR = '.'
def rec_tree_traverse(curr_dir, indent):
"recurcive function to traverse the directory"
#print "[traverse_tree]"
try :
dfList = [os.path.join(curr_dir, f_or_d) for f_or_d in os.listdir(curr_dir)]
except:
print "wrong path name/directory name"
return
for file_or_dir in dfList:
if os.path.isdir(file_or_dir):
#print "dir : ",
print indent, file_or_dir,"\\"
rec_tree_traverse(file_or_dir, indent*2)
if os.path.isfile(file_or_dir):
#print "file : ",
print indent, file_or_dir
#end if for loop
#end of traverse_tree()
def main():
base_dir = _CURRENT_DIR
rec_tree_traverse(base_dir," ")
raw_input("enter any key to exit....")
#end of main()
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2012-11-23T11:38:05Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 25,390,299 | <p>FYI Add a filter of extension or ext file
import os</p>
<pre><code>path = '.'
for dirname, dirnames, filenames in os.walk(path):
# print path to all filenames with extension py.
for filename in filenames:
fname_path = os.path.join(dirname, filename)
fext = os.path.splitext(fname_path)[1]
if fext == '.py':
print fname_path
else:
continue
</code></pre>
| 0 | 2014-08-19T18:17:06Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 27,713,560 | <p>A nice one liner to list only the files recursively. I used this in my setup.py package_data directive:</p>
<pre><code>import os
[os.path.join(x[0],y) for x in os.walk('<some_directory>') for y in x[2]]
</code></pre>
<p>I know it's not the answer to the question, but may come in handy</p>
| 1 | 2014-12-30T22:35:24Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 30,471,791 | <p>A recursive implementation</p>
<pre><code>import os
def scan_dir(dir):
for name in os.listdir(dir):
path = os.path.join(dir, name)
if os.path.isfile(path):
print path
else:
scan_dir(path)
</code></pre>
| 3 | 2015-05-27T01:45:10Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 30,878,347 | <pre><code>import os, sys
#open files in directory
path = "My Documents"
dirs = os.listdir( path )
# print the files in given directory
for file in dirs:
print (file)
</code></pre>
| 0 | 2015-06-16T21:15:27Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 35,628,738 | <p>If figured I'd throw this in. Simple and dirty way to do wildcard searches.</p>
<pre><code>import re
import os
[a for a in os.listdir(".") if re.search("^.*\.py$",a)]
</code></pre>
| 0 | 2016-02-25T13:31:56Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 38,609,425 | <p>For files in current working directory without specifying a path:</p>
<pre><code>import os
os.listdir(os.getcwd())
</code></pre>
<p>I still think this is quite clumsy, if anyone knows a shorter equivalent please comment</p>
| 2 | 2016-07-27T09:47:07Z | [
"python",
"filesystems"
] |
Directory listing in Python | 120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| 413 | 2008-09-23T12:28:19Z | 38,941,184 | <h1>For Python 2</h1>
<pre><code>#!/bin/python2
import os
def scan_dir(path):
print map(os.path.abspath, os.listdir(pwd))
</code></pre>
<h1>For Python 3</h1>
<p>For filter and map, you need wrap them with list()</p>
<pre><code>#!/bin/python3
import os
def scan_dir(path):
print(list(map(os.path.abspath, os.listdir(pwd))))
</code></pre>
<p>The recommendation now is that you replace your usage of map and filter with generators expressions or list comprehensions:</p>
<pre><code>#!/bin/python
import os
def scan_dir(path):
print([os.path.abspath(f) for f in os.listdir(path)])
</code></pre>
| 0 | 2016-08-14T10:11:03Z | [
"python",
"filesystems"
] |
Python subprocess issue with ampersands | 120,657 | <p>I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.</p>
<p>The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?</p>
<p>To clarify from current responses:</p>
<ol>
<li>I am using the subprocess module</li>
<li>I am passing the command line + arguments in as a list</li>
<li>The issue is with the path to the command itself, not any of the arguments</li>
<li>I've tried quoting the command. It causes a <code>[Error 123] The filename, directory name, or volume label syntax is incorrect</code> error</li>
<li>I'm using no shell argument (so <code>shell=false</code>) </li>
<li>In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin</li>
<li>It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.</li>
<li>The command that is failing is: </li>
</ol>
<blockquote>
<p>p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)</p>
</blockquote>
<p>when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.</p>
| 3 | 2008-09-23T12:28:39Z | 120,705 | <p>A proper answer will need more information than that. What are you actually doing? How does it fail? Are you using the subprocess module? Are you passing a list of arguments and shell=False (or no shell argument) or are you actually invoking the shell?</p>
| 1 | 2008-09-23T12:36:18Z | [
"python",
"windows",
"subprocess",
"command-line-arguments"
] |
Python subprocess issue with ampersands | 120,657 | <p>I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.</p>
<p>The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?</p>
<p>To clarify from current responses:</p>
<ol>
<li>I am using the subprocess module</li>
<li>I am passing the command line + arguments in as a list</li>
<li>The issue is with the path to the command itself, not any of the arguments</li>
<li>I've tried quoting the command. It causes a <code>[Error 123] The filename, directory name, or volume label syntax is incorrect</code> error</li>
<li>I'm using no shell argument (so <code>shell=false</code>) </li>
<li>In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin</li>
<li>It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.</li>
<li>The command that is failing is: </li>
</ol>
<blockquote>
<p>p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)</p>
</blockquote>
<p>when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.</p>
| 3 | 2008-09-23T12:28:39Z | 120,706 | <p>Make sure you are using lists and no shell expansion:</p>
<pre><code>subprocess.Popen(['command', 'argument1', 'argument2'], shell=False)
</code></pre>
| 5 | 2008-09-23T12:36:19Z | [
"python",
"windows",
"subprocess",
"command-line-arguments"
] |
Python subprocess issue with ampersands | 120,657 | <p>I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.</p>
<p>The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?</p>
<p>To clarify from current responses:</p>
<ol>
<li>I am using the subprocess module</li>
<li>I am passing the command line + arguments in as a list</li>
<li>The issue is with the path to the command itself, not any of the arguments</li>
<li>I've tried quoting the command. It causes a <code>[Error 123] The filename, directory name, or volume label syntax is incorrect</code> error</li>
<li>I'm using no shell argument (so <code>shell=false</code>) </li>
<li>In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin</li>
<li>It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.</li>
<li>The command that is failing is: </li>
</ol>
<blockquote>
<p>p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)</p>
</blockquote>
<p>when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.</p>
| 3 | 2008-09-23T12:28:39Z | 120,708 | <p>Try quoting the argument that contains the &</p>
<pre><code>wget "http://foo.com/?bar=baz&amp;baz=bar"
</code></pre>
<p>Is usually what has to be done in a Linux shell</p>
| 1 | 2008-09-23T12:36:32Z | [
"python",
"windows",
"subprocess",
"command-line-arguments"
] |
Python subprocess issue with ampersands | 120,657 | <p>I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.</p>
<p>The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?</p>
<p>To clarify from current responses:</p>
<ol>
<li>I am using the subprocess module</li>
<li>I am passing the command line + arguments in as a list</li>
<li>The issue is with the path to the command itself, not any of the arguments</li>
<li>I've tried quoting the command. It causes a <code>[Error 123] The filename, directory name, or volume label syntax is incorrect</code> error</li>
<li>I'm using no shell argument (so <code>shell=false</code>) </li>
<li>In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin</li>
<li>It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.</li>
<li>The command that is failing is: </li>
</ol>
<blockquote>
<p>p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)</p>
</blockquote>
<p>when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.</p>
| 3 | 2008-09-23T12:28:39Z | 120,782 | <p>To answer my own question:</p>
<p>Quoting the actual command when passing the parameters as a list doesn't work correctly (command is first item of list) so to solve the issue I turned the list into a space separated string and passed that into subprocess instead.</p>
<p>Better solutions still welcomed.</p>
| 0 | 2008-09-23T12:49:55Z | [
"python",
"windows",
"subprocess",
"command-line-arguments"
] |
Python subprocess issue with ampersands | 120,657 | <p>I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.</p>
<p>The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?</p>
<p>To clarify from current responses:</p>
<ol>
<li>I am using the subprocess module</li>
<li>I am passing the command line + arguments in as a list</li>
<li>The issue is with the path to the command itself, not any of the arguments</li>
<li>I've tried quoting the command. It causes a <code>[Error 123] The filename, directory name, or volume label syntax is incorrect</code> error</li>
<li>I'm using no shell argument (so <code>shell=false</code>) </li>
<li>In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin</li>
<li>It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.</li>
<li>The command that is failing is: </li>
</ol>
<blockquote>
<p>p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)</p>
</blockquote>
<p>when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.</p>
| 3 | 2008-09-23T12:28:39Z | 120,992 | <p>"escaping the ampersand with ^"</p>
<p>Are you sure <code>^</code> is an escape character to Windows? Shouldn't you use <code>\</code>?</p>
| 1 | 2008-09-23T13:29:31Z | [
"python",
"windows",
"subprocess",
"command-line-arguments"
] |
Python subprocess issue with ampersands | 120,657 | <p>I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.</p>
<p>The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?</p>
<p>To clarify from current responses:</p>
<ol>
<li>I am using the subprocess module</li>
<li>I am passing the command line + arguments in as a list</li>
<li>The issue is with the path to the command itself, not any of the arguments</li>
<li>I've tried quoting the command. It causes a <code>[Error 123] The filename, directory name, or volume label syntax is incorrect</code> error</li>
<li>I'm using no shell argument (so <code>shell=false</code>) </li>
<li>In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin</li>
<li>It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.</li>
<li>The command that is failing is: </li>
</ol>
<blockquote>
<p>p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)</p>
</blockquote>
<p>when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.</p>
| 3 | 2008-09-23T12:28:39Z | 20,922,266 | <p>I try a situation as following:</p>
<pre><code>exe = 'C:/Program Files (x86)/VideoLAN/VLC/VLC.exe'
url = 'http://translate.google.com/translate_tts?tl=en&q=hello+world'
subprocess.Popen([exe, url.replace("&","^&")],shell=True)
</code></pre>
<p>This does work.</p>
| 0 | 2014-01-04T14:36:14Z | [
"python",
"windows",
"subprocess",
"command-line-arguments"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 120,956 | <p>The problem with tabs is that they are invisible, and people can never agree on the width of tabs. When you mix tabs and spaces, and you set tabstops at something other than Python (which uses tabstops every 8 spaces) you will be seeing the code in a different layout than Python sees it. And because the layout determines blocks, you will be seeing different logic. It leads to subtle bugs.</p>
<p>If you insist on defying PEP 8 and using tabs -- or worse, mixing tabs and spaces -- at least always run python with the '-tt' argument, which makes <em>inconsistent</em> indentation (sometimes a tab, sometimes a space for the same indentation level) an error. Also, if possible, set your editor to display tabs differently. But really, the best approach is not to use tabs, period.</p>
| 25 | 2008-09-23T13:24:26Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 120,969 | <p>The universal problem with tabs is that they can be represented differently in different environment.<br />
In a given editor, a tab might be 8 spaces or it might be 2.<br />
In some editors, you can control this, while in others you can't.</p>
<p>Another issue with tabs is how they are represented in printed output. I believe most printers interpret a tab as 8 spaces.</p>
<p>With spaces, there is no doubt. Everything will line up as the author intended.</p>
| -2 | 2008-09-23T13:25:57Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 120,996 | <p>The most significant advantage I can tell of spaces over tabs is that a lot of programmers and projects use a set number of columns for the source code, and if someone commits a change with their tabstop set to 2 spaces and the project uses 4 spaces as the tabstop the long lines are going to be too long for other people's editor window. I agree that tabs are easier to work with but I think spaces are easier for collaboration, which is important on a large open source project like Python.</p>
| 0 | 2008-09-23T13:30:23Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 121,036 | <p>Since python relies on indentation in order to recognize program structure, a clear way to identify identation is required. This is the reason to pick either spaces or tabs.</p>
<p>However, python also has a strong philosophy of only having one way to do things, therefore there should be an official recommendation for one way to do indentation.</p>
<p>Both spaces and tabs pose unique challenges for an editor to handle as indentation. The handling of tabs themselves is not uniform across editors or even user settings. Since spaces are not configurable, they pose the more logical choice as they guarantee that the outcome will look everywhere the same.</p>
| 1 | 2008-09-23T13:35:42Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 121,126 | <p>You can have your cake and eat it to. Set your editor to expand tabs into spaces automatically.</p>
<p>(That would be <code>:set expandtab</code> in Vim.)</p>
| 0 | 2008-09-23T13:52:25Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 121,481 | <p>The reason for spaces is that tabs are optional. Spaces are the actual lowest-common denominator in punctuation.</p>
<p>Every decent text editor has a "replace tabs with spaces" and many people use this. But not always.</p>
<p>While some text editors might replace a run of spaces with a tab, this is really rare.</p>
<p><strong>Bottom Line</strong>. You can't go wrong with spaces. You <em>might</em> go wrong with tabs. So don't use tabs and reduce the risk of mistakes.</p>
| 28 | 2008-09-23T14:45:39Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 121,671 | <p>The answer was given right there in the PEP [ed: this passage has been edited out in <a href="https://hg.python.org/peps/rev/fb24c80e9afb#l1.75">2013</a>]. I quote:</p>
<blockquote>
<p>The <strong>most popular</strong> way of indenting Python is with spaces only.</p>
</blockquote>
<p>What other underlying reason do you need?</p>
<p>To put it less bluntly: Consider also the scope of the PEP as stated in the very first paragraph:</p>
<blockquote>
<p>This document gives coding conventions for the Python code comprising the standard library in the main Python distribution.</p>
</blockquote>
<p>The intention is to make <em>all code that goes in the official python distribution</em> consistently formatted (I hope we can agree that this is universally a Good Thingâ¢).</p>
<p>Since the decision between spaces and tabs for an individual programmer is a) really a matter of taste and b) easily dealt with by technical means (editors, conversion scripts, etc.), there is a clear way to end all discussion: chose one.</p>
<p>Guido was the one to choose. He didn't even have to give a reason, but he still did by referring to empirical data.</p>
<p>For all other purposes you can either take this PEP as a recommendation, or you can ignore it -- your choice, or your team's, or your team leaders.</p>
<p>But if I may give you one advice: don't mix'em ;-) [ed: Mixing tabs and spaces is no longer an option.]</p>
| 74 | 2008-09-23T15:19:27Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 143,995 | <p>The answer to the question is: PEP-8 wants to make a recommendation and has decided that since spaces are more popular it will strongly recommend spaces over tabs.</p>
<p><hr /></p>
<p>Notes on PEP-8</p>
<p>PEP-8 says <em>'Use 4 spaces per indentation level.'</em><br />
Its clear that this is the standard recommendation.</p>
<p><em>'For really old code that you don't want to mess up, you can continue to use 8-space tabs.'</em><br />
Its clear that there are SOME circumstances when tabs can be used.</p>
<p><em>'Never mix tabs and spaces.'</em><br />
This is a clear prohibition of mixing - I think we all agree on this. Python can detect this and often chokes. Using the -tt argument makes this an explicit error.</p>
<p><em>'The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only.'</em><br />
This clearly states that both are used. Just to be ultra-clear: You should still never mix spaces and tabs in same file.</p>
<p><em>'For new projects, spaces-only are strongly recommended over tabs.'</em><br />
This is a clear recommendation, and a strong one, but not a prohibition of tabs.</p>
<p><hr /></p>
<p>I can't find a good answer to my own question in PEP-8.
I use tabs, which I have used historically in other languages.
Python accepts source with exclusive use of tabs. That's good enough for me.</p>
<p>I thought I would have a go at working with spaces. In my editor, I configured a file type to use spaces exclusively and so it inserts 4 spaces if I press tab. If I press tab too many times, I have to delete the spaces! <strong>Arrgh!</strong> Four times as many deletes as tabs! My editor can't tell that I'm using 4 spaces for indents (although AN editor might be able to do this) and obviously insists on deleting the spaces one at a time.</p>
<p>Couldn't Python be told to consider tabs to be n spaces when its reading indentations?
If we could agree on 4 spaces per indentation and 4 spaces per tab and allow Python to accept this, then there would be no problems.<br />
We should find win-win solutions to problems.</p>
| 7 | 2008-09-27T16:56:59Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 144,096 | <p>The main problems with indentation occur when you mix tabs and spaces. Obviously this doesn't tell you which you should choose, but it is a good reason to to recommend one, even if you pick it by flipping a coin.</p>
<p>However, IMHO there are a few minor reasons to favour spaces over tabs:</p>
<ul>
<li><p>Different tools. Sometimes code gets displayed outside of a programmer's editor. Eg. posted to a newsgroup or forum. Spaces generally do better than tabs here - everywhere spaces would get mangled, tabs do as well, but not vice-versa.</p></li>
<li><p>Programmers see the source differently. This is deeply subjective - its either the main benefit of tabs, or a reason to avoid them depending on which side you're on. On the plus side, developers can view the source with their preferred indentation, so a developer preferring 2-space indent can work with an 8-space developer on the same source and still see it as they like. The downside is that there are repercussions to this - some people like 8-space because it gives very visible feedback that they're too deeply nested - they may see code checked in by the 2-indenter constantly wrapping in their editor. Having every developer see the code the same way leads to more consistency wrt line lengths, and other matters too.</p></li>
<li><p>Continued line indentation. Sometimes you want to indent a line to indicate it is carried from the previous one. eg.</p>
<pre><code>def foo():
x = some_function_with_lots_of_args(foo, bar, baz,
xyzzy, blah)
</code></pre>
<p>If using tabs, theres no way to align this for people using different tabstops in their editor without mixing spaces and tabs. This effectively kills the above benefit.</p></li>
</ul>
<p>Obviously though, this is a deeply religious issue, which programming is plagued with. The most important issue is that we should choose one - even if thats not the one you favour. Sometimes I think that the biggest advantage of significant indentation is that at least we're spared brace placement flamewars.</p>
<p>Also worth reading is <a href="http://www.jwz.org/doc/tabs-vs-spaces.html">this</a> article by Jamie Zawinski on the issue.</p>
| 19 | 2008-09-27T17:32:09Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 144,133 | <p><a href="http://www.jwz.org/doc/tabs-vs-spaces.html" rel="nofollow">JWZ says it best</a>:</p>
<blockquote>
<p>When [people are] reading code, and when they're done writing new code, they care about how many screen columns by which the code tends to indent when a new scope (or sexpr, or whatever) opens...</p>
<p>...My opinion is that the best way to solve the technical issues is to mandate that the ASCII #9 TAB character never appear in disk files: program your editor to expand TABs to an appropriate number of spaces before writing the lines to disk...</p>
<p>...This assumes that you never use tabs in places where they are actually significant, like in string or character constants, but I never do that: when it matters that it is a tab, I always use '\t' instead. </p>
</blockquote>
| 2 | 2008-09-27T17:50:59Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 872,883 | <p>I personally don't agree with spaces over tabs. To me, tabs are a document layout character/mechanism while spaces are for content or delineation between commands in the case of code.</p>
<p>I have to agree with Jim's comments that tabs aren't really the issue, it is people and how they want to mix tabs and spaces.</p>
<p>That said, I've forced myself to use spaces for the sake of convention. I value consistency over personal preference.</p>
| 23 | 2009-05-16T17:41:35Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 5,048,130 | <p>Well well, seems like everybody is strongly biased towards spaces.
I use tabs exclusively. I know very well why.</p>
<p>Tabs are actually a cool invention, that came <strong>after</strong> spaces. It allows you to indent without pushing space millions of times or using a fake tab (that produces spaces).</p>
<p>I really don't get why everybody is discriminating the use of tabs.
It is very much like old people discriminating younger people for choosing a newer more efficient technology and complaining that pulse dialing works on <strong>every phone</strong>, not just on these fancy new ones. "Tone dialing doesn't work on every phone, that's why it is wrong".</p>
<p>Your editor cannot handle tabs properly? Well, get a <strong>modern</strong> editor. Might be darn time, we are now in the 21st century and the time when an editor was a high tech complicated piece of software is long past. We have now tons and tons of editors to choose from, all of them that support tabs just fine. Also, you can define how much a tab should be, a thing that you cannot do with spaces.
Cannot see tabs? What is that for an argument? Well, you cannot see spaces neither!</p>
<p>May I be so bold to suggest to get a better editor? One of these high tech ones, that were released some 10 years ago already, that <strong>display invisible characters</strong>? (sarcasm off)</p>
<p>Using spaces causes a lot more deleting and formatting work. That is why (and all other people that know this and agree with me) use tabs for Python.</p>
<p>Mixing tabs and spaces is a no-no and no argument about that. That is a mess and can never work.</p>
| 34 | 2011-02-19T00:56:16Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 6,965,294 | <p>On the discussion between <a href="http://stackoverflow.com/questions/120926/why-does-python-pep-8-strongly-recommend-spaces-over-tabs-for-indentation/120956#120956">Jim and Thomas Wouters</a> in the comments.</p>
<p>The issue was... since the width of tabs and spaces both can vary -- and since programmers can't agree on either width -- why is it that tabs bear the blame.</p>
<p>I agree with Jim on that -- tabs are NOT evil in and of themselves. But there is a problem...</p>
<p>With spaces I can control how <strong><em>"MY OWN CODE"</em></strong> looks in EVERY editor in the world. If I use 4 spaces -- then no matter what editor you open my code in, it will have the same distance from the left margin. With tabs I am at the mercy of the tab-width setting for the editor -- even for MY OWN CODE. And I don't like that.</p>
<p>So while it is true that even spaces can't guarantee consistency -- they at least afford you more control over the look of your OWN code everywhere -- something that tabs can't.</p>
<p>I think it's NOT the consistency in the programmers writing the code -- but the consistency in editors showing that code -- that spaces make easier to achieve (and impose).</p>
| -2 | 2011-08-06T06:53:51Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 8,747,788 | <p>I've always used tabs in my code. That said, I've recently found a reason to use spaces: When developing on my Nokia N900 internet tablet, I now had a keyboard without a tab key. This forced me to either copy and paste tabs or re-write my code with spaces.
I've run into the same problem with other phones. Granted, this is not a standard use of Python, but something to keep in mind.</p>
| 2 | 2012-01-05T18:31:35Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 15,076,562 | <p>Besides all the other reasons already named (consistency, never mixing spaces and tabs etc) I believe there are a few more reasons for the 4 spaces convention to note. These only apply to Python (and maybe other languages where indentation has meaning). Tabs may be nicer in other languages, depending on individual preferences.</p>
<ol>
<li><p>If an editor doesn't show tabs (which happens, depending on the configuration, in quite a few), another author might assume that your code uses 4 spaces, b/c almost all of the Python code being publicly available does; if that same editor happens to have a tab width of 4, nasty things may happen - at least, that poor person will lose time over an indentation issue that would have been very easy to avoid by sticking to the convention. So for me, the number one reason is to avoid bugs with consistency.</p></li>
<li><p>Reframing the question of which is better, tabs or spaces, one should ask which the advantages of tabs are; I've seen plenty posts praising tabs, but few compelling arguments for them; good editors like emacs, vi(m), kate, ... do proper indentation depending on the semantics of your code - even without tabs; the same editors can easily be configured to unindent on backspace etc.</p></li>
<li><p>Some people have very strong preferences when it comes to their freedom in deciding the look/ layout of code; others value consistency over this freedom. Python drastically reduces this freedom by dictating that indentation is used for blocks etc. This may be seen as a bug or a feature, but it sort of comes with choosing Python. Personally, I like this consistency - when starting to code on a new project, at least the layout is close to what I'm used to, so it's fairly easy to read. Almost always.</p></li>
<li><p>Using spaces for indentation allows "layout tricks" that may facilitate to comprehend code; some examples of these are listed in PEP8; eg.</p>
<pre><code>foo = long_function_name(var_one, var_two,
var_three, var_four)
# the same for lists
a_long_list = [1,
2,
# ...
79]
# or dictionaries
a_dict = {"a_key": "a_value",
"another_key": "another_value"}
</code></pre>
<p>Of course, the above can also be written nicely as</p>
<pre><code>foo = long_function_name(
var_one, var_two,
var_three, var_four)
# the same for lists
a_long_list = [
1,
2,
# ...
79]
# or dictionaries
a_dict = {
"a_key": "a_value",
"another_key": "another_value"}
</code></pre>
<p>However, the latter takes more lines of code and less lines are sometimes argued to be better (b/c you get more on a single screen). But if you like alignment, spaces (preferably assisted by a good editor) give you, in a sense, more freedom in Python than tabs. [Well, I guess some editors allow you to do the same w/ tabs ;) - but with spaces, all of them do...]</p></li>
<li><p>Coming back to the same argument that everybody else makes - PEP 8 dictates (ok, strongly recommends) spaces. If coming to a project that uses tabs only, of course, you have little choice. But because of the establishment of the PEP 8 conventions, almost all Python programmers are used to this style. This makes it sooooo much easier to find a consensus on a style that is accepted by most programmers... and having individuals agree on style might be very hard otherwise.</p></li>
<li><p>Tools that help enforcing style are usually aware of PEP 8 without extra effort. That's not a great reason, but it's just nice to have things work ~out of the box.</p></li>
</ol>
| -1 | 2013-02-25T21:11:22Z | [
"python",
"indentation"
] |
Why does Python pep-8 strongly recommend spaces over tabs for indentation? | 120,926 | <p>I see on Stack Overflow and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain.</p>
<p>Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.</p>
| 90 | 2008-09-23T13:20:34Z | 18,034,554 | <p>Note that the use of tabs confuses another aspect of PEP 8:</p>
<blockquote>
<p>Limit all lines to a maximum of 79 characters.</p>
</blockquote>
<p>Let's say, hypothetically, that you use a tab width of 2 and I use a tab width of 8. You write all your code so your longest lines reach 79 characters, then I start to work on your file. Now I've got hard-to-read code because (as the PEP states):</p>
<blockquote>
<p>The default wrapping in most tools disrupts the visual structure of the code</p>
</blockquote>
<p>If we all use 4 spaces, it's ALWAYS the same. Anyone whose editor can support an 80 character width can comfortably read the code. <em>Note: The 80 character limit is a holy war in and of itself, so let's not start that here.</em></p>
<p>Any non-sucky editor should have an option to use spaces as if they were tabs (both inserting and deleting), so that really shouldn't be a valid argument.</p>
| 7 | 2013-08-03T15:49:14Z | [
"python",
"indentation"
] |
How can I normalize a URL in python | 120,951 | <p>I'd like to know do I normalize a URL in python. </p>
<p>For example, If I have a url string like : "http://www.example.com/foo goo/bar.html"</p>
<p>I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.</p>
| 55 | 2008-09-23T13:23:50Z | 120,959 | <pre><code>import urlparse, urllib
def myquote(url):
parts= urlparse.urlparse(url)
return urlparse.urlunparse(parts[:2] + urllib.quote(parts[2]) + parts[3:])
</code></pre>
<p>This quotes only the path component.</p>
<p>Otherwise, you could do: <code>urllib.quote(url, safe=":/")</code></p>
| 9 | 2008-09-23T13:25:01Z | [
"python",
"url",
"normalization",
"normalize"
] |
How can I normalize a URL in python | 120,951 | <p>I'd like to know do I normalize a URL in python. </p>
<p>For example, If I have a url string like : "http://www.example.com/foo goo/bar.html"</p>
<p>I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.</p>
| 55 | 2008-09-23T13:23:50Z | 120,971 | <p>use <code>urllib.quote</code> or <code>urllib.quote_plus</code></p>
<p>From the <a href="http://docs.python.org/lib/module-urllib.html">urllib documentation</a>:</p>
<blockquote>
<p><strong>quote(string[, safe])</strong></p>
<p>Replace special characters in string
using the "%xx" escape. Letters,
digits, and the characters "_.-" are
never quoted. The optional safe
parameter specifies additional
characters that should not be quoted
-- its default value is '/'.</p>
<p>Example: <code>quote('/~connolly/')</code> yields <code>'/%7econnolly/'</code>. </p>
<p><strong>quote_plus(string[, safe])</strong></p>
<p>Like quote(), but also replaces spaces
by plus signs, as required for quoting
HTML form values. Plus signs in the
original string are escaped unless
they are included in safe. It also
does not have safe default to '/'.</p>
</blockquote>
<p>EDIT: Using urllib.quote or urllib.quote_plus on the whole URL will mangle it, as @<a href="#120959">ΤÎΩΤÎÎÎÎ¥</a> points out:</p>
<pre><code>>>> quoted_url = urllib.quote('http://www.example.com/foo goo/bar.html')
>>> quoted_url
'http%3A//www.example.com/foo%20goo/bar.html'
>>> urllib2.urlopen(quoted_url)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python25\lib\urllib2.py", line 124, in urlopen
return _opener.open(url, data)
File "c:\python25\lib\urllib2.py", line 373, in open
protocol = req.get_type()
File "c:\python25\lib\urllib2.py", line 244, in get_type
raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: http%3A//www.example.com/foo%20goo/bar.html
</code></pre>
<p>@<a href="#120959">ΤÎΩΤÎÎÎÎ¥</a> provides a function that uses <a href="http://docs.python.org/lib/module-urlparse.html">urlparse.urlparse and urlparse.urlunparse</a> to parse the url and only encode the path. This may be more useful for you, although if you're building the URL from a known protocol and host but with a suspect path, you could probably do just as well to avoid urlparse and just quote the suspect part of the URL, concatenating with known safe parts.</p>
| 18 | 2008-09-23T13:26:16Z | [
"python",
"url",
"normalization",
"normalize"
] |
How can I normalize a URL in python | 120,951 | <p>I'd like to know do I normalize a URL in python. </p>
<p>For example, If I have a url string like : "http://www.example.com/foo goo/bar.html"</p>
<p>I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.</p>
| 55 | 2008-09-23T13:23:50Z | 121,017 | <p>Have a look at this module: <a href="https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/urls.py">werkzeug.utils</a>. (now in <code>werkzeug.urls</code>)</p>
<p>The function you are looking for is called "url_fix" and works like this:</p>
<pre><code>>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')
'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'
</code></pre>
<p>It's implemented in Werkzeug as follows:</p>
<pre><code>import urllib
import urlparse
def url_fix(s, charset='utf-8'):
"""Sometimes you get an URL by a user that just isn't a real
URL because it contains unsafe characters like ' ' and so on. This
function can fix some of the problems in a similar way browsers
handle data entered by the user:
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')
'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'
:param charset: The target charset for the URL if the url was
given as unicode string.
"""
if isinstance(s, unicode):
s = s.encode(charset, 'ignore')
scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
path = urllib.quote(path, '/%')
qs = urllib.quote_plus(qs, ':&=')
return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
</code></pre>
| 60 | 2008-09-23T13:33:06Z | [
"python",
"url",
"normalization",
"normalize"
] |
How can I normalize a URL in python | 120,951 | <p>I'd like to know do I normalize a URL in python. </p>
<p>For example, If I have a url string like : "http://www.example.com/foo goo/bar.html"</p>
<p>I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.</p>
| 55 | 2008-09-23T13:23:50Z | 845,595 | <p><a href="http://svn.python.org/view/python/trunk/Lib/urllib.py?r1=71780&r2=71779&pathrev=71780">Real fix in Python 2.7 for that problem</a></p>
<p>Right solution was:</p>
<pre><code> # percent encode url, fixing lame server errors for e.g, like space
# within url paths.
fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]")
</code></pre>
<p>For more information see <a href="http://bugs.python.org/issue918368">Issue918368: "urllib doesn't correct server returned urls"</a></p>
| 46 | 2009-05-10T16:15:40Z | [
"python",
"url",
"normalization",
"normalize"
] |
How can I normalize a URL in python | 120,951 | <p>I'd like to know do I normalize a URL in python. </p>
<p>For example, If I have a url string like : "http://www.example.com/foo goo/bar.html"</p>
<p>I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.</p>
| 55 | 2008-09-23T13:23:50Z | 962,248 | <p>Because this page is a top result for Google searches on the topic, I think it's worth mentioning some work that has been done on URL normalization with Python that goes beyond urlencoding space characters. For example, dealing with default ports, character case, lack of trailing slashes, etc.</p>
<p>When the Atom syndication format was being developed, there was some discussion on how to normalize URLs into canonical format; this is documented in the article <a href="http://www.intertwingly.net/wiki/pie/PaceCanonicalIds">PaceCanonicalIds</a> on the Atom/Pie wiki. That article provides some good test cases.</p>
<p>I believe that one result of this discussion was Mark Nottingham's <a href="http://www.mnot.net/python/urlnorm.py">urlnorm.py</a> library, which I've used with good results on a couple projects. That script doesn't work with the URL given in this question, however. So a better choice might be <a href="http://intertwingly.net/blog/2004/08/04/Urlnorm">Sam Ruby's version of urlnorm.py</a>, which handles that URL, and all of the aforementioned test cases from the Atom wiki.</p>
| 12 | 2009-06-07T16:35:25Z | [
"python",
"url",
"normalization",
"normalize"
] |
How can I normalize a URL in python | 120,951 | <p>I'd like to know do I normalize a URL in python. </p>
<p>For example, If I have a url string like : "http://www.example.com/foo goo/bar.html"</p>
<p>I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.</p>
| 55 | 2008-09-23T13:23:50Z | 1,912,115 | <p>Just FYI, urlnorm has moved to github:
<a href="http://gist.github.com/246089" rel="nofollow">http://gist.github.com/246089</a></p>
| 3 | 2009-12-16T03:43:51Z | [
"python",
"url",
"normalization",
"normalize"
] |
How can I normalize a URL in python | 120,951 | <p>I'd like to know do I normalize a URL in python. </p>
<p>For example, If I have a url string like : "http://www.example.com/foo goo/bar.html"</p>
<p>I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.</p>
| 55 | 2008-09-23T13:23:50Z | 24,203,504 | <p>I encounter such an problem: need to quote the space only.</p>
<p><code>fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]")</code> do help, but it's too complicated.</p>
<p>So I used a simple way: <code>url = url.replace(' ', '%20')</code>, it's not perfect, but it's the simplest way and it works for this situation.</p>
| 1 | 2014-06-13T10:45:33Z | [
"python",
"url",
"normalization",
"normalize"
] |
Accessing object memory address | 121,396 | <p>When you call the <code>object.__repr__()</code> method in python you get something like this back: <code><__main__.Test object at 0x2aba1c0cf890></code>, is there any way to get a hold of the memory address if you overload <code>__repr__()</code>, other then calling <code>super(Class, obj).__repr__()</code> and regexing it out? </p>
| 89 | 2008-09-23T14:35:00Z | 121,422 | <p>Just use </p>
<pre><code>id(object)
</code></pre>
| 32 | 2008-09-23T14:37:24Z | [
"python",
"object",
"tostring",
"memory-address",
"repr"
] |
Accessing object memory address | 121,396 | <p>When you call the <code>object.__repr__()</code> method in python you get something like this back: <code><__main__.Test object at 0x2aba1c0cf890></code>, is there any way to get a hold of the memory address if you overload <code>__repr__()</code>, other then calling <code>super(Class, obj).__repr__()</code> and regexing it out? </p>
| 89 | 2008-09-23T14:35:00Z | 121,426 | <p>You can get something suitable for that purpose with:</p>
<pre><code>id(self)
</code></pre>
| 2 | 2008-09-23T14:38:01Z | [
"python",
"object",
"tostring",
"memory-address",
"repr"
] |
Accessing object memory address | 121,396 | <p>When you call the <code>object.__repr__()</code> method in python you get something like this back: <code><__main__.Test object at 0x2aba1c0cf890></code>, is there any way to get a hold of the memory address if you overload <code>__repr__()</code>, other then calling <code>super(Class, obj).__repr__()</code> and regexing it out? </p>
| 89 | 2008-09-23T14:35:00Z | 121,452 | <p>The <a href="https://docs.python.org/2/library/functions.html#id">Python manual</a> has this to say about id():</p>
<blockquote>
<p>Return the ``identity'' of an object.
This is an integer (or long integer)
which is guaranteed to be unique and
constant for this object during its
lifetime. Two objects with
non-overlapping lifetimes may have the
same id() value. (Implementation note:
this is the address of the object.)</p>
</blockquote>
<p>So in CPython, this will be the address of the object. No such guarantee for any other Python interpreter, though.</p>
<p>Note that if you're writing a C extension, you have full access to the internals of the Python interpreter, including access to the addresses of objects directly.</p>
| 116 | 2008-09-23T14:41:30Z | [
"python",
"object",
"tostring",
"memory-address",
"repr"
] |
Accessing object memory address | 121,396 | <p>When you call the <code>object.__repr__()</code> method in python you get something like this back: <code><__main__.Test object at 0x2aba1c0cf890></code>, is there any way to get a hold of the memory address if you overload <code>__repr__()</code>, other then calling <code>super(Class, obj).__repr__()</code> and regexing it out? </p>
| 89 | 2008-09-23T14:35:00Z | 121,508 | <p>You could reimplement the default repr this way:</p>
<pre><code>def __repr__(self):
return '<%s.%s object at %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self))
)
</code></pre>
| 46 | 2008-09-23T14:49:57Z | [
"python",
"object",
"tostring",
"memory-address",
"repr"
] |
Accessing object memory address | 121,396 | <p>When you call the <code>object.__repr__()</code> method in python you get something like this back: <code><__main__.Test object at 0x2aba1c0cf890></code>, is there any way to get a hold of the memory address if you overload <code>__repr__()</code>, other then calling <code>super(Class, obj).__repr__()</code> and regexing it out? </p>
| 89 | 2008-09-23T14:35:00Z | 121,572 | <p>With <a href="http://docs.python.org/lib/module-ctypes.html">ctypes</a>, you can achieve the same thing with</p>
<pre><code>>>> import ctypes
>>> a = (1,2,3)
>>> ctypes.addressof(a)
3077760748L
</code></pre>
<p>Documentation:</p>
<blockquote>
<p><code>addressof(C instance) -> integer</code><br />
Return the address of the C instance internal buffer</p>
</blockquote>
<p>Note that in CPython, currently <code>id(a) == ctypes.addressof(a)</code>, but <code>ctypes.addressof</code> should return the real address for each Python implementation, if</p>
<ul>
<li>ctypes is supported</li>
<li>memory pointers are a valid notion.</li>
</ul>
<p><strong>Edit</strong>: added information about interpreter-independence of ctypes</p>
| 6 | 2008-09-23T15:00:58Z | [
"python",
"object",
"tostring",
"memory-address",
"repr"
] |
Accessing object memory address | 121,396 | <p>When you call the <code>object.__repr__()</code> method in python you get something like this back: <code><__main__.Test object at 0x2aba1c0cf890></code>, is there any way to get a hold of the memory address if you overload <code>__repr__()</code>, other then calling <code>super(Class, obj).__repr__()</code> and regexing it out? </p>
| 89 | 2008-09-23T14:35:00Z | 122,032 | <p>While it's true that <code>id(object)</code> gets the object's address in the default CPython implementation, this is generally useless... you can't <i>do</i> anything with the address from pure Python code.</p>
<p>The only time you would actually be able to use the address is from a C extension library... in which case it is trivial to get the object's address since Python objects are always passed around as C pointers.</p>
| 0 | 2008-09-23T16:10:37Z | [
"python",
"object",
"tostring",
"memory-address",
"repr"
] |
Accessing object memory address | 121,396 | <p>When you call the <code>object.__repr__()</code> method in python you get something like this back: <code><__main__.Test object at 0x2aba1c0cf890></code>, is there any way to get a hold of the memory address if you overload <code>__repr__()</code>, other then calling <code>super(Class, obj).__repr__()</code> and regexing it out? </p>
| 89 | 2008-09-23T14:35:00Z | 4,628,230 | <p>Just in response to Torsten, I wasn't able to call <code>addressof()</code> on a regular python object. Furthermore, <code>id(a) != addressof(a)</code>. This is in CPython, don't know about anything else.</p>
<pre><code>>>> from ctypes import c_int, addressof
>>> a = 69
>>> addressof(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: invalid type
>>> b = c_int(69)
>>> addressof(b)
4300673472
>>> id(b)
4300673392
</code></pre>
| 11 | 2011-01-07T17:14:04Z | [
"python",
"object",
"tostring",
"memory-address",
"repr"
] |
Accessing object memory address | 121,396 | <p>When you call the <code>object.__repr__()</code> method in python you get something like this back: <code><__main__.Test object at 0x2aba1c0cf890></code>, is there any way to get a hold of the memory address if you overload <code>__repr__()</code>, other then calling <code>super(Class, obj).__repr__()</code> and regexing it out? </p>
| 89 | 2008-09-23T14:35:00Z | 26,285,749 | <p>There are a few issues here that aren't covered by any of the other answers.</p>
<p>First, <a href="https://docs.python.org/3/library/functions.html#id"><code>id</code></a> only returns:</p>
<blockquote>
<p>the âidentityâ of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same <code>id()</code> value.</p>
</blockquote>
<hr>
<p>In CPython, this happens to be the pointer to the <a href="https://docs.python.org/3/c-api/object.html"><code>PyObject</code></a> that represents the object in the interpreter, which is the same thing that <code>object.__repr__</code> displays. But this is just an implementation detail of CPython, not something that's true of Python in general. Jython doesn't deal in pointers, it deals in Java references (which the JVM of course probably represents as pointers, but you can't see thoseâand wouldn't want to, because the GC is allowed to move them around). PyPy lets different types have different kinds of <code>id</code>, but the most general is just an index into a table of objects you've called <code>id</code> on, which is obviously not going to be a pointer. I'm not sure about IronPython, but I'd suspect it's more like Jython than like CPython in this regard. So, in most Python implementations, there's no way to get whatever showed up in that <code>repr</code>, and no use if you did.</p>
<hr>
<p>But what if you only care about CPython? That's a pretty common case, after all.</p>
<p>Well, first, you may notice that <code>id</code> is an integer;* if you want that <code>0x2aba1c0cf890</code> string instead of the number <code>46978822895760</code>, you're going to have to format it yourself. Under the covers, I believe <code>object.__repr__</code> is ultimately using <code>printf</code>'s <code>%p</code> format, which you don't have from Python⦠but you can always do this:</p>
<pre><code>format(id(spam), '#010x' if sys.maxsize.bit_length() <= 32 else '#18x')
</code></pre>
<p><sub>* In 3.x, it's an <code>int</code>. In 2.x, it's an <code>int</code> if that's big enough to hold a pointerâwhich is may not be because of signed number issues on some platformsâand a <code>long</code> otherwise.</sub></p>
<p>Is there anything you can do with these pointers besides print them out? Sure (again, assuming you only care about CPython).</p>
<p>All of the <a href="https://docs.python.org/3/c-api/index.html">C API</a> functions take a pointer to a <code>PyObject</code> or a related type. For those related types, you can just call <code>PyFoo_Check</code> to make sure it really is a <code>Foo</code> object, then cast with <code>(PyFoo *)p</code>. So, if you're writing a C extension, the <code>id</code> is exactly what you need.</p>
<p>What if you're writing pure Python code? You can call the exact same functions with <a href="https://docs.python.org/3/library/ctypes.html#accessing-values-exported-from-dlls"><code>pythonapi</code></a> from <code>ctypes</code>.</p>
<hr>
<p>Finally, a few of the other answers have brought up <a href="https://docs.python.org/3/library/ctypes.html#ctypes.addressof"><code>ctypes.addressof</code></a>. That isn't relevant here. This only works for <code>ctypes</code> objects like <code>c_int32</code> (and maybe a few memory-buffer-like objects, like those provided by <code>numpy</code>). And, even there, it isn't giving you the address of the <code>c_int32</code> value, it's giving you the address of the C-level <code>int32</code> that the <code>c_int32</code> wraps up.</p>
<p>That being said, more often than not, if you really think you need the address of something, you didn't want a native Python object in the first place, you wanted a <code>ctypes</code> object.</p>
| 9 | 2014-10-09T18:41:51Z | [
"python",
"object",
"tostring",
"memory-address",
"repr"
] |
How do I include a stacktrace in my Django 500.html page? | 121,439 | <p>I'm running <code>Django 1.0</code> and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False.</p>
<p>With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers.</p>
<p>Any thoughts on how best to approach this issue?</p>
| 18 | 2008-09-23T14:39:35Z | 121,474 | <p>Automatically log your 500s, that way:</p>
<ul>
<li>You know when they occur.</li>
<li>You don't need to rely on users sending you stacktraces.</li>
</ul>
<p>Joel recommends even going so far as automatically creating tickets in your bug tracker when your application experiences a failure. Personally, I create a (private) RSS feed with the stacktraces, urls, etc. that the developers can subscribe to.</p>
<p>Showing stack traces to your users on the other hand could possibly leak information that malicious users could use to attack your site. Overly detailed error messages are one of the classic stepping stones to SQL injection attacks.</p>
<p><em>Edit</em> (added code sample to capture traceback):</p>
<p>You can get the exception information from the sys.exc_info call. While formatting the traceback for display comes from the traceback module:</p>
<pre><code>import traceback
import sys
try:
raise Exception("Message")
except:
type, value, tb = sys.exc_info()
print >> sys.stderr, type.__name__, ":", value
print >> sys.stderr, '\n'.join(traceback.format_tb(tb))
</code></pre>
<p>Prints:</p>
<pre><code>Exception : Message
File "exception.py", line 5, in <module>
raise Exception("Message")
</code></pre>
| 14 | 2008-09-23T14:44:50Z | [
"python",
"django",
"templates",
"stack-trace"
] |
How do I include a stacktrace in my Django 500.html page? | 121,439 | <p>I'm running <code>Django 1.0</code> and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False.</p>
<p>With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers.</p>
<p>Any thoughts on how best to approach this issue?</p>
| 18 | 2008-09-23T14:39:35Z | 121,487 | <p>You could call <code>sys.exc_info()</code> in a custom exception handler. But I don't recommend that. Django can send you emails for exceptions.</p>
| 1 | 2008-09-23T14:46:22Z | [
"python",
"django",
"templates",
"stack-trace"
] |
How do I include a stacktrace in my Django 500.html page? | 121,439 | <p>I'm running <code>Django 1.0</code> and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False.</p>
<p>With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers.</p>
<p>Any thoughts on how best to approach this issue?</p>
| 18 | 2008-09-23T14:39:35Z | 122,482 | <p>As @zacherates says, you really don't want to display a stacktrace to your users. The easiest approach to this problem is what Django does by default if you have yourself and your developers listed in the ADMINS setting with email addresses; it sends an email to everyone in that list with the full stack trace (and more) everytime there is a 500 error with DEBUG = False.</p>
| 11 | 2008-09-23T17:32:19Z | [
"python",
"django",
"templates",
"stack-trace"
] |
How do I include a stacktrace in my Django 500.html page? | 121,439 | <p>I'm running <code>Django 1.0</code> and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False.</p>
<p>With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers.</p>
<p>Any thoughts on how best to approach this issue?</p>
| 18 | 2008-09-23T14:39:35Z | 17,483,769 | <p>If we want to show exceptions which are generated , on ur template(500.html) then we could write your own 500 view, grabbing the exception and passing it to your 500 template.</p>
<h2>Steps:</h2>
<h2>#.In views.py:</h2>
<pre><code>import sys,traceback
def custom_500(request):
t = loader.get_template('500.html')
print sys.exc_info()
type, value, tb = sys.exc_info()
return HttpResponseServerError(t.render(Context({
'exception_value': value,
'value':type,
'tb':traceback.format_exception(type, value,
tb)
</code></pre>
<p>},RequestContext(request))))</p>
<h2>#.In Main Urls.py:</h2>
<pre><code>from django.conf.urls.defaults import *
handler500 = 'project.web.services.views.custom_500'
</code></pre>
<h2>#.In Template(500.html):</h2>
<pre><code>{{ exception_value }}{{value}}{{tb}}
</code></pre>
<p>more about it here: <a href="https://docs.djangoproject.com/en/dev/topics/http/views/#the-500-server-error-view" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/http/views/#the-500-server-error-view</a></p>
| 0 | 2013-07-05T07:50:53Z | [
"python",
"django",
"templates",
"stack-trace"
] |
How do I include a stacktrace in my Django 500.html page? | 121,439 | <p>I'm running <code>Django 1.0</code> and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False.</p>
<p>With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers.</p>
<p>Any thoughts on how best to approach this issue?</p>
| 18 | 2008-09-23T14:39:35Z | 35,889,521 | <p>I know this is an old question, but these days I would recommend using a service such as <a href="https://getsentry.com/welcome/" rel="nofollow">Sentry</a> to capture your errors.</p>
<p>On Django, the steps to set this up are incredibly simple. From <a href="https://docs.getsentry.com/hosted/clients/python/integrations/django/" rel="nofollow">the docs</a>:</p>
<ul>
<li>Install Raven using <code>pip install raven</code></li>
<li>Add <code>'raven.contrib.django.raven_compat'</code> to your <code>settings.INSTALLED_APPS</code>.</li>
<li>Add <code>RAVEN_CONFIG = {"dsn": YOUR_SENTRY_DSN}</code> to your settings.</li>
</ul>
<p>Then, on your 500 page (defined in <code>handler500</code>), pass the <code>request.sentry.id</code> to the template and your users can reference the specific error without any of your internals being exposed.</p>
| 0 | 2016-03-09T10:53:22Z | [
"python",
"django",
"templates",
"stack-trace"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,047 | <p>Python with Numeric Python:</p>
<pre><code>from numpy import *
a = random.random_integers(0, 100, 5)
b = unique(a)
</code></pre>
<p>Voilà ! Sure you could do something similar in a functional programming style but... why?</p>
| 0 | 2008-09-23T16:13:51Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,062 | <p>I will forgo the simplest solutions using the 'random' module since I take it that's not really what you are after. Here's what I think you are looking for in Python:</p>
<pre><code>>>> import random
>>>
>>> def getUniqueRandomNumbers(num, highest):
... seen = set()
... while len(seen) < num:
... i = random.randrange(0, highest)
... if i not in seen:
... seen.add(i)
... yield i
...
>>>
</code></pre>
<p>To show you how it works:</p>
<pre><code>>>> list(getUniqueRandomNumbers(10, 100))
[81, 57, 98, 47, 93, 31, 29, 24, 97, 10]
</code></pre>
| 2 | 2008-09-23T16:17:48Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,064 | <pre><code>>>> import random
>>> print random.sample(xrange(100), 5)
[61, 54, 91, 72, 85]
</code></pre>
<p>This should yield 5 unique values in the range <code>0 â 99</code>. The <code>xrange</code> object generates values as requested so no memory is used for values that aren't sampled.</p>
| 13 | 2008-09-23T16:18:19Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,085 | <p>I can't really read your LINQ, but I think you're trying to get 5 random numbers up to 100 and then remove duplicates.</p>
<p>Here's a solution for that:</p>
<pre><code>def random(max)
(rand * max).to_i
end
# Get 5 random numbers between 0 and 100
a = (1..5).inject([]){|acc,i| acc << random( 100)}
# Remove Duplicates
a = a & a
</code></pre>
<p>But perhaps you're actually looking for 5 distinct random numbers between 0 and 100. In which case:</p>
<pre><code>def random(max)
(rand * max).to_i
end
a = []
while( a.size < 5)
a << random( 100)
a = a & a
end
</code></pre>
<p>Now, this one might violate your sense of "not too many loops," but presumably Take and Distinct are just hiding the looping from you. It would be easy enough to just add methods to Enumerable to hide the while loop.</p>
| -1 | 2008-09-23T16:23:30Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,093 | <p>Hmm... How about (Python):</p>
<pre><code>s = set()
while len(s) <= N: s.update((random.random(),))
</code></pre>
| 3 | 2008-09-23T16:24:18Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,116 | <p>In Ruby:</p>
<pre><code>a = (0..100).entries.sort_by {rand}.slice! 0, 5
</code></pre>
<p><strong>Update</strong>: Here is a slightly different way:
a = (0...100).entries.sort_by{rand}[0...5]</p>
<p><strong>EDIT:</strong></p>
<p>and In Ruby 1.9 you can do this:</p>
<pre><code>Array(0..100).sample(5)
</code></pre>
| 5 | 2008-09-23T16:27:31Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,121 | <p>Here's another Ruby solution:</p>
<pre><code>a = (1..5).collect { rand(100) }
a & a
</code></pre>
<p>I think, with your LINQ statement, the Distinct will remove duplicates after 5 have already been taken, so you aren't guaranteed to get 5 back. Someone can correct me if I'm wrong, though.</p>
| 2 | 2008-09-23T16:28:02Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,146 | <pre><code>import random
def makeRand(n):
rand = random.Random()
while 1:
yield rand.randint(0,n)
yield rand.randint(0,n)
gen = makeRand(100)
terms = [ gen.next() for n in range(5) ]
print "raw list"
print terms
print "de-duped list"
print list(set(terms))
# produces output similar to this
#
# raw list
# [22, 11, 35, 55, 1]
# de-duped list
# [35, 11, 1, 22, 55]
</code></pre>
| 0 | 2008-09-23T16:31:02Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,159 | <p>Well, first you rewrite LINQ in Python. Then your solution is a one-liner :)</p>
<pre><code>from random import randrange
def Distinct(items):
set = {}
for i in items:
if not set.has_key(i):
yield i
set[i] = 1
def Take(num, items):
for i in items:
if num > 0:
yield i
num = num - 1
else:
break
def ToArray(items):
return [i for i in items]
def GetRandomNumbers(max):
while 1:
yield randrange(max)
print ToArray(Take(5, Distinct(GetRandomNumbers(100))))
</code></pre>
<p>If you put all the simple methods above into a module called LINQ.py, you can impress your friends.</p>
<p>(Disclaimer: of course, this is not <em>actually</em> rewriting LINQ in Python. People have the misconception that LINQ is just a bunch of trivial extension methods and some new syntax. The really advanced part of LINQ, however, is automatic SQL generation so that when you're querying a database, it's the database that implements Distinct() rather than the client side.)</p>
| 0 | 2008-09-23T16:32:42Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,188 | <p>EDIT : Ok, just for fun, a shorter and faster one (and still using iterators).</p>
<pre><code>def getRandomNumbers(max, size) :
pool = set()
return ((lambda x : pool.add(x) or x)(random.randrange(max)) for x in xrange(size) if len(a) < size)
print [x for x in gen(100, 5)]
[0, 10, 19, 51, 18]
</code></pre>
<p>Yeah, I know, one-liners should be left to perl lovers, but I think this one is quite powerful isn't it ?</p>
<p>Old message here :</p>
<p>My god, how complicated is all that ! Let's be pythonic :</p>
<pre><code>import random
def getRandomNumber(max, size, min=0) :
# using () and xrange = using iterators
return (random.randrange(min, max) for x in xrange(size))
print set(getRandomNumber(100, 5)) # set() removes duplicates
set([88, 99, 29, 70, 23])
</code></pre>
<p>Enjoy</p>
<p>EDIT : As commentators noticed, this is an exact translation of the question's code.</p>
<p>To avoid the problem we got by removing duplicates after generating the list, resulting in too little data, you can choose another way :</p>
<pre><code>def getRandomNumbers(max, size) :
pool = []
while len(pool) < size :
tmp = random.randrange(max)
if tmp not in pool :
yield pool.append(tmp) or tmp
print [x for x in getRandomNumbers(5, 5)]
[2, 1, 0, 3, 4]
</code></pre>
| 2 | 2008-09-23T16:38:45Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,212 | <p>Here's a transliteration from your solution to Python.</p>
<p>First, a generator that creates Random numbers. This isn't very Pythonic, but it's a good match with your sample code. </p>
<pre><code>>>> import random
>>> def getRandomNumbers( max ):
... while True:
... yield random.randrange(0,max)
</code></pre>
<p>Here's a client loop that collects a set of 5 distinct values. This is -- again -- not the most Pythonic implementation.</p>
<pre><code>>>> distinctSet= set()
>>> for r in getRandomNumbers( 100 ):
... distinctSet.add( r )
... if len(distinctSet) == 5:
... break
...
>>> distinctSet
set([81, 66, 28, 53, 46])
</code></pre>
<p>It's not clear why you want to use a generator for random numbers -- that's one of the few things that's so simple that a generator doesn't simplify it. </p>
<p>A more Pythonic version might be something like:</p>
<pre><code>distinctSet= set()
while len(distinctSet) != 5:
distinctSet.add( random.randrange(0,100) )
</code></pre>
<p>If the requirements are to generate 5 values and find distinct among those 5, then something like</p>
<pre><code>distinctSet= set( [random.randrange(0,100) for i in range(5) ] )
</code></pre>
| 0 | 2008-09-23T16:42:27Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 122,285 | <p>Maybe this will suit your needs and look a bit more linqish:</p>
<pre><code>from numpy import random,unique
def GetRandomNumbers(total=5):
while True:
yield unique(random.random(total*2))[:total]
randomGenerator = GetRandomNumbers()
myRandomNumbers = randomGenerator.next()
</code></pre>
| 0 | 2008-09-23T16:57:09Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 123,258 | <p>Here's another python version, more closely matching the structure of your C# code. There isn't a builtin for giving distinct results, so I've added a function to do this.</p>
<pre><code>import itertools, random
def distinct(seq):
seen=set()
for item in seq:
if item not in seen:
seen.add(item)
yield item
def getRandomNumbers(max):
while 1:
yield random.randint(0,max)
for item in itertools.islice(distinct(getRandomNumbers(100)), 5):
print item
</code></pre>
| 0 | 2008-09-23T19:33:19Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? | 122,033 | <p>Yesterday, I asked <a href="http://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: </p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes? </p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
| 7 | 2008-09-23T16:10:42Z | 3,793,197 | <p>In Ruby 1.9:</p>
<pre><code>Array(0..100).sample(5)
</code></pre>
| 1 | 2010-09-25T09:17:24Z | [
"python",
"ruby",
"linq",
"functional-programming"
] |
How do you translate this regular-expression idiom from Perl into Python? | 122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| 35 | 2008-09-23T16:55:18Z | 122,294 | <p>Using named groups and a dispatch table:</p>
<pre><code>r = re.compile(r'(?P<cmd>foo|bar|baz)(?P<data>.+)')
def do_foo(data):
...
def do_bar(data):
...
def do_baz(data):
...
dispatch = {
'foo': do_foo,
'bar': do_bar,
'baz': do_baz,
}
m = r.match(var)
if m:
dispatch[m.group('cmd')](m.group('data'))
</code></pre>
<p>With a little bit of introspection you can auto-generate the regexp and the dispatch table.</p>
| 16 | 2008-09-23T16:58:53Z | [
"python",
"regex",
"perl"
] |
How do you translate this regular-expression idiom from Perl into Python? | 122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| 35 | 2008-09-23T16:55:18Z | 122,345 | <p>Alternatively, something not using regular expressions at all:</p>
<pre><code>prefix, data = var[:3], var[3:]
if prefix == 'foo':
# do something with data
elif prefix == 'bar':
# do something with data
elif prefix == 'baz':
# do something with data
else:
# do something with var
</code></pre>
<p>Whether that is suitable depends on your actual problem. Don't forget, regular expressions aren't the swiss army knife that they are in Perl; Python has different constructs for doing string manipulation.</p>
| 4 | 2008-09-23T17:07:16Z | [
"python",
"regex",
"perl"
] |
How do you translate this regular-expression idiom from Perl into Python? | 122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| 35 | 2008-09-23T16:55:18Z | 122,364 | <pre><code>def find_first_match(string, *regexes):
for regex, handler in regexes:
m = re.search(regex, string):
if m:
handler(m)
return
else:
raise ValueError
find_first_match(
foo,
(r'foo(.+)', handle_foo),
(r'bar(.+)', handle_bar),
(r'baz(.+)', handle_baz))
</code></pre>
<p>To speed it up, one could turn all regexes into one internally and create the dispatcher on the fly. Ideally, this would be turned into a class then.</p>
| 4 | 2008-09-23T17:11:09Z | [
"python",
"regex",
"perl"
] |
How do you translate this regular-expression idiom from Perl into Python? | 122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| 35 | 2008-09-23T16:55:18Z | 123,083 | <p>Yeah, it's kind of annoying. Perhaps this will work for your case. </p>
<pre><code>
import re
class ReCheck(object):
def __init__(self):
self.result = None
def check(self, pattern, text):
self.result = re.search(pattern, text)
return self.result
var = 'bar stuff'
m = ReCheck()
if m.check(r'foo(.+)',var):
print m.result.group(1)
elif m.check(r'bar(.+)',var):
print m.result.group(1)
elif m.check(r'baz(.+)',var):
print m.result.group(1)
</code></pre>
<p><strong>EDIT:</strong> Brian correctly pointed out that my first attempt did not work. Unfortunately, this attempt is longer.</p>
| 10 | 2008-09-23T19:04:53Z | [
"python",
"regex",
"perl"
] |
How do you translate this regular-expression idiom from Perl into Python? | 122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| 35 | 2008-09-23T16:55:18Z | 124,128 | <p>I'd suggest this, as it uses the least regex to accomplish your goal. It is still functional code, but no worse then your old Perl.</p>
<pre><code>import re
var = "barbazfoo"
m = re.search(r'(foo|bar|baz)(.+)', var)
if m.group(1) == 'foo':
print m.group(1)
# do something with m.group(1)
elif m.group(1) == "bar":
print m.group(1)
# do something with m.group(1)
elif m.group(1) == "baz":
print m.group(2)
# do something with m.group(2)
</code></pre>
| 9 | 2008-09-23T21:50:45Z | [
"python",
"regex",
"perl"
] |
How do you translate this regular-expression idiom from Perl into Python? | 122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| 35 | 2008-09-23T16:55:18Z | 135,720 | <pre><code>r"""
This is an extension of the re module. It stores the last successful
match object and lets you access it's methods and attributes via
this module.
This module exports the following additional functions:
expand Return the string obtained by doing backslash substitution on a
template string.
group Returns one or more subgroups of the match.
groups Return a tuple containing all the subgroups of the match.
start Return the indices of the start of the substring matched by
group.
end Return the indices of the end of the substring matched by group.
span Returns a 2-tuple of (start(), end()) of the substring matched
by group.
This module defines the following additional public attributes:
pos The value of pos which was passed to the search() or match()
method.
endpos The value of endpos which was passed to the search() or
match() method.
lastindex The integer index of the last matched capturing group.
lastgroup The name of the last matched capturing group.
re The regular expression object which as passed to search() or
match().
string The string passed to match() or search().
"""
import re as re_
from re import *
from functools import wraps
__all__ = re_.__all__ + [ "expand", "group", "groups", "start", "end", "span",
"last_match", "pos", "endpos", "lastindex", "lastgroup", "re", "string" ]
last_match = pos = endpos = lastindex = lastgroup = re = string = None
def _set_match(match=None):
global last_match, pos, endpos, lastindex, lastgroup, re, string
if match is not None:
last_match = match
pos = match.pos
endpos = match.endpos
lastindex = match.lastindex
lastgroup = match.lastgroup
re = match.re
string = match.string
return match
@wraps(re_.match)
def match(pattern, string, flags=0):
return _set_match(re_.match(pattern, string, flags))
@wraps(re_.search)
def search(pattern, string, flags=0):
return _set_match(re_.search(pattern, string, flags))
@wraps(re_.findall)
def findall(pattern, string, flags=0):
matches = re_.findall(pattern, string, flags)
if matches:
_set_match(matches[-1])
return matches
@wraps(re_.finditer)
def finditer(pattern, string, flags=0):
for match in re_.finditer(pattern, string, flags):
yield _set_match(match)
def expand(template):
if last_match is None:
raise TypeError, "No successful match yet."
return last_match.expand(template)
def group(*indices):
if last_match is None:
raise TypeError, "No successful match yet."
return last_match.group(*indices)
def groups(default=None):
if last_match is None:
raise TypeError, "No successful match yet."
return last_match.groups(default)
def groupdict(default=None):
if last_match is None:
raise TypeError, "No successful match yet."
return last_match.groupdict(default)
def start(group=0):
if last_match is None:
raise TypeError, "No successful match yet."
return last_match.start(group)
def end(group=0):
if last_match is None:
raise TypeError, "No successful match yet."
return last_match.end(group)
def span(group=0):
if last_match is None:
raise TypeError, "No successful match yet."
return last_match.span(group)
del wraps # Not needed past module compilation
</code></pre>
<p>For example:</p>
<pre><code>if gre.match("foo(.+)", var):
# do something with gre.group(1)
elif gre.match("bar(.+)", var):
# do something with gre.group(1)
elif gre.match("baz(.+)", var):
# do something with gre.group(1)
</code></pre>
| 9 | 2008-09-25T20:10:55Z | [
"python",
"regex",
"perl"
] |
How do you translate this regular-expression idiom from Perl into Python? | 122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| 35 | 2008-09-23T16:55:18Z | 1,806,345 | <p>With thanks to <a href="http://stackoverflow.com/questions/1663995/python-variable-assignment-and-if-statement">this other SO question</a>:</p>
<pre><code>import re
class DataHolder:
def __init__(self, value=None, attr_name='value'):
self._attr_name = attr_name
self.set(value)
def __call__(self, value):
return self.set(value)
def set(self, value):
setattr(self, self._attr_name, value)
return value
def get(self):
return getattr(self, self._attr_name)
string = u'test bar 123'
save_match = DataHolder(attr_name='match')
if save_match(re.search('foo (\d+)', string)):
print "Foo"
print save_match.match.group(1)
elif save_match(re.search('bar (\d+)', string)):
print "Bar"
print save_match.match.group(1)
elif save_match(re.search('baz (\d+)', string)):
print "Baz"
print save_match.match.group(1)
</code></pre>
| 6 | 2009-11-27T01:05:41Z | [
"python",
"regex",
"perl"
] |
How do you translate this regular-expression idiom from Perl into Python? | 122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| 35 | 2008-09-23T16:55:18Z | 2,021,009 | <p>Here's the way I solved this issue:</p>
<pre><code>matched = False;
m = re.match("regex1");
if not matched and m:
#do something
matched = True;
m = re.match("regex2");
if not matched and m:
#do something else
matched = True;
m = re.match("regex3");
if not matched and m:
#do yet something else
matched = True;
</code></pre>
<p>Not nearly as clean as the original pattern. However, it is simple, straightforward and doesn't require extra modules or that you change the original regexs.</p>
| 3 | 2010-01-07T14:42:19Z | [
"python",
"regex",
"perl"
] |
How do you translate this regular-expression idiom from Perl into Python? | 122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| 35 | 2008-09-23T16:55:18Z | 4,195,819 | <p>how about using a dictionary?</p>
<pre><code>match_objects = {}
if match_objects.setdefault( 'mo_foo', re_foo.search( text ) ):
# do something with match_objects[ 'mo_foo' ]
elif match_objects.setdefault( 'mo_bar', re_bar.search( text ) ):
# do something with match_objects[ 'mo_bar' ]
elif match_objects.setdefault( 'mo_baz', re_baz.search( text ) ):
# do something with match_objects[ 'mo_baz' ]
...
</code></pre>
<p>however, you must ensure there are no duplicate match_objects dictionary keys ( mo_foo, mo_bar, ... ), best by giving each regular expression its own name and naming the match_objects keys accordingly, otherwise match_objects.setdefault() method would return existing match object instead of creating new match object by running re_xxx.search( text ).</p>
| 1 | 2010-11-16T15:33:00Z | [
"python",
"regex",
"perl"
] |
How do you translate this regular-expression idiom from Perl into Python? | 122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| 35 | 2008-09-23T16:55:18Z | 30,799,800 | <p>My solution would be:</p>
<pre><code>import re
class Found(Exception): pass
try:
for m in re.finditer('bar(.+)', var):
# Do something
raise Found
for m in re.finditer('foo(.+)', var):
# Do something else
raise Found
except Found: pass
</code></pre>
| 0 | 2015-06-12T09:33:08Z | [
"python",
"regex",
"perl"
] |
How do you translate this regular-expression idiom from Perl into Python? | 122,277 | <p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
| 35 | 2008-09-23T16:55:18Z | 38,849,153 | <p>Expanding on the solution by Pat Notz a bit, I found it even the more elegant to:<br>
 - name the methods the same as <code>re</code> provides (e.g. <code>search</code> vs. <code>check</code>) and<br>
  - implement the necessary methods like <code>group()</code> on the holder object itself:</p>
<pre><code>class Re(object):
def __init(self):
self.result = None
def search(self, pattern, text):
self.result = re.search(pattern, text)
return self.result
def group(self, index):
return self.result.group(index)
</code></pre>
<p>So instead of e.g. this:</p>
<pre><code>m = re.search(r'set ([^ ]+) to ([^ ]+)', line)
if m:
vars[m.group(1)] = m.group(2)
else:
m = re.search(r'print ([^ ]+)', line)
if m:
print(vars[m.group(1)])
else:
m = re.search(r'add ([^ ]+) to ([^ ]+)', line)
if m:
vars[m.group(2)] += vars[m.group(1)]
</code></pre>
<p>One does just this:</p>
<pre><code>m = Re()
...
if m.search(r'set ([^ ]+) to ([^ ]+)', line):
vars[m.group(1)] = m.group(2)
elif m.search(r'print ([^ ]+)', line):
print(vars[m.group(1)])
elif m.search(r'add ([^ ]+) to ([^ ]+)', line):
vars[m.group(2)] += vars[m.group(1)]
</code></pre>
<p>Looks very natural in the end, does not need too many code changes and avoids the problems with global state like the accepted answer.</p>
| 0 | 2016-08-09T11:11:22Z | [
"python",
"regex",
"perl"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 122,340 | <p>From <a href="http://docs.djangoproject.com/en/dev/topics/install/#remove-any-old-versions-of-django">"How to Install Django" documentation</a> (though this is useful to more than just Django installation) - execute the following from the shell:</p>
<pre><code>python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
</code></pre>
<p>Formatted for readability (rather than use as a one-liner), that looks like the following:</p>
<pre><code>from distutils.sysconfig import get_python_lib
print(get_python_lib())
</code></pre>
| 240 | 2008-09-23T17:06:59Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 122,360 | <pre><code>from distutils.sysconfig import get_python_lib
print get_python_lib()
</code></pre>
| 5 | 2008-09-23T17:09:54Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 122,377 | <p>As others have noted, <code>distutils.sysconfig</code> has the relevant settings:</p>
<pre><code>import distutils.sysconfig
print distutils.sysconfig.get_python_lib()
</code></pre>
<p>...though the default <code>site.py</code> does something a bit more crude, paraphrased below:</p>
<pre><code>import sys, os
print os.sep.join([sys.prefix, 'lib', 'python' + sys.version[:3], 'site-packages'])
</code></pre>
<p>(it also adds <code>${sys.prefix}/lib/site-python</code> and adds both paths for <code>sys.exec_prefix</code> as well, should that constant be different).</p>
<p>That said, what's the context? You shouldn't be messing with your <code>site-packages</code> directly; setuptools/distutils will work for installation, and your program may be running in a virtualenv where your pythonpath is completely user-local, so it shouldn't assume use of the system site-packages directly either.</p>
| 19 | 2008-09-23T17:14:02Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 122,387 | <p>An additional note to the <code>get_python_lib</code> function mentioned already: on some platforms different directories are used for platform specific modules (eg: modules that require compilation). If you pass <code>plat_specific=True</code> to the function you get the site packages for platform specific packages.</p>
| 7 | 2008-09-23T17:16:22Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 1,711,808 | <p>A side-note: The proposed solution (distutils.sysconfig.get_python_lib()) does not work when there is more than one site-packages directory (as <a href="http://pythonsimple.noucleus.net/python-install/python-site-packages-what-they-are-and-where-to-put-them">recommended by this article</a>). It will only return the main site-packages directory. Alas, I have no better solution either. Python doesn't seem to keep track of site-packages directories, just the packages within them.</p>
| 11 | 2009-11-10T22:49:28Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 4,611,382 | <p><em>For Ubuntu</em>,</p>
<pre><code>python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
</code></pre>
<p>...is not correct.</p>
<p>It will point you to <code>/usr/lib/pythonX.X/dist-packages</code></p>
<p>This folder only contains packages your operating system has automatically installed for programs to run.</p>
<p><em>On ubuntu</em>, the site-packages folder that contains packages installed via setup_tools\easy_install\pip will be in <code>/usr/local/lib/pythonX.X/dist-packages</code></p>
<p>The second folder is probably the more useful one if the use case is related to installation or reading source code.</p>
<p>If you do not use Ubuntu, you are probably safe copy-pasting the first code box into the terminal.</p>
| 85 | 2011-01-06T03:08:09Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 5,095,375 | <p>Let's say you have installed the package 'django'. import it and type in dir(django). It will show you, all the functions and attributes with that module. Type in the python interpreter - </p>
<pre><code>>>> import django
>>> dir(django)
['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version']
>>> print django.__path__
['/Library/Python/2.6/site-packages/django']
</code></pre>
<p>You can do the same thing if you have installed mercurial.</p>
<p>This is for Snow Leopard. But I think it should work in general as well.</p>
| 16 | 2011-02-23T18:32:10Z | [
"python",
"installation"
] |
Subsets and Splits