title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Correct way of handling exceptions in Python? | 984,526 | <p>I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.</p>
<p>I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
I want to know how you generally deal with dependent, error prone statements.</p>
<p>My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.</p>
<p>For your consideration, an example:</p>
<pre><code>try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
pass
else: #only if no exception was thrown we may continue
try:
server.login(username, password)
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
server.quit()
else:
try:
# this is already the 3rd nested try...except
# for such a simple procedure! horrible
server.sendmail(addr, [to], msg.as_string())
return True
except Exception:
return False
finally:
server.quit()
return False
</code></pre>
<p>This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?</p>
<p>I am also interested in proper resource cleanup, even Python can manage that for itself. </p>
<p>Thanks, Tom</p>
| 25 | 2009-06-12T00:45:51Z | 984,808 | <p>If it was me I would probably do something like the following:</p>
<pre><code>try:
server = smtplib.SMTP(host)
try:
server.login(username, password)
server.sendmail(addr, [to], str(msg))
finally:
server.quit()
except:
debug("sendmail", traceback.format_exc().splitlines()[-1])
return True
</code></pre>
<p>All errors are caught and debugged, the return value == True on success, and the server connection is properly cleaned up if the initial connection is made.</p>
| 3 | 2009-06-12T03:09:51Z | [
"python",
"exception"
] |
Correct way of handling exceptions in Python? | 984,526 | <p>I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.</p>
<p>I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
I want to know how you generally deal with dependent, error prone statements.</p>
<p>My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.</p>
<p>For your consideration, an example:</p>
<pre><code>try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
pass
else: #only if no exception was thrown we may continue
try:
server.login(username, password)
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
server.quit()
else:
try:
# this is already the 3rd nested try...except
# for such a simple procedure! horrible
server.sendmail(addr, [to], msg.as_string())
return True
except Exception:
return False
finally:
server.quit()
return False
</code></pre>
<p>This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?</p>
<p>I am also interested in proper resource cleanup, even Python can manage that for itself. </p>
<p>Thanks, Tom</p>
| 25 | 2009-06-12T00:45:51Z | 985,886 | <p>I would try something like this:</p>
<pre><code>class Mailer():
def send_message(self):
exception = None
for method in [self.connect,
self.authenticate,
self.send,
self.quit]:
try:
if not method(): break
except Exception, ex:
exception = ex
break
if method == quit and exception == None:
return True
if exception:
self.handle_exception(method, exception)
else:
self.handle_failure(method)
def connect(self):
return True
def authenticate(self):
return True
def send(self):
return True
def quit(self):
return True
def handle_exception(self, method, exception):
print "{name} ({msg}) in {method}.".format(
name=exception.__class__.__name__,
msg=exception,
method=method.__name__)
def handle_failure(self, method):
print "Failure in {0}.".format(method.__name__)
</code></pre>
<p>All of the methods (including <code>send_message</code>, really) follow the same protocol: they return True if they succeeded, and unless they actually <em>handle</em> an exception, they don't trap it. This protocol also makes it possible to handle the case where a method needs to indicate that it failed without raising an exception. (If the only way your methods fail is by raising an exception, that simplifies the protocol. If you're having to deal with a lot of non-exception failure states outside of the method that failed, you probably have a design problem that you haven't worked out yet.)</p>
<p>The downside of this approach is that all of the methods have to use the same arguments. I've opted for none, with the expectation that the methods I've stubbed out will end up manipulating class members.</p>
<p>The upside of this approach is considerable, though. First, you can add dozens of methods to the process without <code>send_message</code> getting any more complex. </p>
<p>You can also go crazy and do something like this:</p>
<pre><code>def handle_exception(self, method, exception):
custom_handler_name = "handle_{0}_in_{1}".format(\
exception.__class__.__name__,
method.__name__)
try:
custom_handler = self.__dict__[custom_handler_name]
except KeyError:
print "{name} ({msg}) in {method}.".format(
name=exception.__class__.__name__,
msg=exception,
method=method.__name__)
return
custom_handler()
def handle_AuthenticationError_in_authenticate(self):
print "Your login credentials are questionable."
</code></pre>
<p>...though at that point, I might say to myself, "self, you're working the Command pattern pretty hard without creating a Command class. Maybe now is the time."</p>
| 1 | 2009-06-12T09:46:10Z | [
"python",
"exception"
] |
How to use standard toolbar icons with WxPython? | 984,816 | <p>I'm designing a simple text editor using WxPython, and I want to put the platform's native icons in the toolbar. It seems that the only way to make toolbars is with custom images, which are not good for portability. Is there some kind of (e.g.) GetSaveIcon()?</p>
| 2 | 2009-06-12T03:16:20Z | 984,833 | <p>I don't think wxPython provides native images on each platform
but just for consistency sake you can use wx.ArtProvider
e.g.
wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN)</p>
| 4 | 2009-06-12T03:25:11Z | [
"python",
"wxpython",
"icons"
] |
Convert a value into row, column and char | 984,888 | <p>My data structure is initialized as follows:</p>
<pre><code>[[0,0,0,0,0,0,0,0] for x in range(8)]
</code></pre>
<p>8 characters, 8 rows, each row has 5 bits for columns, so each integer can be in the range between 0 and 31 inclusive.</p>
<p>I have to convert the number 177 (can be between 0 and 319) into char, row, and column.</p>
<p>Let me try again, this time with a better code example. No bits are set.</p>
<p>Ok, I added the reverse to the problem. Maybe that'll help.</p>
<pre><code>chars = [[0,0,0,0,0,0,0,0] for x in range(8)]
# reverse solution
for char in range(8):
for row in range(8):
for col in range(5):
n = char * 40 + (row * 5 + col)
chars[char][row] = chars[char][row] ^ [0, 1<<4-col][row < col]
for data in range(320):
char = data / 40
col = (data - char * 40) % 5
row = ?
print "Char %g, Row %g, Col %g" % (char, row, col), chars[char][row] & 1<<4-col
</code></pre>
| 1 | 2009-06-12T03:56:42Z | 984,954 | <p>Are you looking for divmod function?</p>
<p>[Edit: using python operators instead of pseudo language.]</p>
<pre><code>char is between 0 and 319
character = (char % 40)
column = (char / 40) % 5
row = (char / 40) / 5
</code></pre>
| 1 | 2009-06-12T04:15:11Z | [
"python",
"math"
] |
Convert a value into row, column and char | 984,888 | <p>My data structure is initialized as follows:</p>
<pre><code>[[0,0,0,0,0,0,0,0] for x in range(8)]
</code></pre>
<p>8 characters, 8 rows, each row has 5 bits for columns, so each integer can be in the range between 0 and 31 inclusive.</p>
<p>I have to convert the number 177 (can be between 0 and 319) into char, row, and column.</p>
<p>Let me try again, this time with a better code example. No bits are set.</p>
<p>Ok, I added the reverse to the problem. Maybe that'll help.</p>
<pre><code>chars = [[0,0,0,0,0,0,0,0] for x in range(8)]
# reverse solution
for char in range(8):
for row in range(8):
for col in range(5):
n = char * 40 + (row * 5 + col)
chars[char][row] = chars[char][row] ^ [0, 1<<4-col][row < col]
for data in range(320):
char = data / 40
col = (data - char * 40) % 5
row = ?
print "Char %g, Row %g, Col %g" % (char, row, col), chars[char][row] & 1<<4-col
</code></pre>
| 1 | 2009-06-12T03:56:42Z | 985,510 | <p>Okay, this looks as if you're working with a 1x8 LCD display, where each character is 8 rows of 5 pixels.</p>
<p>So, you have a total of 8 * (8 * 5) = 320 pixels, and you want to map the index of a pixel to a position in the "framebuffer" decribing the display's contents.</p>
<p>I assume pixels are distributed like this (shown for the first char only), your initial loops indicate this is is correct:</p>
<pre><code> 0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
25 26 27 28 29
30 31 32 33 34
35 36 37 38 39
</code></pre>
<p>We then have:</p>
<pre><code> # Compute which of the 8 characters the pixel falls in, 0..7:
char = int(number / 40)
# Compute which pixel column the pixel is in, 0..4:
col = number % 5
# Compute which pixel row the pixel is in, 0..7:
row = int((number - char * 40) / 5)
</code></pre>
<p>I used explicit <code>int()</code>s to make it clear that the numbers are integers.</p>
<p>Note that you might want to flip the column, since this numbers them from the left.</p>
| 2 | 2009-06-12T07:50:34Z | [
"python",
"math"
] |
Python Subprocess.Popen from a thread | 984,941 | <p>I'm trying to launch an 'rsync' using subprocess module and Popen inside of a thread. After I call the rsync I need to read the output as well. I'm using the communicate method to read the output. The code runs fine when I do not use a thread. It appears that when I use a thread it hangs on the communicate call. Another thing I've noticed is that when I set shell=False I get nothing back from the communicate when running in a thread.</p>
| 18 | 2009-06-12T04:13:25Z | 985,028 | <p>You didn't supply any code for us to look at, but here's a sample that does something similar to what you describe:</p>
<pre><code>import threading
import subprocess
class MyClass(threading.Thread):
def __init__(self):
self.stdout = None
self.stderr = None
threading.Thread.__init__(self)
def run(self):
p = subprocess.Popen('rsync -av /etc/passwd /tmp'.split(),
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.stdout, self.stderr = p.communicate()
myclass = MyClass()
myclass.start()
myclass.join()
print myclass.stdout
</code></pre>
| 27 | 2009-06-12T04:39:35Z | [
"python",
"multithreading",
"subprocess",
"rsync"
] |
Python Subprocess.Popen from a thread | 984,941 | <p>I'm trying to launch an 'rsync' using subprocess module and Popen inside of a thread. After I call the rsync I need to read the output as well. I'm using the communicate method to read the output. The code runs fine when I do not use a thread. It appears that when I use a thread it hangs on the communicate call. Another thing I've noticed is that when I set shell=False I get nothing back from the communicate when running in a thread.</p>
| 18 | 2009-06-12T04:13:25Z | 4,872,639 | <p>Here's a great implementation not using threads:
<a href="http://stackoverflow.com/questions/4417546/constantly-print-subprocess-output-while-process-is-running">constantly-print-subprocess-output-while-process-is-running</a></p>
<pre><code>import subprocess
def execute(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ''
# Poll process for new output until finished
for line in iter(process.stdout.readline, ""):
print line,
output += line
process.wait()
exitCode = process.returncode
if (exitCode == 0):
return output
else:
raise Exception(command, exitCode, output)
execute(['ping', 'localhost'])
</code></pre>
| 5 | 2011-02-02T09:25:26Z | [
"python",
"multithreading",
"subprocess",
"rsync"
] |
Page isn't always rendered | 985,017 | <p>In Google App Engine, I have the following code which shows a simple HTML page.</p>
<pre><code>import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
class IndexHandler(webapp.RequestHandler):
def get(self):
template_values = { }
path = os.path.join(os.path.dirname(__file__), '../templates/index.html')
self.response.out.write(template.render(path, template_values))
</code></pre>
<p>The issue is that the page isn't always rendered. The index.html is a simple "Hello World!". After a couple of page refresh the page is displayed properly (i.e. the index.html file is found...). I tried to call flush at the end, but it didn't help. I am able to repro this with the SDK and on their server. </p>
<p>Am I missing something? Does someone have an idea of what is going on?</p>
<p>Thanks</p>
| 1 | 2009-06-12T04:35:23Z | 985,165 | <p>Can't reproduce -- with directory changed to <code>./templates</code> (don't have a <code>../templates</code> in my setup), and the usual <code>main</code> function added, and this script assigned in <code>app.yaml</code> to some arbitrary URL, it serves successfully "Hello World" every time. Guess we need more info to help -- log entries (maybe add <code>logging.info</code> calls here?), <code>app.yaml</code>, where's <code>main</code>, etc, etc...</p>
| 0 | 2009-06-12T05:34:28Z | [
"python",
"google-app-engine"
] |
Page isn't always rendered | 985,017 | <p>In Google App Engine, I have the following code which shows a simple HTML page.</p>
<pre><code>import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
class IndexHandler(webapp.RequestHandler):
def get(self):
template_values = { }
path = os.path.join(os.path.dirname(__file__), '../templates/index.html')
self.response.out.write(template.render(path, template_values))
</code></pre>
<p>The issue is that the page isn't always rendered. The index.html is a simple "Hello World!". After a couple of page refresh the page is displayed properly (i.e. the index.html file is found...). I tried to call flush at the end, but it didn't help. I am able to repro this with the SDK and on their server. </p>
<p>Am I missing something? Does someone have an idea of what is going on?</p>
<p>Thanks</p>
| 1 | 2009-06-12T04:35:23Z | 986,395 | <p>Your handler script (the one referenced by app.yaml) has a main() function, but needs this stanza at the end:</p>
<pre><code>if __name__ == '__main__':
main()
</code></pre>
<p>What's happening is that the first time your script is run in a given interpreter, it interprets your main script, which does nothing (thus returning a blank response). On subsequent invocations, the interpreter simply executes your main() (a documented optimization), which generates the page as expected. Adding the stanza above will cause it to execute main on initial import, too.</p>
| 3 | 2009-06-12T12:33:49Z | [
"python",
"google-app-engine"
] |
Python shortcuts | 985,026 | <p>Python is filled with little neat shortcuts.</p>
<p>For example:</p>
<pre><code>self.data = map(lambda x: list(x), data)
</code></pre>
<p>and (although not so pretty)</p>
<pre><code>tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema')
</code></pre>
<p>among countless others.</p>
<p>In the irc channel, they said "too many to know them all". </p>
<p>I think we should list some here, as i love using these shortcuts to shorten & refctor my code. I'm sure this would benefit many.</p>
| 1 | 2009-06-12T04:39:21Z | 985,045 | <pre><code>self.data = map(lambda x: list(x), data)
</code></pre>
<p>is dreck -- use</p>
<pre><code>self.data = map(list, data)
</code></pre>
<p>if you're a <code>map</code> fanatic (list comprehensions are generally preferred these days). More generally, <code>lambda x: somecallable(x)</code> can <strong>always</strong> be productively changed to just <code>somecallable</code>, in <strong>every</strong> context, with nothing but good effect.</p>
<p>As for shortcuts in general, my wife and I did our best to list the most important and useful one in the early part of the Python Cookbook's second edition -- could be a start.</p>
| 11 | 2009-06-12T04:45:29Z | [
"python",
"shortcut",
"refactoring"
] |
Python shortcuts | 985,026 | <p>Python is filled with little neat shortcuts.</p>
<p>For example:</p>
<pre><code>self.data = map(lambda x: list(x), data)
</code></pre>
<p>and (although not so pretty)</p>
<pre><code>tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema')
</code></pre>
<p>among countless others.</p>
<p>In the irc channel, they said "too many to know them all". </p>
<p>I think we should list some here, as i love using these shortcuts to shorten & refctor my code. I'm sure this would benefit many.</p>
| 1 | 2009-06-12T04:39:21Z | 985,141 | <p>Alex Martelli provided an even shorter version of your first example. I shall provide a (slightly) shorter version of your second:</p>
<pre><code>tuple(t[0] for t in self.result if t[0] not in ('mysql', 'information_schema'))
</code></pre>
<p>Obviously the in operator becomes more advantageous the more values you're testing for.</p>
<p>I would also like to stress that shortening and refactoring is good only to the extent that it improves clarity and readability. (Unless you are code-golfing. ;)</p>
| 3 | 2009-06-12T05:24:11Z | [
"python",
"shortcut",
"refactoring"
] |
Python shortcuts | 985,026 | <p>Python is filled with little neat shortcuts.</p>
<p>For example:</p>
<pre><code>self.data = map(lambda x: list(x), data)
</code></pre>
<p>and (although not so pretty)</p>
<pre><code>tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema')
</code></pre>
<p>among countless others.</p>
<p>In the irc channel, they said "too many to know them all". </p>
<p>I think we should list some here, as i love using these shortcuts to shorten & refctor my code. I'm sure this would benefit many.</p>
| 1 | 2009-06-12T04:39:21Z | 985,952 | <p>I'm not sure if this is a shortcut, but I love it:</p>
<pre><code>>>> class Enum(object):
def __init__(self, *keys):
self.keys = keys
self.__dict__.update(zip(keys, range(len(keys))))
def value(self, key):
return self.keys.index(key)
>>> colors = Enum("Red", "Blue", "Green", "Yellow", "Purple")
>>> colors.keys
('Red', 'Blue', 'Green', 'Yellow', 'Purple')
>>> colors.Green
2
</code></pre>
<p>(I don't know who came up with this, but it wasn't me.)</p>
| 3 | 2009-06-12T10:01:58Z | [
"python",
"shortcut",
"refactoring"
] |
Python shortcuts | 985,026 | <p>Python is filled with little neat shortcuts.</p>
<p>For example:</p>
<pre><code>self.data = map(lambda x: list(x), data)
</code></pre>
<p>and (although not so pretty)</p>
<pre><code>tuple(t[0] for t in self.result if t[0] != 'mysql' and t[0] != 'information_schema')
</code></pre>
<p>among countless others.</p>
<p>In the irc channel, they said "too many to know them all". </p>
<p>I think we should list some here, as i love using these shortcuts to shorten & refctor my code. I'm sure this would benefit many.</p>
| 1 | 2009-06-12T04:39:21Z | 986,633 | <p>I always liked the "unzip" idiom:</p>
<pre><code>>>> zipped = [('a', 1), ('b', 2), ('c', 3)]
>>> zip(*zipped)
[('a', 'b', 'c'), (1, 2, 3)]
>>>
>>> l,n = zip(*zipped)
>>> l
('a', 'b', 'c')
>>> n
(1, 2, 3)
</code></pre>
| 1 | 2009-06-12T13:26:38Z | [
"python",
"shortcut",
"refactoring"
] |
How to specify native library search path for python | 985,155 | <p>I have installed lxml which was built using a standalone version of libxml2. Reason for this was that the lxml needed a later version of libxml2 than what was currently installed.</p>
<p>When I use the lxml module how do I tell it (python) where to find the correct version of the libxml2 shared library?</p>
| 4 | 2009-06-12T05:28:54Z | 985,176 | <p>Assuming you're talking about a <code>.so</code> file, it's not up to Python to find it -- it's up to the operating system's dynamic library loaded. For Linux, for example, <code>LD_LIBRARY_PATH</code> is the environment variable you need to set.</p>
| 5 | 2009-06-12T05:38:53Z | [
"python"
] |
disable a block in django | 985,224 | <p>I want to disable a block in development and use it in deployment in google apps in python development. What changes do i need to make in template or main script?</p>
| 0 | 2009-06-12T06:10:29Z | 985,268 | <p>If you've got the middleware <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-debug" rel="nofollow">django.core.content_processors.debug</a> then you can just do this in your template:</p>
<pre><code>{% block mydebugonly %}
{% if debug %}
<p>Something that will only appear if the DEBUG setting is True.</p>
{% endif %}
{% endblock %}
</code></pre>
| 3 | 2009-06-12T06:33:01Z | [
"python",
"django",
"google-app-engine"
] |
Is the pickling process deterministic? | 985,294 | <p>Does Pickle always produce the same output for a certain input value? I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories. My goal is to create a "signature" of function arguments, using Pickle and SHA1, for a memoize implementation.</p>
| 6 | 2009-06-12T06:41:15Z | 985,362 | <p>What do you mean by same output ? You should normally always get the same output for a roundtrip (pickling -> unpickling), but I don't think the serialized format itself is guaranteed to be the same in every condition. Certainly, it may change between platforms and all that.</p>
<p>Within one run of your program, using pickling for memoization should be fine - I have used this scheme several times without trouble, but that was for quite simple problems. One problem is that this does not cover every useful case (function come to mind: you cannot pickle them, so if your function takes a callable argument, that won't work).</p>
| 0 | 2009-06-12T07:04:14Z | [
"python",
"pickle",
"memoization"
] |
Is the pickling process deterministic? | 985,294 | <p>Does Pickle always produce the same output for a certain input value? I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories. My goal is to create a "signature" of function arguments, using Pickle and SHA1, for a memoize implementation.</p>
| 6 | 2009-06-12T06:41:15Z | 985,369 | <blockquote>
<p>I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories.</p>
</blockquote>
<p>Right:</p>
<pre><code>>>> pickle.dumps({1: 0, 9: 0}) == pickle.dumps({9: 0, 1: 0})
False
</code></pre>
<p>See also: <a href="http://www.aminus.org/blogs/index.php/2007/11/03/pickle%5Fdumps%5Fnot%5Fsuitable%5Ffor%5Fhashing?blog=2">pickle.dumps not suitable for hashing</a></p>
<blockquote>
<p>My goal is to create a "signature" of function arguments, using Pickle and SHA1, for a memoize implementation.</p>
</blockquote>
<p>There's a number of fundamental problems with this. It's impossible to come up with an object-to-string transformation that maps equality correctlyâthink of the problem of object identity:</p>
<pre><code>>>> a = object()
>>> b = object()
>>> a == b
False
>>> pickle.dumps(b) == pickle.dumps(a)
True
</code></pre>
<p>Depending on your exact requirements, you may be able to transform object hierarchies into ones that you could then hash:</p>
<pre><code>def hashablize(obj):
"""Convert a container hierarchy into one that can be hashed.
Don't use this with recursive structures!
Also, this won't be useful if you pass dictionaries with
keys that don't have a total order.
Actually, maybe you're best off not using this function at all."""
try:
hash(obj)
except TypeError:
if isinstance(obj, dict):
return tuple((k, hashablize(v)) for (k, v) in sorted(obj.iteritems()))
elif hasattr(obj, '__iter__'):
return tuple(hashablize(o) for o in obj)
else:
raise TypeError("Can't hashablize object of type %r" % type(obj))
else:
return obj
</code></pre>
| 7 | 2009-06-12T07:06:00Z | [
"python",
"pickle",
"memoization"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)</em>). And I have the same for ranges ]j,k[ and ]j,k]. </p>
<p>Code in those three methods look duplicated from one method to another:</p>
<pre><code>def inRange(i,j,k):
"""
Returns True if i in [j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j <= i < k
# j > k :
return j <= i or i < k
def inStrictRange(i,j,k):
"""
Returns True if i in ]j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i < k
# j > k :
return j < i or i < k
def inRange2(i,j,k):
"""
Returns True if i in ]j, k]
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i <= k
# j > k :
return j < i or i <= k
</code></pre>
<p>Do you know any cleaner way to implement those three methods? After all, only the operators are changing?!</p>
<p>After thinking of a better solution, I came up with:</p>
<pre><code>from operator import lt, le
def _compare(i,j,k, op1, op2):
if j <= k:
return op1(j,i) and op2(i,k)
return op1(j,i) or op2(i,k)
def inRange(i,j,k):
return _compare(i,j,k, le, lt)
def inStrictRange(i,j,k):
return _compare(i,j,k, lt, lt)
def inRange2(i,j,k):
return _compare(i,j,k, lt, le)
</code></pre>
<p>Is it any better? Can you come up with something more intuitive?
In short, <em>what would be the Pythonic way to write these three operators?</em></p>
<p>Also, I hate the inRange, inStrictRange, inRange2 names, but I can't think of crystal-clear names. Any ideas?</p>
<p>Thanks.</p>
| 2 | 2009-06-12T06:48:02Z | 985,331 | <p>Now I am thinking of something such as:</p>
<pre><code>def comparator(lop, rop):
def comp(i, j, k):
if j <= k:
return lop(j, i) and rop(i,k)
return lop(j, i) or rop(i,k)
return comp
from operator import le, lt
inRange = comparator(le, lt)
inStrictRange = comparator(lt, lt)
inRange2 = comparator(lt, le)
</code></pre>
<p>Which looks better indeed.</p>
| 2 | 2009-06-12T06:55:07Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)</em>). And I have the same for ranges ]j,k[ and ]j,k]. </p>
<p>Code in those three methods look duplicated from one method to another:</p>
<pre><code>def inRange(i,j,k):
"""
Returns True if i in [j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j <= i < k
# j > k :
return j <= i or i < k
def inStrictRange(i,j,k):
"""
Returns True if i in ]j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i < k
# j > k :
return j < i or i < k
def inRange2(i,j,k):
"""
Returns True if i in ]j, k]
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i <= k
# j > k :
return j < i or i <= k
</code></pre>
<p>Do you know any cleaner way to implement those three methods? After all, only the operators are changing?!</p>
<p>After thinking of a better solution, I came up with:</p>
<pre><code>from operator import lt, le
def _compare(i,j,k, op1, op2):
if j <= k:
return op1(j,i) and op2(i,k)
return op1(j,i) or op2(i,k)
def inRange(i,j,k):
return _compare(i,j,k, le, lt)
def inStrictRange(i,j,k):
return _compare(i,j,k, lt, lt)
def inRange2(i,j,k):
return _compare(i,j,k, lt, le)
</code></pre>
<p>Is it any better? Can you come up with something more intuitive?
In short, <em>what would be the Pythonic way to write these three operators?</em></p>
<p>Also, I hate the inRange, inStrictRange, inRange2 names, but I can't think of crystal-clear names. Any ideas?</p>
<p>Thanks.</p>
| 2 | 2009-06-12T06:48:02Z | 985,340 | <p>The Pythonic way to do it is to choose readability, and therefor keep the 3 methods as they were at the beginning.</p>
<p>It's not like they are HUGE methods, or there are thousand of them, or you would have to dynamically generate them.</p>
| 5 | 2009-06-12T06:58:04Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)</em>). And I have the same for ranges ]j,k[ and ]j,k]. </p>
<p>Code in those three methods look duplicated from one method to another:</p>
<pre><code>def inRange(i,j,k):
"""
Returns True if i in [j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j <= i < k
# j > k :
return j <= i or i < k
def inStrictRange(i,j,k):
"""
Returns True if i in ]j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i < k
# j > k :
return j < i or i < k
def inRange2(i,j,k):
"""
Returns True if i in ]j, k]
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i <= k
# j > k :
return j < i or i <= k
</code></pre>
<p>Do you know any cleaner way to implement those three methods? After all, only the operators are changing?!</p>
<p>After thinking of a better solution, I came up with:</p>
<pre><code>from operator import lt, le
def _compare(i,j,k, op1, op2):
if j <= k:
return op1(j,i) and op2(i,k)
return op1(j,i) or op2(i,k)
def inRange(i,j,k):
return _compare(i,j,k, le, lt)
def inStrictRange(i,j,k):
return _compare(i,j,k, lt, lt)
def inRange2(i,j,k):
return _compare(i,j,k, lt, le)
</code></pre>
<p>Is it any better? Can you come up with something more intuitive?
In short, <em>what would be the Pythonic way to write these three operators?</em></p>
<p>Also, I hate the inRange, inStrictRange, inRange2 names, but I can't think of crystal-clear names. Any ideas?</p>
<p>Thanks.</p>
| 2 | 2009-06-12T06:48:02Z | 985,388 | <p>No higher-order functions, but it's less code, even with the extraneous <code>else</code>.</p>
<pre><code>def exclusive(i, j, k):
if j <= k:
return j < i < k
else:
return j < i or i < k
def inclusive_left(i, j, k):
return i==j or exclusive(i, j, k)
def inclusive_right(i, j, k):
return i==k or exclusive(i, j, k)
</code></pre>
<p>I actually tried switching the identifiers to <code>n, a, b</code>, but the code began to look less cohesive. (My point: perfecting this code may not be a productive use of time.)</p>
| 4 | 2009-06-12T07:12:45Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)</em>). And I have the same for ranges ]j,k[ and ]j,k]. </p>
<p>Code in those three methods look duplicated from one method to another:</p>
<pre><code>def inRange(i,j,k):
"""
Returns True if i in [j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j <= i < k
# j > k :
return j <= i or i < k
def inStrictRange(i,j,k):
"""
Returns True if i in ]j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i < k
# j > k :
return j < i or i < k
def inRange2(i,j,k):
"""
Returns True if i in ]j, k]
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i <= k
# j > k :
return j < i or i <= k
</code></pre>
<p>Do you know any cleaner way to implement those three methods? After all, only the operators are changing?!</p>
<p>After thinking of a better solution, I came up with:</p>
<pre><code>from operator import lt, le
def _compare(i,j,k, op1, op2):
if j <= k:
return op1(j,i) and op2(i,k)
return op1(j,i) or op2(i,k)
def inRange(i,j,k):
return _compare(i,j,k, le, lt)
def inStrictRange(i,j,k):
return _compare(i,j,k, lt, lt)
def inRange2(i,j,k):
return _compare(i,j,k, lt, le)
</code></pre>
<p>Is it any better? Can you come up with something more intuitive?
In short, <em>what would be the Pythonic way to write these three operators?</em></p>
<p>Also, I hate the inRange, inStrictRange, inRange2 names, but I can't think of crystal-clear names. Any ideas?</p>
<p>Thanks.</p>
| 2 | 2009-06-12T06:48:02Z | 985,630 | <p>Two <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow" title="PEP 20: The Zen of Python">Zen of Python</a> principles leap to mind:</p>
<ul>
<li>Simple is better than complex.</li>
<li>There should be oneâand preferably only oneâobvious way to do it.</li>
</ul>
<h1><code>range</code></h1>
<p>The Python built-in function <code>range(start, end)</code> generates a list from <code>start</code> to <code>end</code>.<sup>1</sup> The first element of that list is <code>start</code>, and the last element is <code>end - 1</code>.</p>
<p>There is no <code>range_strict</code> function or <code>inclusive_range</code> function. This was very awkward to me when I started in Python. ("I just want a list from <code>a</code> to <code>b</code> inclusive! How hard is that, Guido?") However, the convention used in calling the <code>range</code> function was simple and easy to remember, and the lack of multiple functions made it easy to remember exactly how to generate a range every time.</p>
<h1>Recommendation</h1>
<p>As you've probably guessed, my recommendation is to only create a function to test whether <em>i</em> is in the range [<em>j</em>, <em>k</em>). In fact, my recommendation is to keep only your existing <code>inRange</code> function.</p>
<p>(Since your question specifically mentions Pythonicity, I would recommend you name the function as <code>in_range</code> to better fit with the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow" title="PEP 8: Style Guide for Python Code">Python Style Guide</a>.)</p>
<h1>Justification</h1>
<p>Why is this a good idea?</p>
<ul>
<li><p><em>The single function is easy to understand. It is very easy to learn how to use it.</em></p>
<p>Of course, the same could be said for each of your three starting functions. So far so good.</p></li>
<li><p><em>There is only one function to learn. There are not three functions with necessarily similar names.</em></p>
<p>Given the similar names and behaviours of your three functions, it is somewhat possible that you will, at some point, use the wrong function. This is compounded by the fact that the functions return the same value except for edge cases, which could lead to a hard-to-find off-by-one bug. By only making one function available, you know you will not make such a mistake.</p></li>
<li><p><em>The function is easy to edit.</em></p>
<p>It is unlikely that you'll need to ever debug or edit such an easy piece of code. However, should you need to do so, you need only edit this one function. With your original three functions, you have to make the same edit in three places. With your revised code in your self-answer, the code is made slightly less intuitive by the operator obfuscation.</p></li>
<li><p><em>The "size" of the range is obvious.</em></p>
<p>For a given ring where you would use <code>inRange(i, j, k)</code>, it is obvious how many elements would be covered by the range [<em>j</em>, <em>k</em>). Here it is in code.</p>
<pre><code>if j <= k:
size = k - j
if j > k:
size = k - j + MAX
</code></pre>
<p>So therefore</p>
<pre><code>size = (k - j) % MAX
</code></pre></li>
</ul>
<h1>Caveats</h1>
<p>I'm approaching this problem from a completely generic point of view, such as that of a person writing a function for a publicly-released library. Since I don't know your problem domain, I can't say whether this is a practical solution.</p>
<p>Using this solution may mean a fair bit of refactoring of the code that calls these functions. Look through this code to see if editing it is prohibitively difficult or tedious.</p>
<p><hr /></p>
<p><sup>1</sup>: Actually, it is <code>range([start], end, [step])</code>. I trust you get what I mean though.</p>
| 7 | 2009-06-12T08:39:00Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)</em>). And I have the same for ranges ]j,k[ and ]j,k]. </p>
<p>Code in those three methods look duplicated from one method to another:</p>
<pre><code>def inRange(i,j,k):
"""
Returns True if i in [j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j <= i < k
# j > k :
return j <= i or i < k
def inStrictRange(i,j,k):
"""
Returns True if i in ]j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i < k
# j > k :
return j < i or i < k
def inRange2(i,j,k):
"""
Returns True if i in ]j, k]
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i <= k
# j > k :
return j < i or i <= k
</code></pre>
<p>Do you know any cleaner way to implement those three methods? After all, only the operators are changing?!</p>
<p>After thinking of a better solution, I came up with:</p>
<pre><code>from operator import lt, le
def _compare(i,j,k, op1, op2):
if j <= k:
return op1(j,i) and op2(i,k)
return op1(j,i) or op2(i,k)
def inRange(i,j,k):
return _compare(i,j,k, le, lt)
def inStrictRange(i,j,k):
return _compare(i,j,k, lt, lt)
def inRange2(i,j,k):
return _compare(i,j,k, lt, le)
</code></pre>
<p>Is it any better? Can you come up with something more intuitive?
In short, <em>what would be the Pythonic way to write these three operators?</em></p>
<p>Also, I hate the inRange, inStrictRange, inRange2 names, but I can't think of crystal-clear names. Any ideas?</p>
<p>Thanks.</p>
| 2 | 2009-06-12T06:48:02Z | 989,391 | <p>To make it more familiar to your users, I would have one main in_range function with the same bounds as range(). This makes it much easier to remember, and has other nice properties as Wesley mentioned.</p>
<pre><code>def in_range(i, j, k):
return (j <= i < k) if j <= k else (j <= i or i < k)
</code></pre>
<p>You can certainly use this one alone for all your use cases by adding 1 to j and/or k. If you find that you're using a specific form frequently, then you can define it in terms of the main one:</p>
<pre><code>def exclusive(i, j, k):
"""Excludes both endpoints."""
return in_range(i, j + 1, k)
def inclusive(i, j, k):
"""Includes both endpoints."""
return in_range(i, j, k + 1)
def weird(i, j, k):
"""Excludes the left endpoint but includes the right endpoint."""
return in_range(i, j + 1, k + 1)
</code></pre>
<p>This is shorter than mucking around with operators, and is also much less confusing to understand. Also, note that you should use underscores instead of camelCase for function names in Python.</p>
| 1 | 2009-06-12T22:42:50Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)</em>). And I have the same for ranges ]j,k[ and ]j,k]. </p>
<p>Code in those three methods look duplicated from one method to another:</p>
<pre><code>def inRange(i,j,k):
"""
Returns True if i in [j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j <= i < k
# j > k :
return j <= i or i < k
def inStrictRange(i,j,k):
"""
Returns True if i in ]j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i < k
# j > k :
return j < i or i < k
def inRange2(i,j,k):
"""
Returns True if i in ]j, k]
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i <= k
# j > k :
return j < i or i <= k
</code></pre>
<p>Do you know any cleaner way to implement those three methods? After all, only the operators are changing?!</p>
<p>After thinking of a better solution, I came up with:</p>
<pre><code>from operator import lt, le
def _compare(i,j,k, op1, op2):
if j <= k:
return op1(j,i) and op2(i,k)
return op1(j,i) or op2(i,k)
def inRange(i,j,k):
return _compare(i,j,k, le, lt)
def inStrictRange(i,j,k):
return _compare(i,j,k, lt, lt)
def inRange2(i,j,k):
return _compare(i,j,k, lt, le)
</code></pre>
<p>Is it any better? Can you come up with something more intuitive?
In short, <em>what would be the Pythonic way to write these three operators?</em></p>
<p>Also, I hate the inRange, inStrictRange, inRange2 names, but I can't think of crystal-clear names. Any ideas?</p>
<p>Thanks.</p>
| 2 | 2009-06-12T06:48:02Z | 989,437 | <p>I'd go one step further than Wesley in aping the normal python 'in range' idiom; i'd write a cyclic_range class:</p>
<pre><code>import itertools
MAX = 10 # or whatever
class cyclic_range(object):
def __init__(self, start, stop):
# mod so you can be a bit sloppy with indices, plus -1 means the last element, as with list indices
self.start = start % MAX
self.stop = stop % MAX
def __len__(self):
return (self.stop - self.start) % MAX
def __getitem__(self, i):
return (self.start + i) % MAX
def __contains__(self, x):
if (self.start < self.stop):
return (x >= self.start) and (x < self.stop)
else:
return (x >= self.start) or (x < self.stop)
def __iter__(self):
for i in xrange(len(self)):
yield self[i]
def __eq__(self, other):
if (len(self) != len(other)): return False
for a, b in itertools.izip(self, other):
if (a != b): return False
return True
def __hash__(self):
return (self.start << 1) + self.stop
def __str__(self):
return str(list(self))
def __repr__(self):
return "cyclic_range(" + str(self.start) + ", " + str(self.stop) + ")"
# and whatever other list-like methods you fancy
</code></pre>
<p>You can then write code like:</p>
<pre><code>if (myIndex in cyclic_range(firstNode, stopNode)):
blah
</code></pre>
<p>To do the equivalent of inRange. To do inStrictRange, write:</p>
<pre><code>if (myIndex in cyclic_range(firstNode + 1, stopNode)):
</code></pre>
<p>And to do inRange2:</p>
<pre><code>if (myIndex in cyclic_range(firstNode + 1, stopNode + 1)):
</code></pre>
<p>If you don't like doing the additions by hand, how about adding these methods:</p>
<pre><code> def strict(self):
return cyclic_range(self.start + 1, self.stop)
def right_closed(self):
return cyclic_range(self.start + 1, self.stop + 1)
</code></pre>
<p>And then doing:</p>
<pre><code>if (myIndex in cyclic_range(firstNode, stopNode).strict()): # inStrictRange
if (myIndex in cyclic_range(firstNode, stopNode).closed_right()): # inRange2
</code></pre>
<p>Whilst this approach is, IMHO, more readable, it does involve doing an allocation, rather than just a function call, which is more expensive - although still O(1). But then if you really cared about performance, you wouldn't be using python!</p>
| 1 | 2009-06-12T22:58:17Z | [
"python",
"operators"
] |
Pythonic way to implement three similar integer range operators? | 985,309 | <p>I am working on a circular problem. In this problem, we have objects that are put on a ring of size <code>MAX</code>, and are assigned IDs from (0 to MAX-1).</p>
<p>I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is <em>i inRange(j,k)</em>). And I have the same for ranges ]j,k[ and ]j,k]. </p>
<p>Code in those three methods look duplicated from one method to another:</p>
<pre><code>def inRange(i,j,k):
"""
Returns True if i in [j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j <= i < k
# j > k :
return j <= i or i < k
def inStrictRange(i,j,k):
"""
Returns True if i in ]j, k[
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i < k
# j > k :
return j < i or i < k
def inRange2(i,j,k):
"""
Returns True if i in ]j, k]
* 0 <= i, j, k < MAX
* no order is assumed between j and k: we can have k < j
"""
if j <= k:
return j < i <= k
# j > k :
return j < i or i <= k
</code></pre>
<p>Do you know any cleaner way to implement those three methods? After all, only the operators are changing?!</p>
<p>After thinking of a better solution, I came up with:</p>
<pre><code>from operator import lt, le
def _compare(i,j,k, op1, op2):
if j <= k:
return op1(j,i) and op2(i,k)
return op1(j,i) or op2(i,k)
def inRange(i,j,k):
return _compare(i,j,k, le, lt)
def inStrictRange(i,j,k):
return _compare(i,j,k, lt, lt)
def inRange2(i,j,k):
return _compare(i,j,k, lt, le)
</code></pre>
<p>Is it any better? Can you come up with something more intuitive?
In short, <em>what would be the Pythonic way to write these three operators?</em></p>
<p>Also, I hate the inRange, inStrictRange, inRange2 names, but I can't think of crystal-clear names. Any ideas?</p>
<p>Thanks.</p>
| 2 | 2009-06-12T06:48:02Z | 989,623 | <p>I certainly agree that you need only one function, and that the function should use a (Pythonic) half-open range.</p>
<p>Two suggestions:</p>
<ol>
<li><p>Use meaningful names for the args:
in_range(x, lo, hi) is a big
improvement relative to the
2-keystroke cost.</p></li>
<li><p>Document the fact that the
constraint hi < MAX means that it is
not possible to express a range that
includes <strong>all</strong> MAX elements. As
Wesley remarked, <em>size = (k - j) %
MAX</em> i.e. <em>size = (hi - lo) % MAX</em>
and thus <em>0 <= size < MAX</em>.</p></li>
</ol>
| 2 | 2009-06-13T00:39:29Z | [
"python",
"operators"
] |
UTF-8 problem in python when reading chars | 985,486 | <p>I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?</p>
<p><em>in.txt:</em></p>
<pre><code>Stäckövérfløw
</code></pre>
<p><em>code.py</em></p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.txt','r')
for line in f:
print line
for i in line:
print i,
f.close()
</code></pre>
<p><em>output:</em></p>
<pre><code>Stäckövérfløw
S t � � c k � � v � � r f l � � w
</code></pre>
| 8 | 2009-06-12T07:39:00Z | 985,494 | <p>Check this out:</p>
<pre><code># -*- coding: utf-8 -*-
import pprint
f = open('unicode.txt','r')
for line in f:
print line
pprint.pprint(line)
for i in line:
print i,
f.close()
</code></pre>
<p>It returns this:</p>
<p>Stäckövérfløw<br />
'St\xc3\xa4ck\xc3\xb6v\xc3\xa9rfl\xc3\xb8w'<br />
S t ? ? c k ? ? v ? ? r f l ? ? w </p>
<p>The thing is that the file is just being read as a string of bytes. Iterating over them splits the multibyte characters into nonsensical byte values.</p>
| 1 | 2009-06-12T07:42:17Z | [
"python",
"utf-8"
] |
UTF-8 problem in python when reading chars | 985,486 | <p>I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?</p>
<p><em>in.txt:</em></p>
<pre><code>Stäckövérfløw
</code></pre>
<p><em>code.py</em></p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.txt','r')
for line in f:
print line
for i in line:
print i,
f.close()
</code></pre>
<p><em>output:</em></p>
<pre><code>Stäckövérfløw
S t � � c k � � v � � r f l � � w
</code></pre>
| 8 | 2009-06-12T07:39:00Z | 985,501 | <p>Use codecs.open instead, it works for me.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = codecs.open('in','r','utf8')
for line in f:
print line
for i in line:
print i,
f.close()
</code></pre>
| 2 | 2009-06-12T07:45:50Z | [
"python",
"utf-8"
] |
UTF-8 problem in python when reading chars | 985,486 | <p>I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?</p>
<p><em>in.txt:</em></p>
<pre><code>Stäckövérfløw
</code></pre>
<p><em>code.py</em></p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.txt','r')
for line in f:
print line
for i in line:
print i,
f.close()
</code></pre>
<p><em>output:</em></p>
<pre><code>Stäckövérfløw
S t � � c k � � v � � r f l � � w
</code></pre>
| 8 | 2009-06-12T07:39:00Z | 985,508 | <pre><code>for i in line:
print i,
</code></pre>
<p>When you read the file, the string you read in is a string of bytes. The for loop iterates over a single byte at a time. This causes problems with a UTF-8 encoded string, where non-ASCII characters are represented by multiple bytes. If you want to work with Unicode objects, where the characters are the basic pieces, you should use</p>
<pre><code>import codecs
f = codecs.open('in', 'r', 'utf8')
</code></pre>
<p>If <code>sys.stdout</code> doesn't already have the appropriate encoding set, you may have to wrap it:</p>
<pre><code>sys.stdout = codecs.getwriter('utf8')(sys.stdout)
</code></pre>
| 14 | 2009-06-12T07:50:00Z | [
"python",
"utf-8"
] |
UTF-8 problem in python when reading chars | 985,486 | <p>I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?</p>
<p><em>in.txt:</em></p>
<pre><code>Stäckövérfløw
</code></pre>
<p><em>code.py</em></p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.txt','r')
for line in f:
print line
for i in line:
print i,
f.close()
</code></pre>
<p><em>output:</em></p>
<pre><code>Stäckövérfløw
S t � � c k � � v � � r f l � � w
</code></pre>
| 8 | 2009-06-12T07:39:00Z | 985,523 | <pre><code>print c,
</code></pre>
<p>Adds a "blank charrecter" and breaks correct utf-8 sequences into incorrect one. So this would not work unless you write a signle byte to output</p>
<pre><code>sys.stdout.write(i)
</code></pre>
| 1 | 2009-06-12T07:56:28Z | [
"python",
"utf-8"
] |
UTF-8 problem in python when reading chars | 985,486 | <p>I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?</p>
<p><em>in.txt:</em></p>
<pre><code>Stäckövérfløw
</code></pre>
<p><em>code.py</em></p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.txt','r')
for line in f:
print line
for i in line:
print i,
f.close()
</code></pre>
<p><em>output:</em></p>
<pre><code>Stäckövérfløw
S t � � c k � � v � � r f l � � w
</code></pre>
| 8 | 2009-06-12T07:39:00Z | 20,399,153 | <p>One may want to just use </p>
<pre><code>f = open('in.txt','r')
for line in f:
print line
for i in line.decode('utf-8'):
print i,
f.close()
</code></pre>
| 0 | 2013-12-05T11:45:02Z | [
"python",
"utf-8"
] |
Locale date formatting in Python | 985,505 | <p>How do I get <code>datetime.datetime.now()</code> printed out in the native language?</p>
<pre><code> >>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
</code></pre>
<p>I'd like to get the same result but in local language.</p>
| 25 | 2009-06-12T07:48:25Z | 985,517 | <p>You can just set the locale like in this example:</p>
<pre><code>>>> import time
>>> print time.strftime("%a, %d %b %Y %H:%M:%S")
Sun, 23 Oct 2005 20:38:56
>>> import locale
>>> locale.setlocale(locale.LC_TIME, "sv_SE") # swedish
'sv_SE'
>>> print time.strftime("%a, %d %b %Y %H:%M:%S")
sön, 23 okt 2005 20:39:15
</code></pre>
| 33 | 2009-06-12T07:53:14Z | [
"python",
"date",
"locale"
] |
Locale date formatting in Python | 985,505 | <p>How do I get <code>datetime.datetime.now()</code> printed out in the native language?</p>
<pre><code> >>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
</code></pre>
<p>I'd like to get the same result but in local language.</p>
| 25 | 2009-06-12T07:48:25Z | 10,290,840 | <p>Another option is:</p>
<pre><code>>>> import locale
>>> import datetime
>>> locale.setlocale(locale.LC_TIME,'')
'es_CR.UTF-8'
>>> date_format = locale.nl_langinfo(locale.D_FMT)
>>> date_format
'%d/%m/%Y'
>>> today = datetime.date.today()
>>> today
datetime.date(2012, 4, 23)
>>> today.strftime(date_format)
'23/04/2012'
</code></pre>
| 9 | 2012-04-24T02:03:23Z | [
"python",
"date",
"locale"
] |
Locale date formatting in Python | 985,505 | <p>How do I get <code>datetime.datetime.now()</code> printed out in the native language?</p>
<pre><code> >>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
</code></pre>
<p>I'd like to get the same result but in local language.</p>
| 25 | 2009-06-12T07:48:25Z | 26,927,760 | <p>You should use <code>%x</code> and <code>%X</code> to format the date string in the correct locale. E.g. in Swedish a date is represented as <code>2014-11-14</code> instead of <code>11/14/2014</code>.</p>
<p>The correct way to get the result as Unicode is:</p>
<pre><code>locale.setlocale(locale.LC_ALL, lang)
format_ = datetime.datetime.today().strftime('%a, %x %X')
format_u = format_.decode(locale.getlocale()[1])
</code></pre>
<p>Here is the result from multiple languages:</p>
<pre><code>Bulgarian пеÑ, 14.11.2014 г. 11:21:10 Ñ.
Czech pá, 14.11.2014 11:21:10
Danish fr, 14-11-2014 11:21:10
German Fr, 14.11.2014 11:21:10
Greek ΠαÏ, 14/11/2014 11:21:10 Ïμ
English Fri, 11/14/2014 11:21:10 AM
Spanish vie, 14/11/2014 11:21:10
Estonian R, 14.11.2014 11:21:10
Finnish pe, 14.11.2014 11:21:10
French ven., 14/11/2014 11:21:10
Croatian pet, 14.11.2014. 11:21:10
Hungarian P, 2014.11.14. 11:21:10
Italian ven, 14/11/2014 11:21:10
Lithuanian Pn, 2014.11.14 11:21:10
Latvian pk, 2014.11.14. 11:21:10
Dutch vr, 14-11-2014 11:21:10
Norwegian fr, 14.11.2014 11:21:10
Polish Pt, 2014-11-14 11:21:10
Portuguese sex, 14/11/2014 11:21:10
Romanian V, 14.11.2014 11:21:10
Russian ÐÑ, 14.11.2014 11:21:10
Slovak pi, 14. 11. 2014 11:21:10
Slovenian pet, 14.11.2014 11:21:10
Swedish fr, 2014-11-14 11:21:10
Turkish Cum, 14.11.2014 11:21:10
Chinese å¨äº, 2014/11/14 11:21:10
</code></pre>
| 11 | 2014-11-14T10:22:52Z | [
"python",
"date",
"locale"
] |
Locale date formatting in Python | 985,505 | <p>How do I get <code>datetime.datetime.now()</code> printed out in the native language?</p>
<pre><code> >>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
</code></pre>
<p>I'd like to get the same result but in local language.</p>
| 25 | 2009-06-12T07:48:25Z | 32,785,195 | <p>If your application is supposed to support more than one locale then getting localized format of date/time by changing locale (by means of <code>locale.setlocale()</code>) is discouraged. For explanation why it's a bad idea see Alex Martelli's <a href="http://stackoverflow.com/a/1551834/95735">answer</a> to the the question <a href="http://stackoverflow.com/q/1551508/95735">Using Python locale or equivalent in web applications?</a> (basically locale is global and affects whole application so changing it might change behavior of other parts of application)</p>
<p>You can do it cleanly using Babel package like this:</p>
<pre><code>>>> from datetime import date, datetime, time
>>> from babel.dates import format_date, format_datetime, format_time
>>> d = date(2007, 4, 1)
>>> format_date(d, locale='en')
u'Apr 1, 2007'
>>> format_date(d, locale='de_DE')
u'01.04.2007'
</code></pre>
<p>See <a href="http://babel.pocoo.org/en/latest/dates.html" rel="nofollow">Date and Time</a> section in Babel's documentation.</p>
| 8 | 2015-09-25T15:04:19Z | [
"python",
"date",
"locale"
] |
Django: How can I change a ModelForm's Many2ManyField (select tag) choices verbose values? | 985,543 | <p>For example:</p>
<p>I have the follow model</p>
<pre><code>class Categories(models.Model):
name = models.CharField(max_length=100,verbose_name="Category Name")
parent_cat = models.ForeignKey('self',verbose_name="Parent Category",null=True,blank=True,related_name="child_cat")
description = models.TextField(verbose_name="Category Description",blank=True)
</code></pre>
<p>As one can see, this is a tree-structure table. I also have a ModelForm which consist of a ForeignKey for Categories:</p>
<pre><code>p_category = models.ForeignKey(Categories,verbose_name="Category")
</code></pre>
<p>A sample category tree like structure might be as the following:</p>
<ul>
<li>Brand
<ul>
<li>Red</li>
</ul></li>
<li>Color
<ul>
<li>Red</li>
</ul></li>
</ul>
<p>Each of them have a row in Categories. However you would noticed 2 distinct "Red" rows, both which represent different things, 1 of a red color, the other of a brand named "Red".</p>
<p>However in the ForeignKey modelform, which is represented by the tag in the form, it would show 2 similar "Red" options. This is where I hope to change the verbose value of the tag to reflect something more relevant.</p>
<p>From:</p>
<pre><code><option>Red</option>
</code></pre>
<p>To:</p>
<pre><code><option>Color > Red</option>
</code></pre>
<p>How can I do this?</p>
| 1 | 2009-06-12T08:05:10Z | 985,555 | <p>I'm not sure if this is the best way, but you could edit the Categories model so it looks like this:</p>
<pre><code>class Categories(models.Model):
name = models.CharField(max_length=100,verbose_name="Category Name")
parent_cat = models.ForeignKey('self',verbose_name="Parent Category",null=True,blank=True,related_name="child_cat")
description = models.TextField(verbose_name="Category Description",blank=True)
def __unicode__(self):
name = ''
if self.parent_cat:
name = self.parent_cat + ' &gt; '
return name + self.name
</code></pre>
<p>That should give you what you expect.</p>
| 0 | 2009-06-12T08:10:13Z | [
"python",
"django"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 986,044 | <p>In this case the variable titled <code>var</code> in the method <code>Change</code> is assigned a reference to <code>self.variable</code>, and you immediately assign a string to <code>var</code>. It's no longer pointing to <code>self.variable</code>. The following code snippet shows what would happen if you modify the data structure pointed to by <code>var</code> and <code>self.variable</code>, in this case a list:</p>
<pre><code>>>> class PassByReference:
... def __init__(self):
... self.variable = ['Original']
... self.change(self.variable)
... print self.variable
...
... def change(self, var):
... var.append('Changed')
...
>>> q = PassByReference()
['Original', 'Changed']
>>>
</code></pre>
<p>I'm sure someone else could clarify this further.</p>
| 11 | 2009-06-12T10:39:59Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 986,145 | <p>Arguments are <a href="http://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference">passed by assignment</a>. The rationale behind this is twofold:</p>
<ol>
<li>the parameter passed in is actually a <em>reference</em> to an object (but the reference is passed by value)</li>
<li>some data types are mutable, but others aren't</li>
</ol>
<p>So:</p>
<ul>
<li><p>If you pass a <em>mutable</em> object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object. </p></li>
<li><p>If you pass an <em>immutable</em> object to a method, you still can't rebind the outer reference, and you can't even mutate the object.</p></li>
</ul>
<p>To make it even more clear, let's have some examples. </p>
<h2>List - a mutable type</h2>
<p><strong>Let's try to modify the list that was passed to a method:</strong></p>
<pre><code>def try_to_change_list_contents(the_list):
print 'got', the_list
the_list.append('four')
print 'changed to', the_list
outer_list = ['one', 'two', 'three']
print 'before, outer_list =', outer_list
try_to_change_list_contents(outer_list)
print 'after, outer_list =', outer_list
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>before, outer_list = ['one', 'two', 'three']
got ['one', 'two', 'three']
changed to ['one', 'two', 'three', 'four']
after, outer_list = ['one', 'two', 'three', 'four']
</code></pre>
<p>Since the parameter passed in is a reference to <code>outer_list</code>, not a copy of it, we can use the mutating list methods to change it and have the changes reflected in the outer scope.</p>
<p><strong>Now let's see what happens when we try to change the reference that was passed in as a parameter:</strong></p>
<pre><code>def try_to_change_list_reference(the_list):
print 'got', the_list
the_list = ['and', 'we', 'can', 'not', 'lie']
print 'set to', the_list
outer_list = ['we', 'like', 'proper', 'English']
print 'before, outer_list =', outer_list
try_to_change_list_reference(outer_list)
print 'after, outer_list =', outer_list
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']
</code></pre>
<p>Since the <code>the_list</code> parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The <code>the_list</code> was a copy of the <code>outer_list</code> reference, and we had <code>the_list</code> point to a new list, but there was no way to change where <code>outer_list</code> pointed.</p>
<h2>String - an immutable type</h2>
<p><strong>It's immutable, so there's nothing we can do to change the contents of the string</strong></p>
<p><strong>Now, let's try to change the reference</strong></p>
<pre><code>def try_to_change_string_reference(the_string):
print 'got', the_string
the_string = 'In a kingdom by the sea'
print 'set to', the_string
outer_string = 'It was many and many a year ago'
print 'before, outer_string =', outer_string
try_to_change_string_reference(outer_string)
print 'after, outer_string =', outer_string
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago
</code></pre>
<p>Again, since the <code>the_string</code> parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The <code>the_string</code> was a copy of the <code>outer_string</code> reference, and we had <code>the_string</code> point to a new string, but there was no way to change where <code>outer_string</code> pointed.</p>
<p>I hope this clears things up a little.</p>
<p><strong>EDIT:</strong> It's been noted that this doesn't answer the question that @David originally asked, "Is there something I can do to pass the variable by actual reference?". Let's work on that.</p>
<h2>How do we get around this?</h2>
<p>As @Andrea's answer shows, you could return the new value. This doesn't change the way things are passed in, but does let you get the information you want back out:</p>
<pre><code>def return_a_whole_new_string(the_string):
new_string = something_to_do_with_the_old_string(the_string)
return new_string
# then you could call it like
my_string = return_a_whole_new_string(my_string)
</code></pre>
<p>If you really wanted to avoid using a return value, you could create a class to hold your value and pass it into the function or use an existing class, like a list:</p>
<pre><code>def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change):
new_string = something_to_do_with_the_old_string(stuff_to_change[0])
stuff_to_change[0] = new_string
# then you could call it like
wrapper = [my_string]
use_a_wrapper_to_simulate_pass_by_reference(wrapper)
do_something_with(wrapper[0])
</code></pre>
<p>Although this seems a little cumbersome.</p>
| 1,619 | 2009-06-12T11:18:27Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 986,335 | <p>You got some really good answers here.</p>
<pre><code>x = [ 2, 4, 4, 5, 5 ]
print x # 2, 4, 4, 5, 5
def go( li ) :
li = [ 5, 6, 7, 8 ] # re-assigning what li POINTS TO, does not
# change the value of the ORIGINAL variable x
go( x )
print x # 2, 4, 4, 5, 5 [ STILL! ]
raw_input( 'press any key to continue' )
</code></pre>
| 16 | 2009-06-12T12:16:45Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 986,339 | <p>Think of stuff being passed <strong>by assignment</strong> instead of by reference/by value. That way, it is allways clear, what is happening as long as you understand what happens during normal assignment.</p>
<p>So, when passing a list to a function/method, the list is assigned to the parameter name. Appending to the list will result in the list being modified. Reassigning the list <em>inside</em> the function will not change the original list, since:</p>
<pre><code>a = [1, 2, 3]
b = a
b.append(4)
b = ['a', 'b']
print a, b # prints [1, 2, 3, 4] ['a', 'b']
</code></pre>
<p>Since immutable types cannot be modified, they <em>seem</em> like being passed by value - passing an int into a function means assigning the int to the functions parameter. You can only ever reassign that, but it won't change the originial variables value.</p>
| 110 | 2009-06-12T12:17:48Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 986,495 | <p>It is neither pass-by-value or pass-by-reference - it is call-by-object. See this, by Fredrik Lundh: </p>
<p><a href="http://effbot.org/zone/call-by-object.htm">http://effbot.org/zone/call-by-object.htm</a></p>
<p>Here is a significant quote:</p>
<blockquote>
<p>"...variables [names] are <em>not</em> objects; they cannot be denoted by other variables or referred to by objects."</p>
</blockquote>
<p>In your example, when the <code>Change</code> method is called--a <a href="http://docs.python.org/2/tutorial/classes.html#python-scopes-and-namespaces">namespace</a> is created for it; and <code>var</code> becomes a name, within that namespace, for the string object <code>'Original'</code>. That object then has a name in two namespaces. Next, <code>var = 'Changed'</code> binds <code>var</code> to a new string object, and thus the method's namespace forgets about <code>'Original'</code>. Finally, that namespace is forgotten, and the string <code>'Changed'</code> along with it.</p>
| 190 | 2009-06-12T12:55:41Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 3,127,336 | <p>(edit - Blair has updated his enormously popular answer so that it is now accurate)</p>
<p>I think it is important to note that the current post with the most votes (by Blair Conrad), while being correct with respect to its result, is misleading and is borderline incorrect based on its definitions. While there are many languages (like C) that allow the user to either pass by reference or pass by value, Python is not one of them.</p>
<p>David Cournapeau's answer points to the real answer and explains why the behavior in Blair Conrad's post seems to be correct while the definitions are not.</p>
<p>To the extent that Python is pass by value, all languages are pass by value since some piece of data (be it a "value" or a "reference") must be sent. However, that does not mean that Python is pass by value in the sense that a C programmer would think of it.</p>
<p>If you want the behavior, Blair Conrad's answer is fine. But if you want to know the nuts and bolts of why Python is neither pass by value or pass by reference, read David Cournapeau's answer.</p>
| 29 | 2010-06-27T12:33:45Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 6,963,425 | <p>A simple trick I normally use is to just wrap it in a list:</p>
<pre><code>def Change(self, var):
var[0] = 'Changed'
variable = ['Original']
self.Change(variable)
print variable[0]
</code></pre>
<p>(Yeah I know this can be inconvenient, but sometimes it is simple enough to do this.)</p>
| 23 | 2011-08-05T22:52:00Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 8,140,747 | <p>The problem comes from a misunderstanding of what variables are in Python. If you're used to most traditional languages, you have a mental model of what happens in the following sequence:</p>
<pre><code>a = 1
a = 2
</code></pre>
<p>You believe that <code>a</code> is a memory location that stores the value <code>1</code>, then is updated to store the value <code>2</code>. That's not how things work in Python. Rather, <code>a</code> starts as a reference to an object with the value <code>1</code>, then gets reassigned as a reference to an object with the value <code>2</code>. Those two objects may continue to coexist even though <code>a</code> doesn't refer to the first one anymore; in fact they may be shared by any number of other references within the program.</p>
<p>When you call a function with a parameter, a new reference is created that refers to the object passed in. This is separate from the reference that was used in the function call, so there's no way to update that reference and make it refer to a new object. In your example:</p>
<pre><code> self.variable = 'Original'
self.Change(self.variable)
def Change(self, var):
var = 'Changed'
</code></pre>
<p><code>self.variable</code> is a reference to the string object <code>'Original'</code>. When you call <code>Change</code> you create a second reference <code>var</code> to the object. Inside the function you reassign the reference <code>var</code> to a different string object <code>'Changed'</code>, but the reference <code>self.variable</code> is separate and does not change.</p>
<p>The only way around this is to pass a mutable object. Because both references refer to the same object, any changes to the object are reflected in both places.</p>
<pre><code> self.variable = ['Original']
self.Change(self.variable)
def Change(self, var):
var[0] = 'Changed'
</code></pre>
| 345 | 2011-11-15T17:45:28Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 12,440,140 | <p>Technically, <strong>Python always uses pass by reference values</strong>. I am going to repeat <a href="http://stackoverflow.com/a/12438316/1346705">my other answer</a> to support my statement.</p>
<p>Python always uses pass-by-reference values. There isn't any exception. Any variable assignment means copying the reference value. No exception. Any variable is the name bound to the reference value. Always.</p>
<p>You can think about a reference value as the address of the target object. The address is automatically dereferenced when used. This way, working with the reference value, it seems you work directly with the target object. But there always is a reference in between, one step more to jump to the target.</p>
<p>Here is the example that proves that Python uses passing by reference:</p>
<p><img src="http://i.stack.imgur.com/uzXcP.png" alt="Illustrated example of passing the argument"></p>
<p>If the argument was passed by value, the outer <code>lst</code> could not be modified. The green are the target objects (the black is the value stored inside, the red is the object type), the yellow is the memory with the reference value inside -- drawn as the arrow. The blue solid arrow is the reference value that was passed to the function (via the dashed blue arrow path). The ugly dark yellow is the internal dictionary. (It actually could be drawn also as a green ellipse. The colour and the shape only says it is internal.)</p>
<p>You can use the <a href="http://docs.python.org/3.3/library/functions.html#id"><code>id()</code></a> built-in function to learn what the reference value is (that is, the address of the target object).</p>
<p>In compiled languages, a variable is a memory space that is able to capture the value of the type. In Python, a variable is a name (captured internally as a string) bound to the reference variable that holds the reference value to the target object. The name of the variable is the key in the internal dictionary, the value part of that dictionary item stores the reference value to the target.</p>
<p>Reference values are hidden in Python. There isn't any explicit user type for storing the reference value. However, you can use a list element (or element in any other suitable container type) as the reference variable, because all containers do store the elements also as references to the target objects. In other words, elements are actually not contained inside the container -- only the references to elements are.</p>
| 43 | 2012-09-15T18:53:57Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 12,686,527 | <p>Here is the simple (I hope) explanation of the concept <code>pass by object</code> used in Python.<br>
Whenever you pass an object to the function, the object itself is passed (object in Python is actually what you'd call a value in other programming languages) not the reference to this object. In other words, when you call:</p>
<pre><code>def change_me(list):
list = [1, 2, 3]
my_list = [0, 1]
change_me(my_list)
</code></pre>
<p>The actual object - [0, 1] (which would be called a value in other programming languages) is being passed. So in fact the function <code>change_me</code> will try to do something like:</p>
<pre><code>[0, 1] = [1, 2, 3]
</code></pre>
<p>which obviously will not change the object passed to the function. If the function looked like this:</p>
<pre><code>def change_me(list):
list.append(2)
</code></pre>
<p>Then the call would result in:</p>
<pre><code>[0, 1].append(2)
</code></pre>
<p>which obviously will change the object. <a href="http://stackoverflow.com/a/534509/831531">This answer</a> explains it well.</p>
| 4 | 2012-10-02T08:03:08Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 15,697,476 | <p>Effbot (aka Fredrik Lundh) has described Python's variable passing style as call-by-object: <a href="http://effbot.org/zone/call-by-object.htm">http://effbot.org/zone/call-by-object.htm</a></p>
<p>Objects are allocated on the heap and pointers to them can be passed around anywhere. </p>
<ul>
<li><p>When you make an assignment such as <code>x = 1000</code>, a dictionary entry is created that maps the string "x" in the current namespace to a pointer to the integer object containing one thousand. </p></li>
<li><p>When you update "x" with <code>x = 2000</code>, a new integer object is created and the dictionary is updated to point at the new object. The old one thousand object is unchanged (and may or may not be alive depending on whether anything else refers to the object).</p></li>
<li><p>When you do a new assignment such as <code>y = x</code>, a new dictionary entry "y" is created that points to the same object as the entry for "x".</p></li>
<li><p>Objects like strings and integers are <em>immutable</em>. This simply means that there are no methods that can change the object after it has been created. For example, once the integer object one-thousand is created, it will never change. Math is done by creating new integer objects.</p></li>
<li><p>Objects like lists are <em>mutable</em>. This means that the contents of the object can be changed by anything pointing to the object. For example, <code>x = []; y = x; x.append(10); print y</code> will print <code>[10]</code>. The empty list was created. Both "x" and "y" point to the same list. The <em>append</em> method mutates (updates) the list object (like adding a record to a database) and the result is visible to both "x" and "y" (just as a database update would be visible to every connection to that database).</p></li>
</ul>
<p>Hope that clarifies the issue for you. </p>
| 35 | 2013-03-29T04:41:44Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 21,684,541 | <p>As you can state you need to have a mutable object, but let me suggest you to check over the global variables as they can help you or even solve this kind of issue!</p>
<p><a href="http://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python" rel="nofollow">http://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python</a></p>
<p>example:</p>
<pre><code>>>> def x(y):
... global z
... z = y
...
>>> x
<function x at 0x00000000020E1730>
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> z
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'z' is not defined
>>> x(2)
>>> x
<function x at 0x00000000020E1730>
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> z
2
</code></pre>
| 10 | 2014-02-10T17:57:39Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 21,700,609 | <p>The key to understanding parameter passing is to stop thinking about "variables". <strong>There are no variables in Python.</strong></p>
<ol>
<li>Python has names and objects.</li>
<li>Assignment binds a name to an object.</li>
<li>Passing an argument into a function also binds a name (the parameter name of the function) to an object.</li>
</ol>
<p>That is all there is to it. Mutability is irrelevant for this question.</p>
<p>Example: </p>
<pre><code>a = 1
</code></pre>
<p>This binds the name <code>a</code> to an object of type integer that holds the value 1.</p>
<pre><code>b = x
</code></pre>
<p>This binds the name <code>b</code> to the same object that the name <code>x</code> is currently bound to.
Afterwards, the name <code>b</code> has nothing to do with the name <code>x</code> any more.</p>
<p>See sections 3.1 and 4.1 in the Python 3 language reference.</p>
<hr>
<p>So in the code shown in the question, the statement <code>self.Change(self.variable)</code> binds the name <code>var</code> (in the scope of function <code>Change</code>) to the object that holds the value <code>'Original'</code> and the assignment <code>var = 'Changed'</code> (in the body of function <code>Change</code>) assigns that same name again: to some other object (that happens to hold a string as well but could have been something else entirely).</p>
| 15 | 2014-02-11T11:29:07Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 25,670,170 | <p>I found the other answers rather long and complicated, so I created this simple diagram to explain the way Python treats variables and parameters.
<a href="http://i.stack.imgur.com/FdaCu.png"><img src="http://i.stack.imgur.com/FdaCu.png" alt="enter image description here"></a></p>
| 170 | 2014-09-04T16:05:35Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 25,810,863 | <p>A lot of insights in answers here, but i think an additional point is not clearly mentioned here explicitly. Quoting from python documentation <a href="https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python">https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python</a> </p>
<p>"In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the functionâs body, itâs assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as âglobalâ.
Though a bit surprising at first, a momentâs consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, youâd be using global all the time. Youâd have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects."</p>
<p>Even when passing a mutable object to a function this still applies. And to me clearly explains the reason for the difference in behavior between assigning to the object and operating on the object in the function.</p>
<pre><code>def test(l):
print "Received", l , id(l)
l = [0, 0, 0]
print "Changed to", l, id(l) # New local object created, breaking link to global l
l= [1,2,3]
print "Original", l, id(l)
test(l)
print "After", l, id(l)
</code></pre>
<p>gives:</p>
<pre><code>Original [1, 2, 3] 4454645632
Received [1, 2, 3] 4454645632
Changed to [0, 0, 0] 4474591928
After [1, 2, 3] 4454645632
</code></pre>
<p>The assignment to an global variable that is not declared global therefore creates a new local object and breaks the link to the original object.</p>
| 9 | 2014-09-12T14:40:18Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 29,293,411 | <p>Pythonâs pass-by-assignment scheme isnât quite the same as C++âs reference parameters option, but it turns out to be very similar to the argument-passing model of the C language (and others) in practice:</p>
<ul>
<li>Immutable arguments are effectively passed â<strong>by value</strong>.â Objects such as integers and strings are passed by object reference instead of by copying, but because you canât change immutable objects in place anyhow, the effect is much like making a copy.</li>
<li>Mutable arguments are effectively passed â<strong>by pointer</strong>.â Objects such as lists
and dictionaries are also passed by object reference, which is similar to the way C
passes arrays as pointersâmutable objects can be changed in place in the function,
much like C arrays.</li>
</ul>
| 10 | 2015-03-27T04:38:18Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 35,260,424 | <p>Aside from all the great explanations on how this stuff works in Python, I don't see a simple suggestion for the problem. As you seem to do create objects and instances, the pythonic way of handling instance variables and changing them is the following:</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change()
print self.variable
def Change(self):
self.variable = 'Changed'
</code></pre>
<p>In instance methods, you normally refer to <code>self</code> to access instance attributes. It is normal to set instance attributes in <code>__init__</code> and read or change them in instance methods. That is also why you pass <code>self</code> als the first argument to <code>def Change</code>.</p>
<p>Another solution would be to create a static method like this:</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.variable = PassByReference.Change(self.variable)
print self.variable
@staticmethod
def Change(var):
var = 'Changed'
return var
</code></pre>
| 3 | 2016-02-07T23:18:36Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 36,775,894 | <p>There is a little trick to pass an object by reference, even though the language doesn't make it possible. It works in Java too, it's the list with one item. ;-)</p>
<pre><code>class PassByReference:
def __init__(self, name):
self.name = name
def changeRef(ref):
ref[0] = PassByReference('Michael')
obj = PassByReference('Peter')
print obj.name
p = [obj] # A pointer to obj! ;-)
changeRef(p)
print p[0].name # p->name
</code></pre>
<p>It's an ugly hack, but it works. ;-P</p>
| 2 | 2016-04-21T16:47:42Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 38,834,546 | <p>I used the following method to quickly convert a couple of Fortran codes to Python. True, it's not pass by reference as the original question was posed, but is a simple work around in some cases.</p>
<pre><code>a=0
b=0
c=0
def myfunc(a,b,c):
a=1
b=2
c=3
return a,b,c
a,b,c = myfunc(a,b,c)
print a,b,c
</code></pre>
| 0 | 2016-08-08T16:46:05Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
How do I pass a variable by reference? | 986,006 | <p>The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'</p>
<pre><code>class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def Change(self, var):
var = 'Changed'
</code></pre>
<p>Is there something I can do to pass the variable by actual reference?</p>
| 1,460 | 2009-06-12T10:23:51Z | 39,054,982 | <p>While pass by reference is nothing that fits well into python and should be rarely used there are some workarounds that actually can work to get the object currently assigned to a local variable or even reassign a local variable from inside of a called function.</p>
<p>The basic idea is to have a function that can do that access and can be passed as object into other functions or stored in a class.</p>
<p>One way is to use <code>global</code> (for global variables) or <code>nonlocal</code> (for local variables in a function) in a wrapper function.</p>
<pre><code>def change(wrapper):
wrapper(7)
x = 5
def setter(val):
global x
x = val
print(x)
</code></pre>
<p>The same idea works for reading and <code>del</code>eting a variable.</p>
<p>For just reading there is even a shorter way of just using <code>lambda: x</code> which returns a callable that when called returns the current value of x. This is somewhat like "call by name" used in languages in the distant past.</p>
<p>Passing 3 wrappers to access a variable is a bit unwieldy so those can be wrapped into a class that has a proxy attribute:</p>
<pre><code>class ByRef:
def __init__(self, r, w, d):
self._read = r
self._write = w
self._delete = d
def set(self, val):
self._write(val)
def get(self):
return self._read()
def remove(self):
self._delete()
wrapped = property(get, set, remove)
# left as an exercise for the reader: define set, get, remove as local functions using global / nonlocal
r = ByRef(get, set, remove)
r.wrapped = 15
</code></pre>
<p>Pythons "reflection" support makes it possible to get a object that is capable of reassigning a name/variable in a given scope without defining functions explicitly in that scope:</p>
<pre><code>class ByRef:
def __init__(self, locs, name):
self._locs = locs
self._name = name
def set(self, val):
self._locs[self._name] = val
def get(self):
return self._locs[self._name]
def remove(self):
del self._locs[self._name]
wrapped = property(get, set, remove)
def change(x):
x.wrapped = 7
def test_me():
x = 6
print(x)
change(ByRef(locals(), "x"))
print(x)
</code></pre>
<p>Here the <code>ByRef</code> class wraps a dictionary access. So attribute access to <code>wrapped</code> is translated to a item access in the passed dictionary. By passing the result of the builtin <code>locals</code> and the name of a local variable this ends up accessing a local variable. The python documentation as of 3.5 advises that changing the dictionary might not work but it seems to work for me.</p>
| 1 | 2016-08-20T14:02:37Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] |
What does this line mean in Python? | 986,087 | <p>Which CPU information this code is trying to retrieve. This code is part of a larger package. I am not a Python programmer, and I want to convert this code to C#.</p>
<pre><code>from ctypes import c_uint, create_string_buffer, CFUNCTYPE, addressof
CPUID = create_string_buffer("\x53\x31\xc0\x40\x0f\xa2\x5b\xc3")
cpuinfo = CFUNCTYPE(c_uint)(addressof(CPUID))
print cpuinfo()
</code></pre>
<p>If you are a Python programmer and knows what this code is doing, it will be a great help for me.</p>
| 9 | 2009-06-12T10:57:21Z | 986,128 | <p>It executes the following machine code:</p>
<pre><code>push bx
xor ax, ax
inc ax
cpuid
pop bx
retn
</code></pre>
<p>Basically it calls <a href="http://en.wikipedia.org/wiki/CPUID" rel="nofollow">CPUID</a> instruction of the CPU in order to get information about the CPU. Since EAX=1 it gets the processor info and feature bits. The result 32-bit integer is then displayed on the screen, see the wikipedia article or <a href="http://www.sandpile.org/ia32/cpuid.htm" rel="nofollow">this page</a> to decode the result.</p>
<p><strong>EDIT</strong>: Since that's what you're looking for, <a href="http://devpinoy.org/blogs/cvega/archive/2006/04/07/2658.aspx" rel="nofollow">here's an excellent article about</a> invoking CPUID in a .NET/C# environment (sort of, with P/Invoke)</p>
| 24 | 2009-06-12T11:12:23Z | [
"c#",
"python",
"windows",
"cpu",
"cpuid"
] |
What does this line mean in Python? | 986,087 | <p>Which CPU information this code is trying to retrieve. This code is part of a larger package. I am not a Python programmer, and I want to convert this code to C#.</p>
<pre><code>from ctypes import c_uint, create_string_buffer, CFUNCTYPE, addressof
CPUID = create_string_buffer("\x53\x31\xc0\x40\x0f\xa2\x5b\xc3")
cpuinfo = CFUNCTYPE(c_uint)(addressof(CPUID))
print cpuinfo()
</code></pre>
<p>If you are a Python programmer and knows what this code is doing, it will be a great help for me.</p>
| 9 | 2009-06-12T10:57:21Z | 986,190 | <p>In addition to <a href="http://stackoverflow.com/questions/986087/what-does-this-line-means-in-python/986128#986128">DrJokepu</a>'s answer. The python code is using the <code>ctypes</code> modules do implement the following C code(/hack):</p>
<pre><code>char *CPUID = "\x53\x31\xc0\x40\x0f\xa2\x5b\xc3"; // x86 code
unsigned int (*cpuid)() = (unsigned int (*)()) CPUID; // CPUID points to first instruction in above code; cast it to a function pointer
printf("%u",cpuid()); // calling cpuid() effectively executes the x86 code.
</code></pre>
<p>Also note that this only returns the information in EAX and the x86 code should probably have also pushed/popped the values of ECX and EDX to be safe.</p>
| 6 | 2009-06-12T11:33:40Z | [
"c#",
"python",
"windows",
"cpu",
"cpuid"
] |
Encrypted file or db in python | 986,403 | <p>I have a sqlite3 db which i insert/select from in python. The app works great but i want to tweak it so no one can read from the DB without a password. How can i do this in python? note i have no idea where to start.</p>
| 5 | 2009-06-12T12:35:54Z | 986,515 | <p>A list of <a href="http://www.example-code.com/python/encryption.asp" rel="nofollow">Python encryption examples</a>.</p>
| 2 | 2009-06-12T12:59:18Z | [
"python",
"sqlite",
"encryption"
] |
Encrypted file or db in python | 986,403 | <p>I have a sqlite3 db which i insert/select from in python. The app works great but i want to tweak it so no one can read from the DB without a password. How can i do this in python? note i have no idea where to start.</p>
| 5 | 2009-06-12T12:35:54Z | 987,942 | <p>SQLite databases are pretty human-readable, and there isn't any built-in encryption.</p>
<p>Are you concerned about someone accessing and reading the database files directly, or accessing them through your program? </p>
<p>I'm assuming the former, because the latter isn't really database related--it's your application's security you're asking about. </p>
<p>A few options come to mind:</p>
<ol>
<li>Protect the db with filesystem permissions rather than encryption. You haven't mentioned what your environment is, so I can't say if this is workable for you or not, but it's probably the simplest and most reliable way, as you can't attempt to decrypt what you can't read.</li>
<li>Encrypt in Python before writing, and decrypt in Python after reading. Fairly simple, but you lose most of the power of SQL's set-based matching operations.</li>
<li>Switch to another database; user authentication and permissions are standard features of most multi-user databases. When you find yourself up against the limitations of a tool, it may be easier to look around at other tools rather than hacking new features into the current tool. </li>
</ol>
| 1 | 2009-06-12T17:27:54Z | [
"python",
"sqlite",
"encryption"
] |
Encrypted file or db in python | 986,403 | <p>I have a sqlite3 db which i insert/select from in python. The app works great but i want to tweak it so no one can read from the DB without a password. How can i do this in python? note i have no idea where to start.</p>
| 5 | 2009-06-12T12:35:54Z | 8,723,718 | <p>You can use SQLCipher.</p>
<p><a href="http://sqlcipher.net/">http://sqlcipher.net/</a></p>
<p>Open Source Full Database Encryption for SQLite</p>
<p>SQLCipher is an SQLite extension that provides transparent 256-bit AES encryption of database files. Pages are encrypted before being written to disk and are decrypted when read back. Due to the small footprint and great performance itâs ideal for protecting embedded application databases and is well suited for mobile development.</p>
<ol>
<li>Blazing fast performance with as little as 5-15% overhead for
encryption on many operations </li>
<li>100% of data in the database file is encrypted Uses good security
practices (CBC mode, key derivation)</li>
<li>Zero-configuration and application level cryptography Broad platform</li>
<li>support: works with C/C++, Obj-C, QT, Win32/.NET, Java, Python,
Ruby, etc on Windows, Linux, iPhone/iOSâ¦</li>
</ol>
| 9 | 2012-01-04T08:02:47Z | [
"python",
"sqlite",
"encryption"
] |
Encrypted file or db in python | 986,403 | <p>I have a sqlite3 db which i insert/select from in python. The app works great but i want to tweak it so no one can read from the DB without a password. How can i do this in python? note i have no idea where to start.</p>
| 5 | 2009-06-12T12:35:54Z | 14,290,287 | <p>I had the same problem. My application may have multiple instances running at the same time. Because of this, I can't just encrypt the sqlite db file and be done with it. I also don't believe that encrypting the data in python is a good idea, as you can't do any serious data manipulation in the database with it in this state.</p>
<p>With those constraints in mind, I have come up with the following two solutions:</p>
<p>1) Use the before mentioned SQLCipher. The problems I see here, are that I will have to write my own bindings for Python, and compile it myself (or pay the fee). I might do this in either case as it would be a great solution for other Python developers out there. If I succeed, I will post back with the solution. </p>
<p>2) If option 1 is too difficult for me, or too time consuming, I will use this method. This method is not as secure. I will use pycrypto to encrypt the database file. I will implement a SQL "server" which will decrypt the database file, then handle requests from various clients. Whenever there are no outstanding requests, it will reencrypt the database. This will be slower, over all, and leave the database in temporary decrypted states.</p>
<p>Hope these ideas help the next guy.</p>
<p><strong>EDIT 1/13/2013</strong></p>
<p>I gave up on SQLCipher because I couldn't seem to get it to compile, and the code base is trying to use OpenSSL, which while a sound library, is pretty massive of a code base for simple AES 128.</p>
<p>I found another option wxSQLite3, and I found out how to separate out just the SQLite encryption piece: <a href="https://github.com/shenghe/FreeSQLiteEncryption" rel="nofollow">https://github.com/shenghe/FreeSQLiteEncryption</a>. I was able to get this to compile and work (with the latest version of SQLite3). wxSQLite3 also support AES 256 which is really cool. My next step is going to be to attempt to compile pysqlite (which is the sqlite library that comes built into python) with the modified sqlite3.dll. If that works, I'll tweak pysqlite to support the extended, encryption piece of the wxSQLite3's sqlite3.dll. In any case, I'll try to update this thread with my results, and if successful, I'll post the final code base, with build instructions, on Github.</p>
| 1 | 2013-01-12T04:36:58Z | [
"python",
"sqlite",
"encryption"
] |
Encrypted file or db in python | 986,403 | <p>I have a sqlite3 db which i insert/select from in python. The app works great but i want to tweak it so no one can read from the DB without a password. How can i do this in python? note i have no idea where to start.</p>
| 5 | 2009-06-12T12:35:54Z | 23,161,888 | <p>As Frontware suggests, you can use sqlcipher.</p>
<p><a href="https://pypi.python.org/pypi/pysqlcipher" rel="nofollow">pysqlcipher</a> python package can make it easier to use since it uses the sqlcipher code amalgamation to compile the extension.</p>
<p>It should be just a matter of using pysqlcipher as you would use regular sqlite.dbapi2, just setting the right crypto pragmas.</p>
| 2 | 2014-04-18T20:35:24Z | [
"python",
"sqlite",
"encryption"
] |
One stop resource for : Will it play in App Engine/Python? | 986,516 | <p>Information on frameworks, languages, and libraries for GAE/J is maintained at
: <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine" rel="nofollow">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine</a></p>
<p>Is there a similar page for GAE/Py?</p>
| 1 | 2009-06-12T12:59:28Z | 987,787 | <p>From <a href="http://code.google.com/appengine/docs/python/overview.html" rel="nofollow">http://code.google.com/appengine/docs/python/overview.html</a></p>
<p>The Python runtime environment uses Python 2.5.2.</p>
<p>All code for the Python runtime environment must be pure Python, and not include any C extensions or other code that must be compiled.</p>
<p>The environment includes the Python standard library. Some modules have been disabled because their core functions are not supported by App Engine, such as networking or writing to the filesystem. In addition, the os module is available, but with unsupported features disabled. An attempt to import an unsupported module or use an unsupported feature will raise an exception.</p>
<p>A few modules from the standard library have been replaced or customized to work with App Engine. For example:</p>
<pre><code>* cPickle is aliased to pickle. Features specific to cPickle are not supported.
* marshal is empty. An import will succeed, but using it will not.
* These modules are similarly empty: imp, ftplib, select, socket
* tempfile is disabled, except for TemporaryFile which is aliased to StringIO.
* logging is available and its use is highly encouraged! See below.
</code></pre>
<p>In addition to the Python standard library and the App Engine libraries, the runtime environment includes the following third-party libraries:</p>
<pre><code>* Django 0.96.1
* WebOb 0.9
* PyYAML 3.05
</code></pre>
<p>You can include other pure Python libraries with your application by putting the code in your application directory. If you make a symbolic link to a module's directory in your application directory, appcfg.py will follow the link and include the module in your app.</p>
<p>The Python module include path includes your application's root directory (the directory containing the app.yaml file). Modules you create in your application's root directory are available using a path from the root. Don't forget to create <strong>init</strong>.py files in sub-directories, so Python will recognize the sub-directories as packages.</p>
| 4 | 2009-06-12T16:55:52Z | [
"python",
"google-app-engine",
"frameworks"
] |
Experiences of creating Social Network site in Django | 986,594 | <p>I plan to sneak in some Python/Django to my workdays and a possible social network site project seems like a good possibility.</p>
<p>Django itself seems excellent, but I am skeptical about the quality of large amount of Django apps that seem to be available.</p>
<p>I would like to hear what kind of experiences you may have had with Django in creating social network type sites. Any experiences in using any of the Django powered social network "frameworks" would also be welcome.</p>
| 13 | 2009-06-12T13:17:28Z | 986,729 | <p>If you're interested in creating a social-network site in Django, you should definitely investigate <a href="http://pinaxproject.com/">Pinax</a>. This is a project that integrates a number of apps that are useful for creating this sort of site - friends, messaging, invitations, registration, etc. They're mostly very high quality.</p>
| 26 | 2009-06-12T13:48:18Z | [
"python",
"django"
] |
Experiences of creating Social Network site in Django | 986,594 | <p>I plan to sneak in some Python/Django to my workdays and a possible social network site project seems like a good possibility.</p>
<p>Django itself seems excellent, but I am skeptical about the quality of large amount of Django apps that seem to be available.</p>
<p>I would like to hear what kind of experiences you may have had with Django in creating social network type sites. Any experiences in using any of the Django powered social network "frameworks" would also be welcome.</p>
| 13 | 2009-06-12T13:17:28Z | 990,440 | <p>Are you saying that a random survey of some posted Django apps (not Django itself) reveals that some people post code that doesn't meet your standards of quality?</p>
<p>Isn't that universally true of all code posted everywhere on the internet?</p>
<p>A random survey of any code in any language for any framework will turn up quality issues.</p>
<p>What's your <em>real</em> question? Do you think this phenomena will somehow rub off on you and taint your code with their lack of quality?</p>
| -2 | 2009-06-13T09:55:37Z | [
"python",
"django"
] |
Python thread exit code | 986,616 | <p>Is there a way to tell if a thread has exited normally or because of an exception?</p>
| 6 | 2009-06-12T13:23:42Z | 986,658 | <p>You could set some global variable to 0 if success, or non-zero if there was an exception. This is a pretty standard convention.</p>
<p>However, you'll need to protect this variable with a mutex or semaphore. Or you could make sure that only one thread will ever write to it and all others would just read it.</p>
| -1 | 2009-06-12T13:33:12Z | [
"python",
"multithreading",
"exit-code"
] |
Python thread exit code | 986,616 | <p>Is there a way to tell if a thread has exited normally or because of an exception?</p>
| 6 | 2009-06-12T13:23:42Z | 986,698 | <p>Have your thread function catch exceptions. (You can do this with a simple wrapper function that just calls the old thread function inside a <code>try</code>...<code>except</code> or <code>try</code>...<code>except</code>...<code>else</code> block). Then the question just becomes "how to pass information from one thread to another", and I guess you already know how to do that.</p>
| 0 | 2009-06-12T13:43:05Z | [
"python",
"multithreading",
"exit-code"
] |
Python thread exit code | 986,616 | <p>Is there a way to tell if a thread has exited normally or because of an exception?</p>
| 6 | 2009-06-12T13:23:42Z | 987,139 | <p>As mentioned, a wrapper around the Thread class could catch that state. Here's an example.</p>
<pre><code>>>> from threading import Thread
>>> class MyThread(Thread):
def run(self):
try:
Thread.run(self)
except Exception as self.err:
pass # or raise
else:
self.err = None
>>> mt = MyThread(target=divmod, args=(3, 2))
>>> mt.start()
>>> mt.join()
>>> mt.err
>>> mt = MyThread(target=divmod, args=(3, 0))
>>> mt.start()
>>> mt.join()
>>> mt.err
ZeroDivisionError('integer division or modulo by zero',)
</code></pre>
| 8 | 2009-06-12T15:03:59Z | [
"python",
"multithreading",
"exit-code"
] |
Using pysmbc to read files over samba | 986,730 | <p>I am using the python-smbc library on Ubuntu to access a samba share. I can access the directory structure fine, I am however not sure how to access actual files and their content. The webpage (https://fedorahosted.org/pysmbc/) doesn't mention any thing, the code is in C/C++, with little documentation, so I am not quite sure how to use it.</p>
<p>What I know is that Context.open (for files) takes uri, flags and mode, but what flags and mode are, I don't know.</p>
<p>Has anyone used this library, or have examples off how to read files using it?</p>
<p>The ideal situation had of course been to use smbfs mounts, but when I mount the same share using smbmount, all folders are empty. Though I can browse it with smbclient fine using the same credentials.</p>
| 4 | 2009-06-12T13:48:29Z | 988,766 | <p>I would stick with smbfs. It's only a matter of time before you want to access those shared files with something other than Python.</p>
| -2 | 2009-06-12T20:02:38Z | [
"python",
"samba"
] |
Using pysmbc to read files over samba | 986,730 | <p>I am using the python-smbc library on Ubuntu to access a samba share. I can access the directory structure fine, I am however not sure how to access actual files and their content. The webpage (https://fedorahosted.org/pysmbc/) doesn't mention any thing, the code is in C/C++, with little documentation, so I am not quite sure how to use it.</p>
<p>What I know is that Context.open (for files) takes uri, flags and mode, but what flags and mode are, I don't know.</p>
<p>Has anyone used this library, or have examples off how to read files using it?</p>
<p>The ideal situation had of course been to use smbfs mounts, but when I mount the same share using smbmount, all folders are empty. Though I can browse it with smbclient fine using the same credentials.</p>
| 4 | 2009-06-12T13:48:29Z | 989,430 | <p>I also have had trouble using smbfs (random system lockdowns and reboots) and needed a quick answer.</p>
<p>I've also tried the <code>smbc</code> module but couldn't get any data with it. I went just as far as accessing the directory structure, just like you.</p>
<p>Time was up and I had to deliver the code, so I took a shortcut:</p>
<p>I wrote a small wrapper around a "<code>smbclient</code>" call. It is a hack, ugly, <strong>really ugly</strong>, but it works for my needs. It is being used in production on the company I work.</p>
<p>Here's some example usage:</p>
<pre><code>>>> smb = smbclient.SambaClient(server="MYSERVER", share="MYSHARE",
username='foo', password='bar', domain='baz')
>>> print smb.listdir(u"/")
[u'file1.txt', u'file2.txt']
>>> f = smb.open('/file1.txt')
>>> data = f.read()
>>> f.close()
>>> smb.rename(u'/file1.txt', u'/file1.old')
</code></pre>
<p>The programmer before me was using a "bash" file with lots of smbclient calls,
so I think my solution is at least better.</p>
<p>I have uploaded it <a href="http://pypi.python.org/pypi/PySmbClient">here</a>, so you can use it if you want. Bitbucket repository is <a href="http://bitbucket.org/nosklo/pysmbclient/">here</a>. If you find a better solution please tell me and I'll replace my code too.</p>
| 10 | 2009-06-12T22:56:51Z | [
"python",
"samba"
] |
Using pysmbc to read files over samba | 986,730 | <p>I am using the python-smbc library on Ubuntu to access a samba share. I can access the directory structure fine, I am however not sure how to access actual files and their content. The webpage (https://fedorahosted.org/pysmbc/) doesn't mention any thing, the code is in C/C++, with little documentation, so I am not quite sure how to use it.</p>
<p>What I know is that Context.open (for files) takes uri, flags and mode, but what flags and mode are, I don't know.</p>
<p>Has anyone used this library, or have examples off how to read files using it?</p>
<p>The ideal situation had of course been to use smbfs mounts, but when I mount the same share using smbmount, all folders are empty. Though I can browse it with smbclient fine using the same credentials.</p>
| 4 | 2009-06-12T13:48:29Z | 11,393,225 | <p>Provided you have an open context (see the unit tests here)<br>
* <a href="https://github.com/ioggstream/pysmbc/tree/master/tests" rel="nofollow">https://github.com/ioggstream/pysmbc/tree/master/tests</a></p>
<pre><code>suri = 'smb://' + settings.SERVER + '/' + settings.SHARE + '/test.dat'
dpath = '/tmp/destination.out'
# open smbc uri
sfile = ctx.open(suri, os.O_RDONLY)
# open local target where to copy file
dfile = open(dpath, 'wb')
#copy file and flush
dfile.write(sfile.read())
dfile.flush()
#close both files
sfile.close()
dfile.close()
</code></pre>
<p>To open a context just define an authentication function</p>
<pre><code>ctx = smbc.Context()
def auth_fn(server, share, workgroup, username, password):
return (workgroup, settings.USERNAME, settings.PASSWORD)
ctx.optionNoAutoAnonymousLogin = True
ctx.functionAuthData = auth_fn
</code></pre>
| 0 | 2012-07-09T10:27:23Z | [
"python",
"samba"
] |
Using pysmbc to read files over samba | 986,730 | <p>I am using the python-smbc library on Ubuntu to access a samba share. I can access the directory structure fine, I am however not sure how to access actual files and their content. The webpage (https://fedorahosted.org/pysmbc/) doesn't mention any thing, the code is in C/C++, with little documentation, so I am not quite sure how to use it.</p>
<p>What I know is that Context.open (for files) takes uri, flags and mode, but what flags and mode are, I don't know.</p>
<p>Has anyone used this library, or have examples off how to read files using it?</p>
<p>The ideal situation had of course been to use smbfs mounts, but when I mount the same share using smbmount, all folders are empty. Though I can browse it with smbclient fine using the same credentials.</p>
| 4 | 2009-06-12T13:48:29Z | 13,457,331 | <p>If you've managed to get the directory structure then you have a working context. The key to actually accessing files is the undocumented flags argument of <code>Context.open</code>. (I haven't figured out what mode is for either but it doesn't seem necessary.)</p>
<p><code>flags</code> is how you tell pysmbc what type of access to the file you want. You do that by passing it an integer made by bitwise ORing (<code>|</code>) flags from the os module together. Specifically the flags you want or suffixed with <code>os.O_</code> (see a list in the Python documentation <a href="http://docs.python.org/2/library/os.html#open-flag-constants" rel="nofollow">here</a>). </p>
<p>For example, to write to a file you would set flags to <code>os.O_WRONLY</code> (equiavlent to using <code>"w"</code> as the mode parameter of the built in <code>open</code> function) and to append to a file that might already exist use <code>os.O_WRONLY | os.O_APPEND | os.O_CREAT</code> (equivalent to <code>"a+"</code>).</p>
<p>That call will then return a <code>file</code> object which you can use like any normal, local file.</p>
| 0 | 2012-11-19T15:50:31Z | [
"python",
"samba"
] |
Using pysmbc to read files over samba | 986,730 | <p>I am using the python-smbc library on Ubuntu to access a samba share. I can access the directory structure fine, I am however not sure how to access actual files and their content. The webpage (https://fedorahosted.org/pysmbc/) doesn't mention any thing, the code is in C/C++, with little documentation, so I am not quite sure how to use it.</p>
<p>What I know is that Context.open (for files) takes uri, flags and mode, but what flags and mode are, I don't know.</p>
<p>Has anyone used this library, or have examples off how to read files using it?</p>
<p>The ideal situation had of course been to use smbfs mounts, but when I mount the same share using smbmount, all folders are empty. Though I can browse it with smbclient fine using the same credentials.</p>
| 4 | 2009-06-12T13:48:29Z | 37,755,535 | <p>If don't know if this is more clearly stated, but here's what I gleaned from this page and sorted out from a little extra Google-ing:</p>
<pre><code>def do_auth (server, share, workgroup, username, password):
return ('MYDOMAIN', 'myacct', 'mypassword')
# Create the context
ctx = smbc.Context (auth_fn=do_auth)
destfile = "myfile.txt"
source = open('/home/myuser/textfile.txt', 'r')
# open a SMB/CIFS file and write to it
file = ctx.open ('smb://server/share/folder/'+destfile, os.O_CREAT | os.O_WRONLY)
for line in source:
file.write (line)
file.close()
source.close()
# open a SMB/CIFS file and read it to a local file
source = ctx.open ('smb://server/share/folder/'+destfile, os.O_RDONLY)
destfile = "/home/myuser/textfile.txt"
fle = open(destfile, 'w')
for line in source:
file.write (line)
file.close()
source.close()
</code></pre>
| 0 | 2016-06-10T19:06:47Z | [
"python",
"samba"
] |
How do I get a value node moved up to be an attribute of its parent node? | 986,925 | <p>What do I need to change so the Name node under FieldRef is an attribute of FieldRef, and not a child node?</p>
<p>Suds currently generates the following soap:</p>
<pre><code><ns0:query>
<ns0:Where>
<ns0:Eq>
<ns0:FieldRef>
<ns0:Name>_ows_ID</ns0:Name>
</ns0:FieldRef>
<ns0:Value>66</ns0:Value>
</ns0:Eq>
</ns0:Where>
</ns0:query>
</code></pre>
<p>What I need is this:</p>
<pre><code><ns0:query>
<ns0:Where>
<ns0:Eq>
<ns0:FieldRef Name="_ows_ID">
</ns0:FieldRef>
<ns0:Value>66</ns0:Value>
</ns0:Eq>
</ns0:Where>
</ns0:query>
</code></pre>
<p>The first xml structure is generated by suds from the below code.</p>
<pre><code>q = c.factory.create('GetListItems.query')
q['Where']=InstFactory.object('Where')
q['Where']['Eq']=InstFactory.object('Eq')
q['Where']['Eq']['FieldRef']=InstFactory.object('FieldRef')
q['Where']['Eq']['FieldRef'].Name='_ows_ID'
q['Where']['Eq']['Value']='66'
</code></pre>
<p>and <code>print(q)</code> results in </p>
<pre><code>(query){
Where =
(Where){
Eq =
(Eq){
FieldRef =
(FieldRef){
Name = "_ows_ID"
}
Value = "66"
}
}
}
</code></pre>
<p>Here's the code that makes the WS call that creates the soap request</p>
<pre><code>c = client.Client(url='https://community.site.edu/_vti_bin/Lists.asmx?WSDL',
transport=WindowsHttpAuthenticated(username='domain\user',
password='password')
)
ll= c.service.GetListItems(listName="{BD59F6D9-AB4B-474D-BCC7-E4B4BEA7EB27}",
viewName="{407A6AB9-97CF-4E1F-8544-7DD67CEA997B}",
query=q
)
</code></pre>
| 0 | 2009-06-12T14:27:37Z | 987,501 | <pre><code>from suds.sax.element import Element
#create the nodes
q = Element('query')
where=Element('Where')
eq=Element('Eq')
fieldref=Element('FieldRef')
fieldref.set('Name', '_ows_ID')
value=Element('Value')
value.setText('66')
#append them
eq.append(fieldref)
eq.append(value)
where.append(eq)
q.append(where)
</code></pre>
<p><a href="https://fedorahosted.org/suds/wiki/TipsAndTricks" rel="nofollow">https://fedorahosted.org/suds/wiki/TipsAndTricks</a></p>
<blockquote>
<p>Including Literal XML</p>
<p>To include literal (not escaped) XML
as a parameter value of object
attribute, you need to set the value
of the parameter of the object
attribute to be a sax Element. The
marshaller is designed to simply
attach and append content that is
already XML.</p>
<p>For example, you want to pass the
following XML as a parameter:</p>
<p><code><query> <name>Elmer Fudd</name></code><br />
<code><age unit="years">33</age></code><br />
<code><job>Wabbit Hunter</job> </query></code></p>
<p>The can be done as follows:</p>
<pre><code>from suds.sax.element import Element
query = Element('query')
name = Element('name').setText('Elmer Fudd')
age = Element('age').setText('33')
age.set('units', 'years')
job = Element('job').setText('Wabbit Hunter')
query.append(name)
query.append(age)
query.append(job)
client.service.runQuery(query)
</code></pre>
</blockquote>
| 0 | 2009-06-12T15:59:48Z | [
"python",
"soap",
"suds"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 987,253 | <p>Using Python you can use <a href="http://docs.python.org/library/urllib.html" rel="nofollow">urllib</a> to download webpages and use the version value to change the user-agent.</p>
<p>There is a very good example on <a href="http://wolfprojects.altervista.org/changeua.php" rel="nofollow">http://wolfprojects.altervista.org/changeua.php</a></p>
<p>Here is an example copied from that page:</p>
<pre><code>>>> from urllib import FancyURLopener
>>> class MyOpener(FancyURLopener):
... version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11)
Gecko/20071127 Firefox/2.0.0.11'
>>> myopener = MyOpener()
>>> page = myopener.open('http://www.google.com/search?q=python')
>>> page.read()
[â¦]Results <b>1</b> - <b>10</b> of about <b>81,800,000</b> for <b>python</b>[â¦]
</code></pre>
| 2 | 2009-06-12T15:22:12Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 987,257 | <p>I assume you mean a user-agent string in an HTTP request? This is just an HTTP header that gets sent along with your request.</p>
<p>using Python's urllib2:</p>
<pre><code>import urllib2
url = 'http://foo.com/'
# add a header to define a custon User-Agent
headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' }
req = urllib2.Request(url, '', headers)
response = urllib2.urlopen(req).read()
</code></pre>
| 7 | 2009-06-12T15:22:40Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 987,271 | <p>In <code>urllib</code>, it's done like this:</p>
<pre><code>import urllib
class AppURLopener(urllib.FancyURLopener):
version = "MyStrangeUserAgent"
urllib._urlopener = AppURLopener()
</code></pre>
<p>and then just use <code>urllib.urlopen</code> normally. In <code>urllib2</code>, use <code>req = urllib2.Request(...)</code> with a parameter of <code>headers=somedict</code> to set all the headers you want (including user agent) in the new request object <code>req</code> that you make, and <code>urllib2.urlopen(req)</code>.</p>
<p>Other ways of sending HTTP requests have other ways of specifying headers, of course.</p>
| 3 | 2009-06-12T15:24:28Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 987,297 | <p>If you want to change the user agent string you send when opening web pages, google around for a Firefox plugin. ;) For example, I found <a href="https://addons.mozilla.org/en-US/firefox/addon/59" rel="nofollow">this one</a>. Or you could write a proxy server in Python, which changes all your requests independent of the browser.</p>
<p>My point is, changing the string is going to be the easy part; your first question should be, <em>where do I need to change it?</em> If you already know that (at the browser? proxy server? on the router between you and the web servers you're hitting?), we can probably be more helpful. Or, if you're just doing this inside a script, go with any of the <code>urllib</code> answers. ;)</p>
| 0 | 2009-06-12T15:28:03Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 987,360 | <p><code>urllib2</code> is nice because it's built in, but I tend to use <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> when I have the choice. It extends a lot of <code>urllib2</code>'s functionality (though much of it has been added to python in recent years). Anyhow, if it's what you're using, here's an example from their docs on how you'd change the user-agent string:</p>
<pre><code>import mechanize
cookies = mechanize.CookieJar()
opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies))
opener.addheaders = [("User-agent", "Mozilla/5.0 (compatible; MyProgram/0.1)"),
("From", "responsible.person@example.com")]
</code></pre>
<p>Best of luck.</p>
| 2 | 2009-06-12T15:38:03Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 8,666,088 | <p>Updated for Python 3.2 (py3k):</p>
<pre><code>import urllib.request
headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' }
url = 'http://www.google.com'
request = urllib.request.Request(url, b'', headers)
response = urllib.request.urlopen(request).read()
</code></pre>
| 0 | 2011-12-29T09:36:56Z | [
"python",
"user-agent"
] |
How can I change a user agent string programmatically? | 987,217 | <p>I would like to write a program that changes my user agent string.</p>
<p>How can I do this in Python?</p>
| 4 | 2009-06-12T15:15:56Z | 20,447,014 | <p>As mentioned in the answers above, the user-agent field in the http request header can be changed using builtin modules in python such as urllib2. At the same time, it is also important to analyze what exactly the web server sees. A recent post on <a href="http://remotalks.blogspot.com/2013/12/user-agent-method-used-by-webservers-to.html" rel="nofollow" title="user agent detection">User agent detection</a> gives a sample code and output, which gives a description of what the web server sees when a programmatic request is sent.</p>
| 1 | 2013-12-07T21:39:02Z | [
"python",
"user-agent"
] |
adding a **kwarg to a class | 987,237 | <pre><code>class StatusForm(ModelForm):
bases = forms.ModelMultipleChoiceField(
queryset=Base.objects.all(), #this should get overwritten
widget=forms.SelectMultiple,
)
class Meta:
model = HiringStatus
exclude = ('company', 'date')
def __init__(self, *args, **kwargs):
super(StatusForm, self).__init__(*args, **kwargs)
if kwargs.has_key('bases_queryset'):
self.fields['bases'].queryset = kwargs['bases_queryset']
</code></pre>
<p>I want to add an option to this form that allows me to create a form like so:</p>
<pre><code>form = StatusForm(bases_queryset=Base.objects.filter([...])
</code></pre>
<p>But I somehow need to "add" that keyword argument to the class so it will be recognized. They way it is now, I just get this error:</p>
<p><strong><code>__init__() got an unexpected keyword argument 'bases_queryset'</code></strong></p>
| 3 | 2009-06-12T15:19:15Z | 987,268 | <p>That's because you're unpacking kwargs to the super constructor.
Try to put this before calling super:</p>
<pre><code>if kwargs.has_key('bases_queryset'):
bases_queryset = kwargs['bases_queryset']
del kwargs['bases_queryset']
</code></pre>
<p>but it's not an ideal solution...</p>
| 11 | 2009-06-12T15:24:18Z | [
"python",
"django"
] |
adding a **kwarg to a class | 987,237 | <pre><code>class StatusForm(ModelForm):
bases = forms.ModelMultipleChoiceField(
queryset=Base.objects.all(), #this should get overwritten
widget=forms.SelectMultiple,
)
class Meta:
model = HiringStatus
exclude = ('company', 'date')
def __init__(self, *args, **kwargs):
super(StatusForm, self).__init__(*args, **kwargs)
if kwargs.has_key('bases_queryset'):
self.fields['bases'].queryset = kwargs['bases_queryset']
</code></pre>
<p>I want to add an option to this form that allows me to create a form like so:</p>
<pre><code>form = StatusForm(bases_queryset=Base.objects.filter([...])
</code></pre>
<p>But I somehow need to "add" that keyword argument to the class so it will be recognized. They way it is now, I just get this error:</p>
<p><strong><code>__init__() got an unexpected keyword argument 'bases_queryset'</code></strong></p>
| 3 | 2009-06-12T15:19:15Z | 987,307 | <p>As @Keeper indicates, you must not pass your "new" keyword arguments to the superclass. Best may be to do, before you call super's <code>__init__</code>:</p>
<pre><code>bqs = kwargs.pop('bases_queryset', None)
</code></pre>
<p>and after that <code>__init__</code> call, check <code>if bqs is not None:</code> instead of using <code>has_key</code> (and use <code>bqs</code> instead of <code>kwargs['bases_queryset']</code>, of course).</p>
<p>An interesting alternative approach is to make a "selective call" higher-order function. It's a bit of a mess if you have both positional and named arguments (that's <em>always</em> a bit messy to metaprogram around;-), so for simplicity of exposition assume the function you want to selectively call only has "normal" named arguments (i.e. no <code>**k</code> either). Now:</p>
<pre><code>import inspect
def selective_call(func, **kwargs):
names, _, _, _ = inspect.getargspec(func)
usable_kwargs = dict((k,kwargs[k]) for k in names if k in kwargs)
return func(**usable_kwargs)
</code></pre>
<p>with this approach, in your <code>__init__</code>, instead of calling super's <code>__init__</code> directly, you'd call
<code>selective_call(super_init, **kwargs)</code> and let this higher-order function do the needed "pruning". (Of course, you <em>will</em> need to make it messier to handle both positional and named args, ah well...!-)</p>
| 11 | 2009-06-12T15:29:33Z | [
"python",
"django"
] |
orbited twisted installation problems | 987,632 | <p>i am geting folloing error when i am trying to start orbited server</p>
<pre><code>C:\Python26\Scripts>orbited
Traceback (most recent call last):
File "C:\Python26\Scripts\orbited-script.py", line 8, in <module>
load_entry_point('orbited==0.7.9', 'console_scripts', 'orbited')()
File "C:\Python26\lib\site-packages\orbited-0.7.9-py2.6.egg\orbited\start.py",
line 84, in main
install = _import('twisted.internet.%sreactor.install' % reactor_name)
File "C:\Python26\lib\site-packages\orbited-0.7.9-py2.6.egg\orbited\start.py",
line 13, in _import
return reduce(getattr, name.split('.')[1:], __import__(module_import))
File "C:\Python26\lib\site-packages\twisted\internet\selectreactor.py", line 2
1, in <module>
from twisted.internet import posixbase
File "C:\Python26\lib\site-packages\twisted\internet\posixbase.py", line 25, i
n <module>
from twisted.internet import tcp, udp
File "C:\Python26\lib\site-packages\twisted\internet\tcp.py", line 78, in <mod
ule>
from twisted.internet import defer, base, address
File "C:\Python26\lib\site-packages\twisted\internet\defer.py", line 17, in <m
odule>
from twisted.python import log, failure, lockfile
File "C:\Python26\lib\site-packages\twisted\python\lockfile.py", line 28, in <
module>
from win32api import OpenProcess
ImportError: No module named win32api
C:\Python26\Scripts>
</code></pre>
<p>i am using windows vista. i seacrche on net and found that i sholld copy 2 file in system32 , when i tried to do so i found that those files were already present there. But am still geting the errror.</p>
<p>how wold i install win32api on vista?</p>
| 1 | 2009-06-12T16:25:56Z | 987,840 | <p>I'd start by installing <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">the win32 extensions</a>. If you have done so already, this is probably a path issue.</p>
| 2 | 2009-06-12T17:07:27Z | [
"python",
"twisted"
] |
How can I change a user agent string programmatically? | 987,802 | <p>I want to write a program that changes the HTTP headers in my requests that are sent by my web-browser. I believe it can be done with a proxy server. So, I'd like to write a proxy server. </p>
<p>How can I do this in Python?</p>
| 1 | 2009-06-12T16:59:36Z | 987,812 | <p>Why not use an existing proxy such as <a href="http://www.charlesproxy.com/" rel="nofollow">Charles HTTP Proxy</a>? It has the ability to rewrite headers and do all sorts of cool stuff to requests and responses.</p>
| 2 | 2009-06-12T17:02:10Z | [
"python"
] |
How can I change a user agent string programmatically? | 987,802 | <p>I want to write a program that changes the HTTP headers in my requests that are sent by my web-browser. I believe it can be done with a proxy server. So, I'd like to write a proxy server. </p>
<p>How can I do this in Python?</p>
| 1 | 2009-06-12T16:59:36Z | 987,817 | <p><a href="http://proxies.xhaus.com/" rel="nofollow">This</a> is a list of HTTP proxies in python.</p>
| 1 | 2009-06-12T17:02:47Z | [
"python"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on google.com server, the generated <code>abc.jpg</code> is not a valid jpg file, it's actually a html page . I guess the returned headers (a httplib.HTTPMessage instance) can be used to actually tell whether the retrieval successes or not, but I can't find any doc for <code>httplib.HTTPMessage</code>.</p>
<p>Can anybody provide some information about this problem?</p>
| 41 | 2009-06-12T17:15:33Z | 987,914 | <p>According to the documentation is is <a href="http://bugs.python.org/issue3428" rel="nofollow">undocumented</a></p>
<p>to get access to the message it looks like you do something like:</p>
<pre><code>a, b=urllib.urlretrieve('http://google.com/abc.jpg', r'c:\abc.jpg')
</code></pre>
<p>b is the message instance</p>
<p>Since I have learned that Python it is always useful to use Python's ability to be introspective when I type </p>
<pre><code>dir(b)
</code></pre>
<p>I see lots of methods or functions to play with</p>
<p>And then I started doing things with b</p>
<p>for example </p>
<pre><code>b.items()
</code></pre>
<p>Lists lots of interesting things, I suspect that playing around with these things will allow you to get the attribute you want to manipulate.</p>
<p>Sorry this is such a beginner's answer but I am trying to master how to use the introspection abilities to improve my learning and your questions just popped up.</p>
<p>Well I tried something interesting related to this-I was wondering if I could automatically get the output from each of the things that showed up in the directory that did not need parameters so I wrote:</p>
<pre><code>needparam=[]
for each in dir(b):
x='b.'+each+'()'
try:
eval(x)
print x
except:
needparam.append(x)
</code></pre>
| 3 | 2009-06-12T17:21:43Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on google.com server, the generated <code>abc.jpg</code> is not a valid jpg file, it's actually a html page . I guess the returned headers (a httplib.HTTPMessage instance) can be used to actually tell whether the retrieval successes or not, but I can't find any doc for <code>httplib.HTTPMessage</code>.</p>
<p>Can anybody provide some information about this problem?</p>
| 41 | 2009-06-12T17:15:33Z | 988,339 | <p>Consider using <code>urllib2</code> if it possible in your case. It is more advanced and easy to use than <code>urllib</code>.</p>
<p>You can detect any HTTP errors easily:</p>
<pre><code>>>> import urllib2
>>> resp = urllib2.urlopen("http://google.com/abc.jpg")
Traceback (most recent call last):
<<MANY LINES SKIPPED>>
urllib2.HTTPError: HTTP Error 404: Not Found
</code></pre>
<p><code>resp</code> is actually <code>HTTPResponse</code> object that you can do a lot of useful things with:</p>
<pre><code>>>> resp = urllib2.urlopen("http://google.com/")
>>> resp.code
200
>>> resp.headers["content-type"]
'text/html; charset=windows-1251'
>>> resp.read()
"<<ACTUAL HTML>>"
</code></pre>
| 20 | 2009-06-12T18:46:04Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on google.com server, the generated <code>abc.jpg</code> is not a valid jpg file, it's actually a html page . I guess the returned headers (a httplib.HTTPMessage instance) can be used to actually tell whether the retrieval successes or not, but I can't find any doc for <code>httplib.HTTPMessage</code>.</p>
<p>Can anybody provide some information about this problem?</p>
| 41 | 2009-06-12T17:15:33Z | 990,378 | <p>I ended up with my own <code>retrieve</code> implementation, with the help of <code>pycurl</code> it supports more protocols than urllib/urllib2, hope it can help other people.</p>
<pre><code>import tempfile
import pycurl
import os
def get_filename_parts_from_url(url):
fullname = url.split('/')[-1].split('#')[0].split('?')[0]
t = list(os.path.splitext(fullname))
if t[1]:
t[1] = t[1][1:]
return t
def retrieve(url, filename=None):
if not filename:
garbage, suffix = get_filename_parts_from_url(url)
f = tempfile.NamedTemporaryFile(suffix = '.' + suffix, delete=False)
filename = f.name
else:
f = open(filename, 'wb')
c = pycurl.Curl()
c.setopt(pycurl.URL, str(url))
c.setopt(pycurl.WRITEFUNCTION, f.write)
try:
c.perform()
except:
filename = None
finally:
c.close()
f.close()
return filename
</code></pre>
| 1 | 2009-06-13T09:18:53Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on google.com server, the generated <code>abc.jpg</code> is not a valid jpg file, it's actually a html page . I guess the returned headers (a httplib.HTTPMessage instance) can be used to actually tell whether the retrieval successes or not, but I can't find any doc for <code>httplib.HTTPMessage</code>.</p>
<p>Can anybody provide some information about this problem?</p>
| 41 | 2009-06-12T17:15:33Z | 1,993,124 | <p>You can create a new URLopener (inherit from FancyURLopener) and throw exceptions or handle errors any way you want. Unfortunately, FancyURLopener ignores 404 and other errors. See this question:</p>
<p><a href="http://stackoverflow.com/questions/1308542/how-to-catch-404-error-in-urllib-urlretrieve">http://stackoverflow.com/questions/1308542/how-to-catch-404-error-in-urllib-urlretrieve</a></p>
| 1 | 2010-01-02T22:36:30Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on google.com server, the generated <code>abc.jpg</code> is not a valid jpg file, it's actually a html page . I guess the returned headers (a httplib.HTTPMessage instance) can be used to actually tell whether the retrieval successes or not, but I can't find any doc for <code>httplib.HTTPMessage</code>.</p>
<p>Can anybody provide some information about this problem?</p>
| 41 | 2009-06-12T17:15:33Z | 9,740,603 | <p>I keep it simple:</p>
<pre><code># Simple downloading with progress indicator, by Cees Timmerman, 16mar12.
import urllib2
remote = r"http://some.big.file"
local = r"c:\downloads\bigfile.dat"
u = urllib2.urlopen(remote)
h = u.info()
totalSize = int(h["Content-Length"])
print "Downloading %s bytes..." % totalSize,
fp = open(local, 'wb')
blockSize = 8192 #100000 # urllib.urlretrieve uses 8192
count = 0
while True:
chunk = u.read(blockSize)
if not chunk: break
fp.write(chunk)
count += 1
if totalSize > 0:
percent = int(count * blockSize * 100 / totalSize)
if percent > 100: percent = 100
print "%2d%%" % percent,
if percent < 100:
print "\b\b\b\b\b", # Erase "NN% "
else:
print "Done."
fp.flush()
fp.close()
if not totalSize:
print
</code></pre>
| 4 | 2012-03-16T16:02:06Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on google.com server, the generated <code>abc.jpg</code> is not a valid jpg file, it's actually a html page . I guess the returned headers (a httplib.HTTPMessage instance) can be used to actually tell whether the retrieval successes or not, but I can't find any doc for <code>httplib.HTTPMessage</code>.</p>
<p>Can anybody provide some information about this problem?</p>
| 41 | 2009-06-12T17:15:33Z | 35,767,309 | <pre><code>class MyURLopener(urllib.FancyURLopener):
http_error_default = urllib.URLopener.http_error_default
url = "http://page404.com"
filename = "download.txt"
def reporthook(blockcount, blocksize, totalsize):
pass
...
try:
(f,headers)=MyURLopener().retrieve(url, filename, reporthook)
except Exception, e:
print e
</code></pre>
| 0 | 2016-03-03T08:53:22Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on google.com server, the generated <code>abc.jpg</code> is not a valid jpg file, it's actually a html page . I guess the returned headers (a httplib.HTTPMessage instance) can be used to actually tell whether the retrieval successes or not, but I can't find any doc for <code>httplib.HTTPMessage</code>.</p>
<p>Can anybody provide some information about this problem?</p>
| 41 | 2009-06-12T17:15:33Z | 35,856,359 | <p>:) My first post on StackOverflow, have been a lurker for years. :)</p>
<p>Sadly dir(urllib.urlretrieve) is deficient in useful information.
So from this thread thus far I tried writing this:</p>
<pre><code>a,b = urllib.urlretrieve(imgURL, saveTo)
print "A:", a
print "B:", b
</code></pre>
<p>which produced this:</p>
<pre><code>A: /home/myuser/targetfile.gif
B: Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Cache-Control: max-age=604800
Content-Type: image/gif
Date: Mon, 07 Mar 2016 23:37:34 GMT
Etag: "4e1a5d9cc0857184df682518b9b0da33"
Last-Modified: Sun, 06 Mar 2016 21:16:48 GMT
Server: ECS (hnd/057A)
Timing-Allow-Origin: *
X-Cache: HIT
Content-Length: 27027
Connection: close
</code></pre>
<p>I guess one can check:</p>
<pre><code>if b.Content-Length > 0:
</code></pre>
<p>My next step is to test a scenario where the retrieve fails...</p>
| 0 | 2016-03-07T23:44:29Z | [
"python",
"networking",
"urllib"
] |
How to know if urllib.urlretrieve succeeds? | 987,876 | <p><code>urllib.urlretrieve</code> returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example:</p>
<pre><code>urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg')
</code></pre>
<p>just returns silently, even if abc.jpg doesn't exist on google.com server, the generated <code>abc.jpg</code> is not a valid jpg file, it's actually a html page . I guess the returned headers (a httplib.HTTPMessage instance) can be used to actually tell whether the retrieval successes or not, but I can't find any doc for <code>httplib.HTTPMessage</code>.</p>
<p>Can anybody provide some information about this problem?</p>
| 41 | 2009-06-12T17:15:33Z | 35,857,007 | <p>Results against another server/website - what comes back in "B" is a bit random, but one can test for certain values:</p>
<pre><code>A: get_good.jpg
B: Date: Tue, 08 Mar 2016 00:44:19 GMT
Server: Apache
Last-Modified: Sat, 02 Jan 2016 09:17:21 GMT
ETag: "524cf9-18afe-528565aef9ef0"
Accept-Ranges: bytes
Content-Length: 101118
Connection: close
Content-Type: image/jpeg
A: get_bad.jpg
B: Date: Tue, 08 Mar 2016 00:44:20 GMT
Server: Apache
Content-Length: 1363
X-Frame-Options: deny
Connection: close
Content-Type: text/html
</code></pre>
<p>In the 'bad' case (non-existing image file) "B" retrieved a small chunk of (Googlebot?) HTML code and saved it as the target, hence Content-Length of 1363 bytes. </p>
| 0 | 2016-03-08T00:53:37Z | [
"python",
"networking",
"urllib"
] |
How do I operate on the actual object, not a copy, in a python for loop? | 988,155 | <p>let's say I have a list</p>
<pre><code>a = [1,2,3]
</code></pre>
<p>I'd like to increment every item of that list in place. I want to do something as syntactically easy as</p>
<pre><code>for item in a:
item += 1
</code></pre>
<p>but in that example python uses just the value of <code>item</code>, not its actual reference, so when I'm finished with that loop <code>a</code> still returns [1,2,3] instead of [2,3,4]. I know I could do something like </p>
<pre><code>a = map(lambda x:x+1, a)
</code></pre>
<p>but that doesn't really fit into my current code and I'd hate to have to rewrite it :-\</p>
| 5 | 2009-06-12T18:08:15Z | 988,161 | <p>Here ya go:</p>
<pre><code># Your for loop should be rewritten as follows:
for index in xrange(len(a)):
a[index] += 1
</code></pre>
<p>Incidentally, item IS a reference to the <code>item</code> in <code>a</code>, but of course you can't assign a new value to an integer. For any mutable type, your code would work just fine:</p>
<pre><code>>>> a = [[1], [2], [3], [4]]
>>> for item in a: item += [1]
>>> a
[[1,1], [2,1], [3,1], [4,1]]
</code></pre>
| 17 | 2009-06-12T18:09:35Z | [
"python"
] |
How do I operate on the actual object, not a copy, in a python for loop? | 988,155 | <p>let's say I have a list</p>
<pre><code>a = [1,2,3]
</code></pre>
<p>I'd like to increment every item of that list in place. I want to do something as syntactically easy as</p>
<pre><code>for item in a:
item += 1
</code></pre>
<p>but in that example python uses just the value of <code>item</code>, not its actual reference, so when I'm finished with that loop <code>a</code> still returns [1,2,3] instead of [2,3,4]. I know I could do something like </p>
<pre><code>a = map(lambda x:x+1, a)
</code></pre>
<p>but that doesn't really fit into my current code and I'd hate to have to rewrite it :-\</p>
| 5 | 2009-06-12T18:08:15Z | 988,197 | <p>Instead of your <code>map</code>-based solution, here's a list-comprehension-based solution</p>
<pre><code>a = [item + 1 for item in a]
</code></pre>
| 9 | 2009-06-12T18:19:15Z | [
"python"
] |
How do I operate on the actual object, not a copy, in a python for loop? | 988,155 | <p>let's say I have a list</p>
<pre><code>a = [1,2,3]
</code></pre>
<p>I'd like to increment every item of that list in place. I want to do something as syntactically easy as</p>
<pre><code>for item in a:
item += 1
</code></pre>
<p>but in that example python uses just the value of <code>item</code>, not its actual reference, so when I'm finished with that loop <code>a</code> still returns [1,2,3] instead of [2,3,4]. I know I could do something like </p>
<pre><code>a = map(lambda x:x+1, a)
</code></pre>
<p>but that doesn't really fit into my current code and I'd hate to have to rewrite it :-\</p>
| 5 | 2009-06-12T18:08:15Z | 988,218 | <p>In python integers (and floats, and strings, and tuples) are immutable so you have the actual object (and not a copy), you just can't change it.</p>
<p>What's happening is that in the line: <code>item += 1</code> you are creating a new integer (with a value of <code>item + 1</code>) and binding the name <code>item</code> to it.</p>
<p>What you want to do, is change the integer that <code>a[index]</code> points to which is why the line <code>a[index] += 1</code> works. You're still creating a new integer, but then you're updating the list to point to it.</p>
<p>As a side note:</p>
<pre><code>for index,item in enumerate(a):
a[index] = item + 1
</code></pre>
<p>... is slightly more idiomatic than the answer posted by Triptych.</p>
| 12 | 2009-06-12T18:23:15Z | [
"python"
] |
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.</p>
| 327 | 2009-06-12T18:25:02Z | 988,249 | <p>If the string can <em>always</em> be trusted, you could use <code>eval</code> (or use <code>literal_eval</code> as suggested; it's safe no matter what the string is.) Otherwise you need a parser. A JSON parser (such as simplejson) would work if he only ever stores content that fits with the JSON scheme.</p>
| 16 | 2009-06-12T18:30:12Z | [
"python",
"string",
"dictionary"
] |
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.</p>
| 327 | 2009-06-12T18:25:02Z | 988,251 | <p>Starting in Python 2.6 you can use the built-in <code>ast.literal_eval</code>:</p>
<pre><code>>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
</code></pre>
<p>This is safer than using <code>eval</code>. As its own docs say:</p>
<pre>
>>> help(ast.literal_eval)
Help on function literal_eval in module ast:
literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
</pre>
<p>For example:</p>
<pre><code>>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
</code></pre>
| 559 | 2009-06-12T18:30:45Z | [
"python",
"string",
"dictionary"
] |
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.</p>
| 327 | 2009-06-12T18:25:02Z | 988,481 | <p>If you can't use Python 2.6, you can use a simple safeeval implmenentation like <a href="http://code.activestate.com/recipes/364469/" rel="nofollow">http://code.activestate.com/recipes/364469/</a></p>
<p>It piggybacks on the Python compiler so you don't have to do all the gross work yourself.</p>
| 3 | 2009-06-12T19:09:31Z | [
"python",
"string",
"dictionary"
] |
Converting a String to Dictionary? | 988,228 | <p>How can I convert the <code>str</code> representation of a <code>dict</code>, such as the following string, into a <code>dict</code>?</p>
<pre><code>s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
</code></pre>
<p>I prefer not to use <code>eval</code>. What else can I use?</p>
<p>The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.</p>
| 327 | 2009-06-12T18:25:02Z | 19,391,807 | <p><a href="http://docs.python.org/2/library/json.html">http://docs.python.org/2/library/json.html</a></p>
<p>JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack...</p>
<pre><code>import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}
</code></pre>
<p>NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.</p>
<p>More about json single quote: <a href="http://stackoverflow.com/questions/2275359/jquery-single-quote-in-json-response">jQuery single quote in JSON response</a></p>
| 61 | 2013-10-15T21:54:27Z | [
"python",
"string",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.