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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Emacs defadvice on python-mode function | 1,416,882 | <p>In python-mode, there is a function called py-execute-region which sends a highlighted region of code to the Python buffer for evaluation. After evaluation, the cursor is in the Python buffer, but I would prefer that it remain in the script buffer so I can continue producing more code. I wrote a simple advising function:</p>
<pre><code>(defadvice py-execute-region
(after py-execute-region-other-window activate)
""" After execution, return cursor to script buffer """
(other-window 1)
)
</code></pre>
<p>But this does not do anything at all. I've tried other variants like using 'around' rather than 'after'; setting a variable to the script buffer name and then pop-to-buffer to that buffer and stuff like that. No success! I wonder if the mechanics of this is obvious to someone... Thanks!</p>
| 5 | 2009-09-13T04:52:45Z | 1,851,850 | <p>In this case the solution appears to be</p>
<pre><code>(custom-set-variables
'(py-shell-switch-buffers-on-execute nil))
</code></pre>
| 7 | 2009-12-05T10:43:59Z | [
"python",
"emacs",
"elisp",
"advising-functions",
"defadvice"
] |
Emacs defadvice on python-mode function | 1,416,882 | <p>In python-mode, there is a function called py-execute-region which sends a highlighted region of code to the Python buffer for evaluation. After evaluation, the cursor is in the Python buffer, but I would prefer that it remain in the script buffer so I can continue producing more code. I wrote a simple advising function:</p>
<pre><code>(defadvice py-execute-region
(after py-execute-region-other-window activate)
""" After execution, return cursor to script buffer """
(other-window 1)
)
</code></pre>
<p>But this does not do anything at all. I've tried other variants like using 'around' rather than 'after'; setting a variable to the script buffer name and then pop-to-buffer to that buffer and stuff like that. No success! I wonder if the mechanics of this is obvious to someone... Thanks!</p>
| 5 | 2009-09-13T04:52:45Z | 2,280,633 | <p>I haven't actually tried this out, but I did do something similar for find-file, and over there I needed to call interactive before calling other-window. I actually have no real idea of Emacs Lisp, but this may work.</p>
<pre><code>(defadvice py-execute-region
(after py-execute-region-other-window activate)
(interactive)
(other-window 1)
)
</code></pre>
| 1 | 2010-02-17T12:43:33Z | [
"python",
"emacs",
"elisp",
"advising-functions",
"defadvice"
] |
Google appengine string replacement in template file | 1,416,921 | <p>I'm using google appengine (python, of course :) ) and I'd like to do a string.replace on a string <em>from the template file</em>.</p>
<pre>
{% for item in items %}
<p>{{ item.code.replace( '_', ' ' ) }}</p>
{% endfor %}
</pre>
<p>But that isn't working. So we <b>cannot</b> execute anything other than basic checks in the app engine templates. Is that Correct ?</p>
<p><hr /></p>
<p>Another related problem is I'm trying to shorten a string and make it available to the template.</p>
<p>Each furniture object has a name and a longer <b>description</b> field. In this view I'm rendering, I want only the first 50 characters of the <b>description</b> field.</p>
<p>So I tried something like</p>
<pre>
items = db.GqlQuery( 'select * from furniture' )
# <b>edit: if you change the above line to</b>
# items = db.GqlQuery( 'select * from furniture' ).fetch( 1000 )
# the .fetch() command makes the addition of dynamic properties work!
for item in items :
item.shortdescr = item.description[ 0:50 ]
# pass data off to template for rendering
self.response.out.write(
template.render( 'furnitureAll.html', { 'items' : items } )
)
</pre>
<p>Template goes</p>
<pre>
{% for item in items %}
<p>{{ item.name }}</p>
<p>{{ <b>item.shortdescr</b> }}</p>
<!-- items.shortdescr does not exist here,
probably because I did not .put() it previously. -->
{% endfor %}
</pre>
<p>Since that didn't work, I tried changing the Gql Query to shorten the string instead. But I'm quickly realizing Gql isn't like SQL. I'm trying to write queries like</p>
<pre>
select name,LEFT( description, 50 ) from furniture
</pre>
<p>With little success</p>
| 0 | 2009-09-13T05:23:16Z | 1,416,947 | <p>Apart from the argument-less <code>.fetch()</code> call in your code, which I believe can't possibly work (you ALWAYS have to pass <code>fetch</code> an argument -- the max number of entities you're willing to fetch!), I can't reproduce your problem -- assigning a new attribute (including one obtained by processing existing ones) to each item just works fine in my tests.</p>
<p>Can you please reproduce your observed problem in as tiny as compass as possible and edit your question to include all relevant files pls? Seems to be the only way we could help you with your weird observed bug!</p>
<p>BTW, <code>select name,LEFT( description, 50 )</code> or whatever OF COURSE won't work in GQL -- GQL, very very explicitly, ONLY supports <code>select *</code> to get whole entities, or <code>select __key__</code> to get just the entities' keys -- that's all; NO selectivity of columns in the select, much less any OPERATIONS on them!-)</p>
| 1 | 2009-09-13T05:43:02Z | [
"python",
"google-app-engine"
] |
Google appengine string replacement in template file | 1,416,921 | <p>I'm using google appengine (python, of course :) ) and I'd like to do a string.replace on a string <em>from the template file</em>.</p>
<pre>
{% for item in items %}
<p>{{ item.code.replace( '_', ' ' ) }}</p>
{% endfor %}
</pre>
<p>But that isn't working. So we <b>cannot</b> execute anything other than basic checks in the app engine templates. Is that Correct ?</p>
<p><hr /></p>
<p>Another related problem is I'm trying to shorten a string and make it available to the template.</p>
<p>Each furniture object has a name and a longer <b>description</b> field. In this view I'm rendering, I want only the first 50 characters of the <b>description</b> field.</p>
<p>So I tried something like</p>
<pre>
items = db.GqlQuery( 'select * from furniture' )
# <b>edit: if you change the above line to</b>
# items = db.GqlQuery( 'select * from furniture' ).fetch( 1000 )
# the .fetch() command makes the addition of dynamic properties work!
for item in items :
item.shortdescr = item.description[ 0:50 ]
# pass data off to template for rendering
self.response.out.write(
template.render( 'furnitureAll.html', { 'items' : items } )
)
</pre>
<p>Template goes</p>
<pre>
{% for item in items %}
<p>{{ item.name }}</p>
<p>{{ <b>item.shortdescr</b> }}</p>
<!-- items.shortdescr does not exist here,
probably because I did not .put() it previously. -->
{% endfor %}
</pre>
<p>Since that didn't work, I tried changing the Gql Query to shorten the string instead. But I'm quickly realizing Gql isn't like SQL. I'm trying to write queries like</p>
<pre>
select name,LEFT( description, 50 ) from furniture
</pre>
<p>With little success</p>
| 0 | 2009-09-13T05:23:16Z | 1,416,953 | <p>I have little experience with Google AppEngine, but my understanding is that it is very closely related to Django. Your templates do not actually contain Python code, even if some of the structures you use in them look like it.</p>
<p>Both of your questions should be solved using template filters. If it was Django, I would use something like this for your second question:</p>
<pre><code>{{ item.description|truncatewords:10 }}
</code></pre>
<p>For your first question (string replace), there may be no built-in filter you can use for that. You will need to write your own. Something like this;</p>
<pre><code>from google.appengine.ext.webapp.template import create_template_register
register = create_template_register()
@register.filter
def replace_underscores(strng):
return strng.replace('_', ' ')
</code></pre>
<p>Then, in your template, you can do this:</p>
<pre><code>{{ item.code|replace_underscores }}
</code></pre>
| 1 | 2009-09-13T05:46:55Z | [
"python",
"google-app-engine"
] |
Call Python from C++ | 1,417,473 | <p>I'm trying to call a function in a Python script from my main C++ program. The python function takes a string as the argument and returns nothing (ok.. 'None').
It works perfectly well (never thought it would be that easy..) as long as the previous call is finished before the function is called again, otherwise there is an access violation at <code>pModule = PyImport_Import(pName)</code>.</p>
<p>There are a lot of tutorials how to embed python in C and vice versa but I found nothing about that problem.</p>
<pre><code>int callPython(TCHAR* title){
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs, *pValue;
Py_Initialize();
pName = PyUnicode_FromString("Main");
/* Name of Pythonfile */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, "writeLyricToFile");
/* function name. pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(1);
pValue = PyUnicode_FromWideChar(title, -1);
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
showErrorBox(_T("pValue is false"));
return 1;
}
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
//worked as it should!
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
showErrorBox(_T("pValue is null"));
return 1;
}
}
else {
if (PyErr_Occurred()) PyErr_Print();
showErrorBox(_T("pFunc null or not callable"));
return 1;
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
showErrorBox(_T("pModule is null"));
return 1;
}
Py_Finalize();
return 0;
}
</code></pre>
| 7 | 2009-09-13T11:04:48Z | 1,417,598 | <p>When you say "as long as the previous call is finished before the function is called again", I can only assume that you have multiple threads calling from C++ into Python. The python is not thread safe, so this is going to fail!</p>
<p>Read up on the Global Interpreter Lock (GIL) in the Python manual. Perhaps the following links will help:</p>
<ul>
<li><a href="http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock">http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock</a></li>
<li><a href="http://docs.python.org/c-api/init.html#PyEval%5FInitThreads">http://docs.python.org/c-api/init.html#PyEval%5FInitThreads</a></li>
<li><a href="http://docs.python.org/c-api/init.html#PyEval%5FAcquireLock">http://docs.python.org/c-api/init.html#PyEval%5FAcquireLock</a></li>
<li><a href="http://docs.python.org/c-api/init.html#PyEval%5FReleaseLock">http://docs.python.org/c-api/init.html#PyEval%5FReleaseLock</a></li>
</ul>
<p>The GIL is mentioned on Wikipedia:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock">http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock</a></li>
</ul>
| 5 | 2009-09-13T12:05:31Z | [
"c++",
"python",
"c"
] |
Call Python from C++ | 1,417,473 | <p>I'm trying to call a function in a Python script from my main C++ program. The python function takes a string as the argument and returns nothing (ok.. 'None').
It works perfectly well (never thought it would be that easy..) as long as the previous call is finished before the function is called again, otherwise there is an access violation at <code>pModule = PyImport_Import(pName)</code>.</p>
<p>There are a lot of tutorials how to embed python in C and vice versa but I found nothing about that problem.</p>
<pre><code>int callPython(TCHAR* title){
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs, *pValue;
Py_Initialize();
pName = PyUnicode_FromString("Main");
/* Name of Pythonfile */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, "writeLyricToFile");
/* function name. pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(1);
pValue = PyUnicode_FromWideChar(title, -1);
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
showErrorBox(_T("pValue is false"));
return 1;
}
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
//worked as it should!
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
showErrorBox(_T("pValue is null"));
return 1;
}
}
else {
if (PyErr_Occurred()) PyErr_Print();
showErrorBox(_T("pFunc null or not callable"));
return 1;
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
showErrorBox(_T("pModule is null"));
return 1;
}
Py_Finalize();
return 0;
}
</code></pre>
| 7 | 2009-09-13T11:04:48Z | 1,418,647 | <p>Thank you for your help!</p>
<p>Yes you're right, there are several C threads. Never thought I'd need mutex for the interpreter itself - the GIL is a completly new concept for me (and isn't even once mentioned in the whole tutorial).</p>
<p>After reading the reference (for sure not the easiest part of it, although the PyGILState_* functions simplify the whole thing a lot), I added an </p>
<pre><code>void initPython(){
PyEval_InitThreads();
Py_Initialize();
PyEval_ReleaseLock();
}
</code></pre>
<p>function to initialise the interpreter correctly.
Every thread creates its data structure, acquires the lock and releases it afterwards as shown in the reference.</p>
<p>Works as it should, but when calling Py_Finalize() before terminating the process I get a segfault.. any problems with just leaving it?</p>
| 1 | 2009-09-13T19:33:06Z | [
"c++",
"python",
"c"
] |
Python code to Daemonize a process? | 1,417,631 | <p>Can anyone share an efficient code snipper to daemonize a process in python? </p>
| 3 | 2009-09-13T12:22:48Z | 1,417,642 | <p>From <a href="http://www.jejik.com/articles/2007/02/a%5Fsimple%5Funix%5Flinux%5Fdaemon%5Fin%5Fpython/" rel="nofollow">http://www.jejik.com/articles/2007/02/a%5Fsimple%5Funix%5Flinux%5Fdaemon%5Fin%5Fpython/</a></p>
<pre><code>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys, os, time, atexit
from signal import SIGTERM
class Daemon:
"""
A generic daemon class.
Usage: subclass the Daemon class and override the run() method
"""
def __init__(self, pidfile, stdin='/dev/null',
stdout='/dev/null', stderr='/dev/null'):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.pidfile = pidfile
def daemonize(self):
"""
do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
sys.stderr.write(
"fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError, e:
sys.stderr.write(
"fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = file(self.stdin, 'r')
so = file(self.stdout, 'a+')
se = file(self.stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
file(self.pidfile,'w+').write("%s\n" % pid)
def delpid(self):
os.remove(self.pidfile)
def start(self):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if pid:
message = "pidfile %s already exist. Daemon already running?\n"
sys.stderr.write(message % self.pidfile)
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
def restart(self):
"""
Restart the daemon
"""
self.stop()
self.start()
def run(self):
"""
You should override this method when you subclass Daemon.
It will be called after the process has been
daemonized by start() or restart().
"""
</code></pre>
| 3 | 2009-09-13T12:29:52Z | [
"python"
] |
doing textwrap and dedent in Windows Powershell (or dotNet aka .net) | 1,417,663 | <p><strong>Background</strong></p>
<p>Python has "textwrap" and "dedent" functions. They do pretty much what you expect to any string you supply.</p>
<blockquote>
<p><strong>textwrap.wrap(text[, width[, ...]])</strong></p>
<p>Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.</p>
<p><strong>textwrap.dedent(text)</strong></p>
<p>Remove any common leading whitespace from every line in text.</p>
</blockquote>
<p><a href="http://docs.python.org/library/textwrap.html" rel="nofollow">http://docs.python.org/library/textwrap.html</a></p>
<p><strong>Question:</strong></p>
<p>How do you do this in Windows PowerShell, (or with .NET methods you call from PowerShell)?</p>
| 2 | 2009-09-13T12:40:57Z | 1,417,676 | <p>I think you should create a CLI utility with this behaviour and customize it as you like. And then just use it as a command in your shell. Maybe you will also need to add you script into PATH.</p>
| 1 | 2009-09-13T12:47:58Z | [
".net",
"python",
"string",
"text",
"powershell"
] |
doing textwrap and dedent in Windows Powershell (or dotNet aka .net) | 1,417,663 | <p><strong>Background</strong></p>
<p>Python has "textwrap" and "dedent" functions. They do pretty much what you expect to any string you supply.</p>
<blockquote>
<p><strong>textwrap.wrap(text[, width[, ...]])</strong></p>
<p>Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.</p>
<p><strong>textwrap.dedent(text)</strong></p>
<p>Remove any common leading whitespace from every line in text.</p>
</blockquote>
<p><a href="http://docs.python.org/library/textwrap.html" rel="nofollow">http://docs.python.org/library/textwrap.html</a></p>
<p><strong>Question:</strong></p>
<p>How do you do this in Windows PowerShell, (or with .NET methods you call from PowerShell)?</p>
| 2 | 2009-09-13T12:40:57Z | 1,418,040 | <p>This is a negligent code...</p>
<pre><code>#requires -version 2.0
function wrap( [string]$text, [int]$width ) {
$i=0;
$text.ToCharArray() | group { [Math]::Floor($i/$width); (gv i).Value++ } | % { -join $_.Group }
}
function dedent( [string[]]$text ) {
$i = $text | % { $_ -match "^(\s*)" | Out-Null ; $Matches[1].Length } | sort | select -First 1
$text -replace "^\s{$i}"
}
</code></pre>
| 3 | 2009-09-13T15:43:02Z | [
".net",
"python",
"string",
"text",
"powershell"
] |
doing textwrap and dedent in Windows Powershell (or dotNet aka .net) | 1,417,663 | <p><strong>Background</strong></p>
<p>Python has "textwrap" and "dedent" functions. They do pretty much what you expect to any string you supply.</p>
<blockquote>
<p><strong>textwrap.wrap(text[, width[, ...]])</strong></p>
<p>Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.</p>
<p><strong>textwrap.dedent(text)</strong></p>
<p>Remove any common leading whitespace from every line in text.</p>
</blockquote>
<p><a href="http://docs.python.org/library/textwrap.html" rel="nofollow">http://docs.python.org/library/textwrap.html</a></p>
<p><strong>Question:</strong></p>
<p>How do you do this in Windows PowerShell, (or with .NET methods you call from PowerShell)?</p>
| 2 | 2009-09-13T12:40:57Z | 3,326,275 | <p>Looking at the results in python at <a href="http://try-python.mired.org/" rel="nofollow">http://try-python.mired.org/</a>, it appears that the correct algorithm splits at word boundaries, rather than taking fixed-length substrings from the text.</p>
<pre><code>function wrap( [string]$text, [int]$width = 70 ) {
$line = ''
# Split the text into words.
$text.Split( ' '.ToCharArray( ) ) | % {
# Initialize the first line with the first word.
if( -not $line ) { $line = $_ }
else {
# For each new word, try to add it to the current line.
$next = $line + ' ' + $_
# If the new word goes over the limit,
# return the last line and start a new one.
if( $next.Length -ge $width ) { $line; $line = $_ }
# Otherwise, use the updated line with the new word.
else { $line = $next }
}
}
# Return the last line, containing the remainder of the text.
$line
}
</code></pre>
<p>And here's an alternate implementation for <code>dedent</code> as well.</p>
<pre><code>function dedent( [string[]]$lines ) {
# Find the shortest length of leading whitespace common to all lines.
$commonLength = (
$lines | % {
$i = 0
while( $i -lt $_.Length -and [char]::IsWhitespace( $_, $i ) ) { ++$i }
$i
} | Measure-Object -minimum
).Minimum
# Remove the common whitespace from each string
$lines | % { $_.Substring( $commonLength ) }
}
</code></pre>
<p>Hopefully their greater verbosity will provide better clarity :)</p>
| 1 | 2010-07-24T18:15:46Z | [
".net",
"python",
"string",
"text",
"powershell"
] |
Python: Warnings and logging verbose limit | 1,417,665 | <p>I want to unify the whole logging facility of my app. Any warning is raise an exception, next I catch it and pass it to the logger. But the question: Is there in logging any mute facility? Sometimes logger becomes too verbose. Sometimes for the reason of too noisy warnings, is there are any verbose limit in warnings?</p>
<p><a href="http://docs.python.org/library/logging.html" rel="nofollow">http://docs.python.org/library/logging.html</a></p>
<p><a href="http://docs.python.org/library/warnings.html" rel="nofollow">http://docs.python.org/library/warnings.html</a></p>
| 1 | 2009-09-13T12:41:25Z | 1,417,675 | <p>from the very source you mentioned.
there are the log-levels, use the wisely ;-)</p>
<pre><code>LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
</code></pre>
| 0 | 2009-09-13T12:47:19Z | [
"python",
"logging",
"warnings"
] |
Python: Warnings and logging verbose limit | 1,417,665 | <p>I want to unify the whole logging facility of my app. Any warning is raise an exception, next I catch it and pass it to the logger. But the question: Is there in logging any mute facility? Sometimes logger becomes too verbose. Sometimes for the reason of too noisy warnings, is there are any verbose limit in warnings?</p>
<p><a href="http://docs.python.org/library/logging.html" rel="nofollow">http://docs.python.org/library/logging.html</a></p>
<p><a href="http://docs.python.org/library/warnings.html" rel="nofollow">http://docs.python.org/library/warnings.html</a></p>
| 1 | 2009-09-13T12:41:25Z | 1,417,710 | <p>This will be a problem if you plan to make all logging calls from some blind error handler that doesn't know anything about the code that raised the error, which is what your question sounds like. How will you decide which logging calls get made and which don't?</p>
<p>The more standard practice is to use such blocks to recover if possible, and log an error (really, if it is an error that you weren't specifically prepared for, you want to know about it; use a high level). But don't rely on these blocks for all your state/debug information. Better to sprinkle your code with logging calls before it gets to the error-handler. That way, you can observe useful run-time information about a system when it is NOT failing and you can make logging calls of different severity. For example:</p>
<pre><code>import logging
from traceback import format_exc
logger = logging.getLogger() # Gives the root logger. Change this for better organization
# Add your appenders or what have you
def handle_error(e):
logger.error("Unexpected error found")
logger.warn(format_exc()) #put the traceback in the log at lower level
... #Your recovery code
def do_stuff():
logger.info("Program started")
... #Your main code
logger.info("Stuff done")
if __name__ == "__main__":
try:
do_stuff()
except Exception,e:
handle_error(e)
</code></pre>
| 0 | 2009-09-13T13:07:36Z | [
"python",
"logging",
"warnings"
] |
Python: Warnings and logging verbose limit | 1,417,665 | <p>I want to unify the whole logging facility of my app. Any warning is raise an exception, next I catch it and pass it to the logger. But the question: Is there in logging any mute facility? Sometimes logger becomes too verbose. Sometimes for the reason of too noisy warnings, is there are any verbose limit in warnings?</p>
<p><a href="http://docs.python.org/library/logging.html" rel="nofollow">http://docs.python.org/library/logging.html</a></p>
<p><a href="http://docs.python.org/library/warnings.html" rel="nofollow">http://docs.python.org/library/warnings.html</a></p>
| 1 | 2009-09-13T12:41:25Z | 1,417,759 | <p>Not only are there <a href="http://stackoverflow.com/questions/1417665/python-warnings-and-logging-verbose-limit/1417675">log levels</a>, but there is a really flexible <a href="http://docs.python.org/library/logging.html#configuring-logging" rel="nofollow">way of configuring them</a>. If you are using named <code>logger</code> objects (e.g., <code>logger = logging.getLogger(...)</code>) then you can configure them appropriately. That will let you configure verbosity on a subsystem-by-subsystem basis where a <em>subsystem</em> is defined by the logging hierarchy.</p>
<p>The other option is to use <a href="http://docs.python.org/library/logging.html#filter-objects" rel="nofollow"><code>logging.Filter</code></a> and <a href="http://docs.python.org/library/warnings.html#the-warnings-filter" rel="nofollow">Warning filters</a> to limit the output. I haven't used this method before but it looks like it might be a better fit for your needs.</p>
<p>Give <a href="http://www.python.org/dev/peps/pep-0282/" rel="nofollow">PEP-282</a> a read for a good prose description of the Python <code>logging</code> package. I think that it describes the functionality much better than the module documentation does.</p>
<h2>Edit after Clarification</h2>
<p>You might be able to handle the logging portion of this using a custom class based on <code>logging.Logger</code> and registered with <code>logging.setLoggerClass()</code>. It really sounds like you want something similar to syslog's <em>"Last message repeated 9 times"</em>. Unfortunately I don't know of an implementation of this anywhere. You might want to see if <a href="http://twistedmatrix.com/documents/current/api/twisted.python.log.html" rel="nofollow">twisted.python.log</a> supports this functionality.</p>
| 3 | 2009-09-13T13:33:38Z | [
"python",
"logging",
"warnings"
] |
Detecting the http request type (GET, HEAD, etc) from a python cgi | 1,417,715 | <p>How can I find out the http request my python cgi received? I need different behaviors for HEAD and GET.</p>
<p>Thanks!</p>
| 9 | 2009-09-13T13:12:30Z | 1,417,722 | <pre><code>import os
if os.environ['REQUEST_METHOD'] == 'GET':
# blah
</code></pre>
| 12 | 2009-09-13T13:17:20Z | [
"python",
"http",
"httpwebrequest",
"cgi"
] |
Detecting the http request type (GET, HEAD, etc) from a python cgi | 1,417,715 | <p>How can I find out the http request my python cgi received? I need different behaviors for HEAD and GET.</p>
<p>Thanks!</p>
| 9 | 2009-09-13T13:12:30Z | 1,419,177 | <p>This is not a direct answer to your question. But your question stems from doing things the wrong way.</p>
<p>Do not write Python CGI scripts.</p>
<p>Write a <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> application. Better still, use a Python web framework. There are dozens. Choose one like <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a>.</p>
<p>The WSGI standard (described in <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">PEP 333</a>) makes it much, much easier to find things in the web request. </p>
<p>The mod_wsgi implementation is faster and more secure than a CGI.</p>
<p>A web framework is also simpler than writing your own CGI script or mod_wsgi application.</p>
| 0 | 2009-09-14T00:09:15Z | [
"python",
"http",
"httpwebrequest",
"cgi"
] |
Detecting the http request type (GET, HEAD, etc) from a python cgi | 1,417,715 | <p>How can I find out the http request my python cgi received? I need different behaviors for HEAD and GET.</p>
<p>Thanks!</p>
| 9 | 2009-09-13T13:12:30Z | 1,420,886 | <p>Why do you need to distinguish between GET and HEAD?</p>
<p>Normally you shouldn't distinguish and should treat a HEAD request just like a GET. This is because a HEAD request is meant to return the exact same headers as a GET. The only difference is there will be no response content. Just because there is no response content though doesn't mean you no longer have to return a valid Content-Length header, or other headers, which are dependent on the response content.</p>
<p>In mod_wsgi, which various people are pointing you at, it will actually deliberately change the request method from HEAD to GET in certain cases to guard against people who wrongly treat HEAD differently. The specific case where this is done is where an Apache output filter is registered. The reason that it is done in this case is because the output filter may expect to see the response content and from that generate additional response headers. If you were to decide not to bother to generate any response content for a HEAD request, you will deprive the output filter of the content and the headers they add may then not agree with what would be returned from a GET request. The end result of this is that you can stuff up caches and the operation of the browser.</p>
<p>The same can apply equally for CGI scripts behind Apache as output filters can still be added in that case as well. For CGI scripts there is nothing in place though to protect against users being stupid and doing things differently for a HEAD request.</p>
| 0 | 2009-09-14T10:59:17Z | [
"python",
"http",
"httpwebrequest",
"cgi"
] |
adding the same object twice to a ManyToManyField | 1,417,825 | <p>I have two django model classes:</p>
<pre><code>class A(models.Model):
name = models.CharField(max_length = 128) #irrelevant
class B(models.Model):
a = models.ManyToManyField(A)
name = models.CharField(max_length = 128) #irrelevant
</code></pre>
<p>What I want to do is the following:</p>
<pre><code>a1 = A()
a2 = A()
b = B()
b.a.add(a1)
b.a.add(a1) #I want to have a1 twice
b.a.add(a2)
assert len(b.a.all()) == 3 #this fails; the length of all() is 2
</code></pre>
<p>I am guessing that add() uses a set semantic, but how can I circumvent that? I tried looking into custom managers, but I am not sure if this the right way (seems complicated)...</p>
<p>Thanks in advance!</p>
| 4 | 2009-09-13T14:04:57Z | 1,417,989 | <p>Django uses a relational DB for its underlying storage, and that intrinsically DOES have "set semantics": no way to circumvent THAT. So if you want a "multi-set" of anything, you have to represent it with a numeric field that counts how many times each item "occurs". ManyToManyField doesn't do that -- so, instead, you'll need a separate Model subclass which explicitly indicates the A and the B it's relating, AND has an integer property to "count how many times".</p>
| 3 | 2009-09-13T15:25:40Z | [
"python",
"django",
"django-models"
] |
adding the same object twice to a ManyToManyField | 1,417,825 | <p>I have two django model classes:</p>
<pre><code>class A(models.Model):
name = models.CharField(max_length = 128) #irrelevant
class B(models.Model):
a = models.ManyToManyField(A)
name = models.CharField(max_length = 128) #irrelevant
</code></pre>
<p>What I want to do is the following:</p>
<pre><code>a1 = A()
a2 = A()
b = B()
b.a.add(a1)
b.a.add(a1) #I want to have a1 twice
b.a.add(a2)
assert len(b.a.all()) == 3 #this fails; the length of all() is 2
</code></pre>
<p>I am guessing that add() uses a set semantic, but how can I circumvent that? I tried looking into custom managers, but I am not sure if this the right way (seems complicated)...</p>
<p>Thanks in advance!</p>
| 4 | 2009-09-13T14:04:57Z | 1,418,241 | <p>One way to do it:</p>
<pre><code>class A(models.Model):
...
class B(models.Model):
...
class C(models.Model):
a = models.ForeignKey(A)
b = models.ForeignKey(B)
</code></pre>
<p>Then:</p>
<pre><code>>>> a1 = A()
>>> a2 = A()
>>> b = B()
>>> c1 = C(a=a1, b=b)
>>> c2 = C(a=a2, b=b)
>>> c3 = C(a=a1, b=b)
</code></pre>
<p>So, we simply have:</p>
<pre><code>>>> assert C.objects.filter(b=b).count == 3
>>> for c in C.objects.filter(b=b):
... # do something with c.a
</code></pre>
| 0 | 2009-09-13T17:05:24Z | [
"python",
"django",
"django-models"
] |
adding the same object twice to a ManyToManyField | 1,417,825 | <p>I have two django model classes:</p>
<pre><code>class A(models.Model):
name = models.CharField(max_length = 128) #irrelevant
class B(models.Model):
a = models.ManyToManyField(A)
name = models.CharField(max_length = 128) #irrelevant
</code></pre>
<p>What I want to do is the following:</p>
<pre><code>a1 = A()
a2 = A()
b = B()
b.a.add(a1)
b.a.add(a1) #I want to have a1 twice
b.a.add(a2)
assert len(b.a.all()) == 3 #this fails; the length of all() is 2
</code></pre>
<p>I am guessing that add() uses a set semantic, but how can I circumvent that? I tried looking into custom managers, but I am not sure if this the right way (seems complicated)...</p>
<p>Thanks in advance!</p>
| 4 | 2009-09-13T14:04:57Z | 1,423,749 | <p>I think what you want is to use an intermediary model to form the M2M relationship using the <code>through</code> keyword argument in the ManyToManyField. Sort of like the first answer above, but more "Django-y".</p>
<pre><code>class A(models.Model):
name = models.CharField(max_length=200)
class B(models.Model):
a = models.ManyToManyField(A, through='C')
...
class C(models.Model):
a = models.ForeignKey(A)
b = models.ForeignKey(B)
</code></pre>
<p>When using the <code>through</code> keyword, the usual M2M manipulation methods are no longer available (this means <code>add</code>, <code>create</code>, <code>remove</code>, or assignment with <code>=</code> operator). Instead you must create the intermediary model itself, like so:</p>
<pre><code> >>> C.objects.create(a=a1, b=b)
</code></pre>
<p>However, you will still be able to use the usual querying operations on the model containing the <code>ManyToManyField</code>. In other words the following will still work:</p>
<pre><code> >>> b.a.filter(a=a1)
</code></pre>
<p>But maybe a better example is something like this:</p>
<pre><code>>>> B.objects.filter(a__name='Test')
</code></pre>
<p>As long as the FK fields on the intermediary model are not designated as <code>unique</code> you will be able to create multiple instances with the same FKs. You can also attach additional information about the relationship by adding any other fields you like to <code>C</code>. </p>
<p>Intermediary models are documented <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany" rel="nofollow">here</a>. </p>
| 3 | 2009-09-14T20:30:56Z | [
"python",
"django",
"django-models"
] |
Sending cookies in a SOAP request using Suds | 1,417,902 | <p>I'm trying to access a SOAP API using Suds. The SOAP API documentation states that I have to provide three cookies with some login data. How can I accomplish this?</p>
| 2 | 2009-09-13T14:44:36Z | 1,417,916 | <p>Set a "Cookie" HTTP Request Header having the required name/value pairs. This is how Cookie values are usually transmitted in HTTP Based systems. You can add multiple key/value pairs in the same http header.</p>
<p><strong>Single Cookie</strong></p>
<blockquote>
<p>Cookie: name1=value1</p>
</blockquote>
<p><strong>Multiple Cookies</strong> (seperated by semicolons)</p>
<blockquote>
<p>Cookie: name1=value1; name2=value2</p>
</blockquote>
| 4 | 2009-09-13T14:52:23Z | [
"python",
"soap",
"cookies",
"suds"
] |
Time out error while creating cgi.FieldStorage object | 1,417,918 | <p>Hey, any idea about what is the timeout error which I am getting here:</p>
<p>Error trace:</p>
<pre><code> File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/_cpdispatch.py", line 25, in __call__
return self.callable(*self.args, **self.kwargs)
File "sync_server.py", line 853, in put_file
return RequestController_v1_0.put_file(self, *args, **kw)
File "sync_server.py", line 409, in put_file
saved_path, tgt_path, root_folder = self._save_file(client_id, theFile)
File "sync_server.py", line 404, in _save_file
saved_path, tgt_path, root_folder = get_posted_file(cherrypy.request, 'theFile', staging_path)
File "sync_server.py", line 1031, in get_posted_file
, keep_blank_values=True)
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 496, in __init__
self.read_multi(environ, keep_blank_values, strict_parsing)
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 620, in read_multi
environ, keep_blank_values, strict_parsing)
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 498, in __init__
self.read_single()
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 635, in read_single
self.read_lines()
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 657, in read_lines
self.read_lines_to_outerboundary()
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 685, in read_lines_to_outerboundary
line = self.fp.readline(1<<16)
File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/wsgiserver/__init__.py", line 206, in readline
data = self.rfile.readline(size)
File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/wsgiserver/__init__.py", line 868, in readline
data = self.recv(self._rbufsize)
File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/wsgiserver/__init__.py", line 747, in recv
return self._sock.recv(size)
timeout: timed out
</code></pre>
<p>Here is the code which is getting called:</p>
<pre><code> def get_posted_file(request, form_field_name, tgt_folder, tgt_fname=None):
logger.debug('get_posted_file: %s' % request.headers['Last-Modified'])
lowerHeaderMap = {}
for key, value in request.headers.items():
lowerHeaderMap[key.lower()] = value
---> dataDict = TmpFieldStorage(fp=request.rfile, headers=lowerHeaderMap, environ={'REQUEST_METHOD':'POST'}
, keep_blank_values=True)
</code></pre>
<p>and:</p>
<pre><code>class TmpFieldStorage(cgi.FieldStorage):
"""
Use a named temporary file to allow creation of hard link to final destination
"""
def make_file(self, binary=None):
tmp_folder = os.path.join(get_filer_root(cherrypy.request.login), 'sync_tmp')
if not os.path.exists(tmp_folder):
os.makedirs(tmp_folder)
return tempfile.NamedTemporaryFile(dir=tmp_folder)
</code></pre>
| 0 | 2009-09-13T14:53:40Z | 1,418,017 | <blockquote>
<p>environ={'REQUEST_METHOD':'POST'} </p>
</blockquote>
<p>That seems a rather deficient <code>environ</code>. The CGI spec requires many more environment variables to be in there, some of which the <code>cgi</code> module is going to need.</p>
<p>In particular there is no CONTENT_LENGTH header. Without it, <code>cgi</code> is defaulting to reading the entire contents of the stream up until EOF. But since it is (probably) a network stream rather than a file there will be no EOF (or at least not one directly at the end of the submission), so the form reader will be sitting there waiting for more input that will never come. Timeout.</p>
| 0 | 2009-09-13T15:36:52Z | [
"python",
"cgi",
"cherrypy"
] |
Parse custom URIs with urlparse (Python) | 1,417,958 | <p>My application creates custom URIs (or URLs?) to identify objects and resolve them. The problem is that Python's urlparse module refuses to parse unknown URL schemes like it parses http.</p>
<p>If I do not adjust urlparse's uses_* lists I get this:</p>
<pre><code>>>> urlparse.urlparse("qqqq://base/id#hint")
('qqqq', '', '//base/id#hint', '', '', '')
>>> urlparse.urlparse("http://base/id#hint")
('http', 'base', '/id', '', '', 'hint')
</code></pre>
<p>Here is what I do, and I wonder if there is a better way to do it:</p>
<pre><code>import urlparse
SCHEME = "qqqq"
# One would hope that there was a better way to do this
urlparse.uses_netloc.append(SCHEME)
urlparse.uses_fragment.append(SCHEME)
</code></pre>
<p>Why is there no better way to do this?</p>
| 13 | 2009-09-13T15:10:41Z | 1,417,967 | <p>I think the problem is that URI's don't all have a common format after the scheme. For example, mailto: urls aren't structured the same as http: urls.</p>
<p>I would use the results of the first parse, then synthesize an http url and parse it again:</p>
<pre><code>parts = urlparse.urlparse("qqqq://base/id#hint")
fake_url = "http:" + parts[2]
parts2 = urlparse.urlparse(fake_url)
</code></pre>
| 4 | 2009-09-13T15:15:42Z | [
"python",
"url",
"python-2.6",
"urlparse"
] |
Parse custom URIs with urlparse (Python) | 1,417,958 | <p>My application creates custom URIs (or URLs?) to identify objects and resolve them. The problem is that Python's urlparse module refuses to parse unknown URL schemes like it parses http.</p>
<p>If I do not adjust urlparse's uses_* lists I get this:</p>
<pre><code>>>> urlparse.urlparse("qqqq://base/id#hint")
('qqqq', '', '//base/id#hint', '', '', '')
>>> urlparse.urlparse("http://base/id#hint")
('http', 'base', '/id', '', '', 'hint')
</code></pre>
<p>Here is what I do, and I wonder if there is a better way to do it:</p>
<pre><code>import urlparse
SCHEME = "qqqq"
# One would hope that there was a better way to do this
urlparse.uses_netloc.append(SCHEME)
urlparse.uses_fragment.append(SCHEME)
</code></pre>
<p>Why is there no better way to do this?</p>
| 13 | 2009-09-13T15:10:41Z | 4,907,113 | <p>Try removing the scheme entirely, and start with //netloc, i.e.:</p>
<pre><code>>>> SCHEME="qqqq"
>>> url="qqqq://base/id#hint"[len(SCHEME)+1:]
>>> url
'//base/id#hint'
>>> urlparse.urlparse(url)
('', 'base', '/id', '', '', 'hint')
</code></pre>
<p>You won't have the scheme in the urlparse result, but you know the scheme anyway.</p>
<p>Also note that Python 2.6 seems to handle this url just fine (aside from the fragment):</p>
<pre><code>$ python2.6 -c 'import urlparse; print urlparse.urlparse("qqqq://base/id#hint")'
ParseResult(scheme='qqqq', netloc='base', path='/id#hint', params='', query='', fragment='')
</code></pre>
| 1 | 2011-02-05T13:33:25Z | [
"python",
"url",
"python-2.6",
"urlparse"
] |
Parse custom URIs with urlparse (Python) | 1,417,958 | <p>My application creates custom URIs (or URLs?) to identify objects and resolve them. The problem is that Python's urlparse module refuses to parse unknown URL schemes like it parses http.</p>
<p>If I do not adjust urlparse's uses_* lists I get this:</p>
<pre><code>>>> urlparse.urlparse("qqqq://base/id#hint")
('qqqq', '', '//base/id#hint', '', '', '')
>>> urlparse.urlparse("http://base/id#hint")
('http', 'base', '/id', '', '', 'hint')
</code></pre>
<p>Here is what I do, and I wonder if there is a better way to do it:</p>
<pre><code>import urlparse
SCHEME = "qqqq"
# One would hope that there was a better way to do this
urlparse.uses_netloc.append(SCHEME)
urlparse.uses_fragment.append(SCHEME)
</code></pre>
<p>Why is there no better way to do this?</p>
| 13 | 2009-09-13T15:10:41Z | 6,264,214 | <p>You can also register a custom handler with urlparse:</p>
<pre><code>import urlparse
def register_scheme(scheme):
for method in filter(lambda s: s.startswith('uses_'), dir(urlparse)):
getattr(urlparse, method).append(scheme)
register_scheme('moose')
</code></pre>
<p>This will append your url scheme to the lists:</p>
<pre><code>uses_fragment
uses_netloc
uses_params
uses_query
uses_relative
</code></pre>
<p>The uri will then be treated as http-like and will correctly return the path, fragment, username/password etc.</p>
<pre><code>urlparse.urlparse('moose://username:password@hostname:port/path?query=value#fragment')._asdict()
=> {'fragment': 'fragment', 'netloc': 'username:password@hostname:port', 'params': '', 'query': 'query=value', 'path': '/path', 'scheme': 'moose'}
</code></pre>
| 22 | 2011-06-07T11:00:59Z | [
"python",
"url",
"python-2.6",
"urlparse"
] |
Parse custom URIs with urlparse (Python) | 1,417,958 | <p>My application creates custom URIs (or URLs?) to identify objects and resolve them. The problem is that Python's urlparse module refuses to parse unknown URL schemes like it parses http.</p>
<p>If I do not adjust urlparse's uses_* lists I get this:</p>
<pre><code>>>> urlparse.urlparse("qqqq://base/id#hint")
('qqqq', '', '//base/id#hint', '', '', '')
>>> urlparse.urlparse("http://base/id#hint")
('http', 'base', '/id', '', '', 'hint')
</code></pre>
<p>Here is what I do, and I wonder if there is a better way to do it:</p>
<pre><code>import urlparse
SCHEME = "qqqq"
# One would hope that there was a better way to do this
urlparse.uses_netloc.append(SCHEME)
urlparse.uses_fragment.append(SCHEME)
</code></pre>
<p>Why is there no better way to do this?</p>
| 13 | 2009-09-13T15:10:41Z | 16,927,703 | <p>There is also library called <a href="https://github.com/gruns/furl/" rel="nofollow">furl</a> which gives you result you want:</p>
<pre><code>>>>import furl
>>>f=furl.furl("qqqq://base/id#hint");
>>>f.scheme
'qqqq'
>>> f.host
'base'
>>> f.path
Path('/id')
>>> f.path.segments
['id']
>>> f.fragment
Fragment('hint')
>>> f.fragmentstr
'hint'
</code></pre>
| 3 | 2013-06-04T21:22:13Z | [
"python",
"url",
"python-2.6",
"urlparse"
] |
Parse custom URIs with urlparse (Python) | 1,417,958 | <p>My application creates custom URIs (or URLs?) to identify objects and resolve them. The problem is that Python's urlparse module refuses to parse unknown URL schemes like it parses http.</p>
<p>If I do not adjust urlparse's uses_* lists I get this:</p>
<pre><code>>>> urlparse.urlparse("qqqq://base/id#hint")
('qqqq', '', '//base/id#hint', '', '', '')
>>> urlparse.urlparse("http://base/id#hint")
('http', 'base', '/id', '', '', 'hint')
</code></pre>
<p>Here is what I do, and I wonder if there is a better way to do it:</p>
<pre><code>import urlparse
SCHEME = "qqqq"
# One would hope that there was a better way to do this
urlparse.uses_netloc.append(SCHEME)
urlparse.uses_fragment.append(SCHEME)
</code></pre>
<p>Why is there no better way to do this?</p>
| 13 | 2009-09-13T15:10:41Z | 20,774,335 | <p>You can use <a href="https://github.com/homm/yurl/" rel="nofollow">yurl</a> library. Unlike purl or furl, it not try to fix urlparse bugs. It is new compatible with RFC 3986 implementation.</p>
<pre><code>>>> import yurl
>>> yurl.URL('qqqq://base/id#hint')
URLBase(scheme='qqqq', userinfo=u'', host='base', port='', path='/id', query='', fragment='hint')
</code></pre>
| 0 | 2013-12-25T15:35:22Z | [
"python",
"url",
"python-2.6",
"urlparse"
] |
Parse custom URIs with urlparse (Python) | 1,417,958 | <p>My application creates custom URIs (or URLs?) to identify objects and resolve them. The problem is that Python's urlparse module refuses to parse unknown URL schemes like it parses http.</p>
<p>If I do not adjust urlparse's uses_* lists I get this:</p>
<pre><code>>>> urlparse.urlparse("qqqq://base/id#hint")
('qqqq', '', '//base/id#hint', '', '', '')
>>> urlparse.urlparse("http://base/id#hint")
('http', 'base', '/id', '', '', 'hint')
</code></pre>
<p>Here is what I do, and I wonder if there is a better way to do it:</p>
<pre><code>import urlparse
SCHEME = "qqqq"
# One would hope that there was a better way to do this
urlparse.uses_netloc.append(SCHEME)
urlparse.uses_fragment.append(SCHEME)
</code></pre>
<p>Why is there no better way to do this?</p>
| 13 | 2009-09-13T15:10:41Z | 34,902,870 | <p>The question appears to be out of date. Since at least Python 2.7 there are no issues.</p>
<pre><code>Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
>>> import urlparse
>>> urlparse.urlparse("qqqq://base/id#hint")
ParseResult(scheme='qqqq', netloc='base', path='/id', params='', query='', fragment='hint')
</code></pre>
| 2 | 2016-01-20T14:33:49Z | [
"python",
"url",
"python-2.6",
"urlparse"
] |
How to click a link that has javascript:__doPostBack in href? | 1,418,000 | <p>I am writing a screen scraper script in python with module 'mechanize' and I would like to use the mechanize.click_link() method on a link that has javascript:__doPostBack in href.
I believe the page I am trying to parse is using AJAX.</p>
<p>Note: mech is the mechanize.Browser()</p>
<pre><code>>>> next_link.__class__.__name__
'Link'
>>> next_link
Link(base_url='http://www.citius.mj.pt/Portal/consultas/ConsultasDistribuicao.aspx', url="javascript:__doPostBack('ctl00$ContentPlaceHolder1$Pager1$lnkNext','')", text='2', tag='a', attrs=[('id', 'ctl00_ContentPlaceHolder1_Pager1_lnkNext'), ('title', 'P\xc3\xa1gina seguinte: 2'), ('href', "javascript:__doPostBack('ctl00$ContentPlaceHolder1$Pager1$lnkNext','')")])
>>> req = mech.click_link(next_link)
>>> req
<urllib2.Request instance at 0x025BEE40>
>>> req.has_data()
False
</code></pre>
<p>I would like to retrieve the page source after clicking the link.</p>
| 4 | 2009-09-13T15:30:52Z | 1,418,394 | <p>I don't think <code>mechanize</code> supports Javascript; to scrape pages which intrinsically rely on Javascript execution for their functionality, you may need to use a different tool, such as <a href="http://seleniumhq.org/projects/remote-control/" rel="nofollow">Selenium RC</a>.</p>
| 1 | 2009-09-13T17:56:07Z | [
"javascript",
"python",
"mechanize"
] |
How to click a link that has javascript:__doPostBack in href? | 1,418,000 | <p>I am writing a screen scraper script in python with module 'mechanize' and I would like to use the mechanize.click_link() method on a link that has javascript:__doPostBack in href.
I believe the page I am trying to parse is using AJAX.</p>
<p>Note: mech is the mechanize.Browser()</p>
<pre><code>>>> next_link.__class__.__name__
'Link'
>>> next_link
Link(base_url='http://www.citius.mj.pt/Portal/consultas/ConsultasDistribuicao.aspx', url="javascript:__doPostBack('ctl00$ContentPlaceHolder1$Pager1$lnkNext','')", text='2', tag='a', attrs=[('id', 'ctl00_ContentPlaceHolder1_Pager1_lnkNext'), ('title', 'P\xc3\xa1gina seguinte: 2'), ('href', "javascript:__doPostBack('ctl00$ContentPlaceHolder1$Pager1$lnkNext','')")])
>>> req = mech.click_link(next_link)
>>> req
<urllib2.Request instance at 0x025BEE40>
>>> req.has_data()
False
</code></pre>
<p>I would like to retrieve the page source after clicking the link.</p>
| 4 | 2009-09-13T15:30:52Z | 1,553,659 | <pre><code>>>> next_link.__class__.__name__
'Link'
>>> next_link
Link(base_url='http://www.citius.mj.pt/Portal/consultas/ConsultasDistribuicao.aspx', url="javascript:__doPostBack('ctl00$ContentPlaceHolder1$Pager1$lnkNext','')", text='2', tag='a', attrs=[('id', 'ctl00_ContentPlaceHolder1_Pager1_lnkNext'), ('title', 'P\xc3\xa1gina seguinte: 2'), ('href', "javascript:__doPostBack('ctl00$ContentPlaceHolder1$Pager1$lnkNext','')")])
>>> req = mech.click_link(next_link)
>>> req
<urllib2.Request instance at 0x025BEE40>
>>> req.has_data()
False
</code></pre>
| 0 | 2009-10-12T09:51:26Z | [
"javascript",
"python",
"mechanize"
] |
How to click a link that has javascript:__doPostBack in href? | 1,418,000 | <p>I am writing a screen scraper script in python with module 'mechanize' and I would like to use the mechanize.click_link() method on a link that has javascript:__doPostBack in href.
I believe the page I am trying to parse is using AJAX.</p>
<p>Note: mech is the mechanize.Browser()</p>
<pre><code>>>> next_link.__class__.__name__
'Link'
>>> next_link
Link(base_url='http://www.citius.mj.pt/Portal/consultas/ConsultasDistribuicao.aspx', url="javascript:__doPostBack('ctl00$ContentPlaceHolder1$Pager1$lnkNext','')", text='2', tag='a', attrs=[('id', 'ctl00_ContentPlaceHolder1_Pager1_lnkNext'), ('title', 'P\xc3\xa1gina seguinte: 2'), ('href', "javascript:__doPostBack('ctl00$ContentPlaceHolder1$Pager1$lnkNext','')")])
>>> req = mech.click_link(next_link)
>>> req
<urllib2.Request instance at 0x025BEE40>
>>> req.has_data()
False
</code></pre>
<p>I would like to retrieve the page source after clicking the link.</p>
| 4 | 2009-09-13T15:30:52Z | 5,157,699 | <p>I don't use mechanize, but I do a lot of web scraping myself with python.<p>
When I run into a javascript function like __doPostBack, I do the following:<br>
I access the web site in Firefox, and use the <a href="https://addons.mozilla.org/en-US/firefox/addon/httpfox/" rel="nofollow">HttpFox</a> extension to see the parameters of the POST request the browser sent to the web server when clicking the relevant link.<br>
I then build the same request in python using urllib.parse.urlencode to build the query strings and POST data I need.<br>
Sometimes the website uses cookies as well, so I just use python's http.cookiejar.<p>
I have used this technique successfully several times.</p>
| 5 | 2011-03-01T17:00:16Z | [
"javascript",
"python",
"mechanize"
] |
How to get Python exception text | 1,418,015 | <p>I want to embed python in my C++ application. I'm using Boost library - great tool. But i have one problem. </p>
<p>If python function throws an exception, i want to catch it and print error in my application or get some detailed information like line number in python script that caused error.</p>
<p>How can i do it? I can't find any functions to get detailed exception information in Python API or Boost.</p>
<pre><code>try {
module=import("MyModule"); //this line will throw excetion if MyModule contains an error
} catch ( error_already_set const & ) {
//Here i can said that i have error, but i cant determine what caused an error
std::cout << "error!" << std::endl;
}
</code></pre>
<p>PyErr_Print() just prints error text to stderr and clears error so it can't be solution</p>
| 33 | 2009-09-13T15:36:30Z | 1,418,386 | <p>In the Python C API, <a href="http://docs.python.org/c-api/object.html#PyObject%5FStr" rel="nofollow"><code>PyObject_Str</code></a> returns a new reference to a Python string object with the string form of the Python object you're passing as the argument -- just like <code>str(o)</code> in Python code. Note that the exception object does not have "information like line number" -- that's in the <em>traceback</em> object (you can use <a href="http://docs.python.org/c-api/exceptions.html#PyErr%5FFetch" rel="nofollow"><code>PyErr_Fetch</code></a> to get both the exception object and the traceback object). Don't know what (if anything) Boost provides to make these specific C API functions easier to use, but, worst case, you could always resort to these functions as they are offered in the C API itself.</p>
| 4 | 2009-09-13T17:54:12Z | [
"c++",
"python",
"exception",
"boost-python"
] |
How to get Python exception text | 1,418,015 | <p>I want to embed python in my C++ application. I'm using Boost library - great tool. But i have one problem. </p>
<p>If python function throws an exception, i want to catch it and print error in my application or get some detailed information like line number in python script that caused error.</p>
<p>How can i do it? I can't find any functions to get detailed exception information in Python API or Boost.</p>
<pre><code>try {
module=import("MyModule"); //this line will throw excetion if MyModule contains an error
} catch ( error_already_set const & ) {
//Here i can said that i have error, but i cant determine what caused an error
std::cout << "error!" << std::endl;
}
</code></pre>
<p>PyErr_Print() just prints error text to stderr and clears error so it can't be solution</p>
| 33 | 2009-09-13T15:36:30Z | 1,418,703 | <p>Well, I found out how to do it.</p>
<p>Without boost (only error message, because code to extract info from traceback is too heavy to post it here):</p>
<pre><code>PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
//pvalue contains error message
//ptraceback contains stack snapshot and many other information
//(see python traceback structure)
//Get error message
char *pStrErrorMessage = PyString_AsString(pvalue);
</code></pre>
<p>And BOOST version</p>
<pre><code>try{
//some code that throws an error
}catch(error_already_set &){
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
handle<> hType(ptype);
object extype(hType);
handle<> hTraceback(ptraceback);
object traceback(hTraceback);
//Extract error message
string strErrorMessage = extract<string>(pvalue);
//Extract line number (top entry of call stack)
// if you want to extract another levels of call stack
// also process traceback.attr("tb_next") recurently
long lineno = extract<long> (traceback.attr("tb_lineno"));
string filename = extract<string>(traceback.attr("tb_frame").attr("f_code").attr("co_filename"));
string funcname = extract<string>(traceback.attr("tb_frame").attr("f_code").attr("co_name"));
... //cleanup here
</code></pre>
| 37 | 2009-09-13T20:05:17Z | [
"c++",
"python",
"exception",
"boost-python"
] |
How to get Python exception text | 1,418,015 | <p>I want to embed python in my C++ application. I'm using Boost library - great tool. But i have one problem. </p>
<p>If python function throws an exception, i want to catch it and print error in my application or get some detailed information like line number in python script that caused error.</p>
<p>How can i do it? I can't find any functions to get detailed exception information in Python API or Boost.</p>
<pre><code>try {
module=import("MyModule"); //this line will throw excetion if MyModule contains an error
} catch ( error_already_set const & ) {
//Here i can said that i have error, but i cant determine what caused an error
std::cout << "error!" << std::endl;
}
</code></pre>
<p>PyErr_Print() just prints error text to stderr and clears error so it can't be solution</p>
| 33 | 2009-09-13T15:36:30Z | 6,576,177 | <p>This is the most robust method I've been able to come up so far:</p>
<pre><code> try {
...
}
catch (bp::error_already_set) {
if (PyErr_Occurred()) {
msg = handle_pyerror();
}
py_exception = true;
bp::handle_exception();
PyErr_Clear();
}
if (py_exception)
....
// decode a Python exception into a string
std::string handle_pyerror()
{
using namespace boost::python;
using namespace boost;
PyObject *exc,*val,*tb;
object formatted_list, formatted;
PyErr_Fetch(&exc,&val,&tb);
handle<> hexc(exc),hval(allow_null(val)),htb(allow_null(tb));
object traceback(import("traceback"));
if (!tb) {
object format_exception_only(traceback.attr("format_exception_only"));
formatted_list = format_exception_only(hexc,hval);
} else {
object format_exception(traceback.attr("format_exception"));
formatted_list = format_exception(hexc,hval,htb);
}
formatted = str("\n").join(formatted_list);
return extract<std::string>(formatted);
}
</code></pre>
| 15 | 2011-07-04T21:22:58Z | [
"c++",
"python",
"exception",
"boost-python"
] |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | <p>I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also?</p>
| 76 | 2009-09-13T16:07:53Z | 1,418,419 | <p>There are a few options:</p>
<ul>
<li><p>You could use Selenium Grid so that the browser is opened on a completely different machine (or virtual machine) that you can then connect to via VNC or Remote Desktop Connection if you wanted to see the browser. Also, another option: if you run a Jenkins foreground process on that remote server, it can execute your test project on the desktop.</p></li>
<li><p>You can run Selenium 'headless' on Linux in XVFB. I've never tried doing this and doubt it's really worth the effort. <a href="http://www.alittlemadness.com/2008/03/05/running-selenium-headless/">http://www.alittlemadness.com/2008/03/05/running-selenium-headless/</a></p></li>
<li><p>You can wrap Selenium RC in a Windows service. <a href="http://support.microsoft.com/kb/137890">http://support.microsoft.com/kb/137890</a> . Except that permissions constraints on later versions of windows will probably prevent Selenium from accessing the desktop like Windows 2000 used to allow us to do.</p></li>
<li><p>Another option would be to use something like WebDriver HTMLUnitDriver, which doesn't launch a 'real' browser. <a href="http://code.google.com/p/webdriver/">http://code.google.com/p/webdriver/</a> . Also there is a PhantomJS option as well as a 'headless Chrome' that you could use.</p></li>
<li><p>Of course there's also the option of using a service like SauceLabs, where you can get your tests to be run in the cloud. After your tests have completed you can watch a video of them running.</p></li>
</ul>
| 77 | 2009-09-13T18:04:33Z | [
"python",
"selenium",
"selenium-rc"
] |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | <p>I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also?</p>
| 76 | 2009-09-13T16:07:53Z | 1,419,676 | <p>+1 for Selenium RC as a windows service.</p>
<p>For having the tests run completely hidden, I think you don't have much solutions if you're on windows. </p>
<p>What I'd do it to dedicate a computer in your LAN to be online all the time and have a selenium RC server running. So you use that computer's IP instead of localhost to run your tests. For example:</p>
<pre><code>browser = selenium("10.15.12.34",4444,"*firefox","http://saucelabs.com")
</code></pre>
<p>(considering that that's the ip of the computer running the server).</p>
<p>Having that setup, you run your tests in you computer, the browsers and the RC server window are in another computer and the go back to yours once done.</p>
| 13 | 2009-09-14T04:28:56Z | [
"python",
"selenium",
"selenium-rc"
] |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | <p>I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also?</p>
| 76 | 2009-09-13T16:07:53Z | 1,750,751 | <p>If you're on Windows, one option is to <strong>run the tests under a different user account</strong>. This means the browser and java server will not be visible to your own account.</p>
| 5 | 2009-11-17T18:16:16Z | [
"python",
"selenium",
"selenium-rc"
] |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | <p>I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also?</p>
| 76 | 2009-09-13T16:07:53Z | 8,910,326 | <p>On *nix, you can run WebDriver in a headless (virtual) display to hide the browser. This can be done with <a href="http://en.wikipedia.org/wiki/Xvfb">Xvfb</a>.</p>
<p>I personally use Python on Linux, and the <a href="http://pypi.python.org/pypi/PyVirtualDisplay">PyVirtualDisplay</a> module to handle Xvfb for me.</p>
<p>Code for running headless would look like this:</p>
<pre><code>#!/usr/bin/env python
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
# now Firefox will run in a virtual display.
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()
display.stop()
</code></pre>
<p>Install dependencies on Debian/Ubuntu:</p>
<pre><code>$ sudo apt-get install xvfb python-pip
$ sudo pip install pyvirtualdisplay
</code></pre>
| 49 | 2012-01-18T12:48:05Z | [
"python",
"selenium",
"selenium-rc"
] |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | <p>I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also?</p>
| 76 | 2009-09-13T16:07:53Z | 11,261,393 | <p>This is how I run my tests with maven on a linux desktop (Ubuntu). I got fed up not being able to work with the firefox webdriver always taking focus.</p>
<p>I installed xvfb </p>
<blockquote>
<p>xvfb-run -a mvn clean install</p>
</blockquote>
<p>Thats it</p>
| 3 | 2012-06-29T12:00:18Z | [
"python",
"selenium",
"selenium-rc"
] |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | <p>I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also?</p>
| 76 | 2009-09-13T16:07:53Z | 14,155,698 | <p>On Linux, you can run your test browser on a virtual display. You will need the <code>xvfb</code> package for creating a virtual X server. On Debian based distros, just run</p>
<pre><code>sudo apt-get install xvfb
</code></pre>
<p>There is a nice tool <a href="http://semicomplete.com/blog/geekery/headless-wrapper-for-ephemeral-xservers.html"><code>ephemeral-x.sh</code></a> that will conveniently set up any command to run on the virtual display. <a href="https://github.com/jordansissel/xdotool/blob/master/t/ephemeral-x.sh">Download it</a> and make it executable:</p>
<pre><code>wget https://raw.github.com/jordansissel/xdotool/master/t/ephemeral-x.sh
chmod +x ephemeral-x.sh
</code></pre>
<p>Then you can simply use it to start the Selenium server:</p>
<pre><code>./ephemeral-x.sh java -jar selenium-standalone.jar
</code></pre>
<p>All browser windows created by Selenium will now use the virtual display and will be invisible to you.</p>
| 11 | 2013-01-04T10:50:19Z | [
"python",
"selenium",
"selenium-rc"
] |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | <p>I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also?</p>
| 76 | 2009-09-13T16:07:53Z | 22,846,912 | <p>There is a PhantomJS related project called <a href="https://github.com/detro/ghostdriver" rel="nofollow">GhostDriver</a> , that is meant to run PhantomJS instances in a Selenium Grid using webdriver wire JSON protocol. That is probably what you are looking for, although this question is 4 years old now.</p>
| 0 | 2014-04-03T19:17:02Z | [
"python",
"selenium",
"selenium-rc"
] |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | <p>I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also?</p>
| 76 | 2009-09-13T16:07:53Z | 23,898,054 | <p>I easily managed to hide the browser window.</p>
<p>Just <a href="http://phantomjs.org/download.html">install PhantomJS</a>. Then, change this line:</p>
<pre><code>driver = webdriver.Firefox()
</code></pre>
<p>to:</p>
<pre><code>driver = webdriver.PhantomJS()
</code></pre>
<p>The rest of your code won't need to be changed and no browser will open. For debugging purposes, use <code>driver.save_screenshot('screen.png')</code> at different steps of your code.</p>
| 13 | 2014-05-27T20:11:00Z | [
"python",
"selenium",
"selenium-rc"
] |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | <p>I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also?</p>
| 76 | 2009-09-13T16:07:53Z | 24,662,478 | <p>On MacOSX, I haven't been able to hide the browser window, but at least I figured out how to move it to a different display so it doesn't disrupt my workflow so much. While Firefox is running tests, just control-click its icon in the dock, select Options, and Assign to Display 2.</p>
| 0 | 2014-07-09T19:43:35Z | [
"python",
"selenium",
"selenium-rc"
] |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | <p>I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also?</p>
| 76 | 2009-09-13T16:07:53Z | 38,768,819 | <pre><code>curl -k https://gist.githubusercontent.com/terrancesnyder/995250/raw/cdd1f52353bb614a5a016c2e8e77a2afb718f3c3/ephemeral-x.sh -o ~/ephemeral-x.sh
chmod +x ~/ephemeral-x.sh
~/ephemeral-x.sh TestsStarterCommand
</code></pre>
<p>By the way this is a feature needed by any developer running e2e that logically will spawn browsers. In a development environment it is annoying to deal with the window that keeps popping up and which which you can accidentally interact making the test fail.</p>
| 0 | 2016-08-04T13:32:28Z | [
"python",
"selenium",
"selenium-rc"
] |
django newbie. Having trouble with ModelForm | 1,418,149 | <p>i'm trying to write a very simple django app. I cant get it to show my form inside my template.</p>
<pre><code><form ...>
{{form.as_p}}
</form>
</code></pre>
<p>it shows absolutely nothing. If I add a submit button, it only shows that. </p>
<p>Do I have to declare a form object that inherits from forms.Form ? Cant it be done with ModelForms? </p>
<h1>[UPDATE]Solved! (apologize for wasting your time)</h1>
<p>In my urls file I had:</p>
<pre><code>(r'login/$',direct_to_template, {'template':'register.html'}
</code></pre>
<p>Switched to:</p>
<pre><code>(r'login/$','portal.views.register')
</code></pre>
<p>And yes, I feel terrible. </p>
<h1>Background:</h1>
<p>I have a Student model, and I have a registration page. When it is accessed, it should display a textfield asking for students name. If the student completes that field, then it saves it.</p>
<pre><code>#models.py
class Student(models.Model):
name = models.CharField(max_length =50)
#forms.py
class StudentForm (forms.ModelForm):
class Meta:
model = Student
</code></pre>
<p>So, here is my view:</p>
<pre><code>def register(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
return render_to_response('/thanks/')
else:
student = Student()
form = StudentForm(instance =student)
return render_to_response('register.html',{'form':form})
</code></pre>
| 0 | 2009-09-13T16:34:23Z | 1,418,206 | <p>The problem is in your view. You will have no existing student object to retrieve from the database. The following code sample will help you implement an "create" view.</p>
<p>As a side note, you might like using the direct_to_template generic view function to make your life a bit easier.</p>
<pre><code>def add_student(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
new_student = form.save()
return HttpResponseRedirect('/back/to/somewhere/on/success/')
else:
form = StudentForm()
return direct_to_template(request,
'register.html',
{'form':form})
</code></pre>
| 2 | 2009-09-13T16:52:09Z | [
"python",
"django"
] |
Python implementation question | 1,418,255 | <p>Hey. I have a problem I'm trying to solve in Python and I can't think of a clever implementation. The input is a string of letters. Some of them represent variables, others represent operators, and I want to iterate over a large amount of values for the variables (different configurations).</p>
<p>I think an equivalent question would be that you get an equation with many variables stored as a string and you want to see the solution when you substitute x,y,z etc. for many different values, or satisfying a boolean formula.</p>
<p>I can't think of any clever data structure that would implement this - just 'setting' the formula every time, substiuting variables, takes more time than actually evaluating it.</p>
<p>I know it's a bit abstract - but anyone has any ideas or has experience with somtehing similar?</p>
<p>Someone usggested I want to implement an evaluator. It's true but beside the point. For the sake of the question supposed the eval(string) function is already implemented. What is an efficient data structure that will hold the values and allow to change them every time cleanly and efficiently? Surely not a string! It has to be a modifiable list. And if it has a few instances of the variable x, it should be able to accsess them all fast and change their value before evaluation, etc, etc.</p>
| 0 | 2009-09-13T17:11:39Z | 1,418,273 | <p>What you want is obviously an expression evaluator.</p>
<p>Other you use a built in facility in the language typically called "eval" (I don't know if Python offers this) or you build an expression parser/evaluator.</p>
<p>To get some of ideas of how to build such an expression evaluator,
you can look at the following SO golf exercise:
<a href="http://stackoverflow.com/questions/1384811/code-golf-mathematical-expression-evaluator-full-pemdas">http://stackoverflow.com/questions/1384811/code-golf-mathematical-expression-evaluator-full-pemdas</a></p>
<p>To do what you want, you'd have to translate the basic ideas (they're all pretty much the same) to Pythonese, and add a facility to parse variable names and look up their values.
That should be a very straightforward extension.</p>
| 0 | 2009-09-13T17:18:24Z | [
"python",
"data-structures",
"implementation",
"formula"
] |
Python implementation question | 1,418,255 | <p>Hey. I have a problem I'm trying to solve in Python and I can't think of a clever implementation. The input is a string of letters. Some of them represent variables, others represent operators, and I want to iterate over a large amount of values for the variables (different configurations).</p>
<p>I think an equivalent question would be that you get an equation with many variables stored as a string and you want to see the solution when you substitute x,y,z etc. for many different values, or satisfying a boolean formula.</p>
<p>I can't think of any clever data structure that would implement this - just 'setting' the formula every time, substiuting variables, takes more time than actually evaluating it.</p>
<p>I know it's a bit abstract - but anyone has any ideas or has experience with somtehing similar?</p>
<p>Someone usggested I want to implement an evaluator. It's true but beside the point. For the sake of the question supposed the eval(string) function is already implemented. What is an efficient data structure that will hold the values and allow to change them every time cleanly and efficiently? Surely not a string! It has to be a modifiable list. And if it has a few instances of the variable x, it should be able to accsess them all fast and change their value before evaluation, etc, etc.</p>
| 0 | 2009-09-13T17:11:39Z | 1,418,334 | <p>Parse that string into a tree (or equivalently interpretable data structure), just once, and then repeatedly use a function to "interpret the tree" for each variable-assignment-set of interest. (You could even generate Python bytecode as the "interpretable data structure" so you can just use <code>eval</code> as the "interpret the tree" -- that makes for slow generation, but that's needed only once, and fast interpretation).</p>
<p>As you say that's a bit abstract so let's give a concrete, if over-simplistic, example. Say for example that the variables are the letters x, y, z, t, and the operators are a for addition and s for subtraction -- strings of adjacent letters implicitly mean high-priority multiplication, as in common mathematical convention; no parentheses, and strict left-to-right execution (i.e. no operator precedence, beyond multiplication). Every character except these 6 must be ignored. Here, then, is a very ad-hoc parser and Python bytecode generator:</p>
<pre><code>class BadString(Exception): pass
def makeBytecode(thestring):
theoperator = dict(a='+', s='-')
python = []
state = 'start'
for i, letter in enumerate(thestring):
if letter in 'xyzt':
if state == 'start':
python.append(letter)
state = 'variable'
elif state == 'variable':
python.append('*')
python.append(letter)
elif letter in 'as':
if state == 'start':
raise BadString(
'Unexpected operator %r at column %d' % (letter, i))
python.append(theoperator[letter])
state = 'start'
if state != 'variable':
raise BadString(
'Unexpected operator %r at end of string' % letter)
python = ''.join(python)
# sanity check
# print 'Python for %r is %r' % (thestring, python)
return compile(python, thestring, 'eval')
</code></pre>
<p>Now, you can simply call <code>eval</code> with the result of this as the first argument and the dict associating values to x, y, z and t as the second argument. For example (having imported the above module as <code>par</code> and uncommented the sanity check):</p>
<pre><code>>>> c=par.makeBytecode('xyax')
Python for 'xyax' is 'x*y+x'
>>> for x in range(4):
... for y in range(5):
... print 'x=%s, y=%s: result=%s' % (x,y,eval(c,dict(x=x,y=y)))
...
x=0, y=0: result=0
x=0, y=1: result=0
x=0, y=2: result=0
x=0, y=3: result=0
x=0, y=4: result=0
x=1, y=0: result=1
x=1, y=1: result=2
x=1, y=2: result=3
x=1, y=3: result=4
x=1, y=4: result=5
x=2, y=0: result=2
x=2, y=1: result=4
x=2, y=2: result=6
x=2, y=3: result=8
x=2, y=4: result=10
x=3, y=0: result=3
x=3, y=1: result=6
x=3, y=2: result=9
x=3, y=3: result=12
x=3, y=4: result=15
>>>
</code></pre>
<p>For more sophisticated, yet still simple!, parsing of the string & building of the rapidly interpretable data structure, see for example <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a>.</p>
| 0 | 2009-09-13T17:39:22Z | [
"python",
"data-structures",
"implementation",
"formula"
] |
Python implementation question | 1,418,255 | <p>Hey. I have a problem I'm trying to solve in Python and I can't think of a clever implementation. The input is a string of letters. Some of them represent variables, others represent operators, and I want to iterate over a large amount of values for the variables (different configurations).</p>
<p>I think an equivalent question would be that you get an equation with many variables stored as a string and you want to see the solution when you substitute x,y,z etc. for many different values, or satisfying a boolean formula.</p>
<p>I can't think of any clever data structure that would implement this - just 'setting' the formula every time, substiuting variables, takes more time than actually evaluating it.</p>
<p>I know it's a bit abstract - but anyone has any ideas or has experience with somtehing similar?</p>
<p>Someone usggested I want to implement an evaluator. It's true but beside the point. For the sake of the question supposed the eval(string) function is already implemented. What is an efficient data structure that will hold the values and allow to change them every time cleanly and efficiently? Surely not a string! It has to be a modifiable list. And if it has a few instances of the variable x, it should be able to accsess them all fast and change their value before evaluation, etc, etc.</p>
| 0 | 2009-09-13T17:11:39Z | 1,418,346 | <p>as Ira said you need an expression evaluator like Lex/Yacc to do this job, you have plenty available here :</p>
<p><a href="http://wiki.python.org/moin/LanguageParsing" rel="nofollow">http://wiki.python.org/moin/LanguageParsing</a></p>
<p>I have been using <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a> and works greats for that kind of things</p>
| 1 | 2009-09-13T17:42:08Z | [
"python",
"data-structures",
"implementation",
"formula"
] |
Python implementation question | 1,418,255 | <p>Hey. I have a problem I'm trying to solve in Python and I can't think of a clever implementation. The input is a string of letters. Some of them represent variables, others represent operators, and I want to iterate over a large amount of values for the variables (different configurations).</p>
<p>I think an equivalent question would be that you get an equation with many variables stored as a string and you want to see the solution when you substitute x,y,z etc. for many different values, or satisfying a boolean formula.</p>
<p>I can't think of any clever data structure that would implement this - just 'setting' the formula every time, substiuting variables, takes more time than actually evaluating it.</p>
<p>I know it's a bit abstract - but anyone has any ideas or has experience with somtehing similar?</p>
<p>Someone usggested I want to implement an evaluator. It's true but beside the point. For the sake of the question supposed the eval(string) function is already implemented. What is an efficient data structure that will hold the values and allow to change them every time cleanly and efficiently? Surely not a string! It has to be a modifiable list. And if it has a few instances of the variable x, it should be able to accsess them all fast and change their value before evaluation, etc, etc.</p>
| 0 | 2009-09-13T17:11:39Z | 1,418,398 | <p>I see that the <code>eval</code> idea has already been mentioned, and this won't help if you have operators to substitute, but I've used the following in the past:</p>
<pre><code>def evaluate_expression(expr, context):
try:
return eval(expr, {'__builtins__': None}, context)
except (TypeError, ZeroDivisionError, SyntaxError):
# TypeError is when combining items in the wrong way (ie, None + 4)
# ZeroDivisionError is when the denominator happens to be zero (5/0)
# SyntaxError is when the expression is invalid
return None
</code></pre>
<p>You could then do something like:</p>
<pre><code>values = {
'a': 1.0,
'b': 5.0,
'c': 1.0,
}
evaluate_expression('a + b - (1/c)', **values)
</code></pre>
<p>which would evaluate to 1.0 + 5.0 - 1/1.0 == 5.0</p>
<p>Again, this won't let you substitute in operators, that is, you can't let 'd' evaluate to +, but it gives you a safe way of using the <code>eval</code> function in Python (you can't run "while True" for example).</p>
<p>See <a href="http://lybniz2.sourceforge.net/safeeval.html" rel="nofollow">this example</a> for more information on using <code>eval</code> safely.</p>
| 0 | 2009-09-13T17:56:41Z | [
"python",
"data-structures",
"implementation",
"formula"
] |
Access an instance from Terminal | 1,418,262 | <p>Can't figure this out. In Terminal, I import a module which instantiates a class, which I haven't figured out how to access. Of course, I can always instantiate in Terminal:</p>
<pre>
Server=Data.ServerData()
</pre>
<p>Then I can get a result:</p>
<pre>
Server.Property().DefaultChart
</pre>
<p>However, I want to skip that step getting the result directly from the instance already running in the module. I think Data.Server in this case should load the Server instance from when I imported Data:</p>
<pre>
Data.Server.Property().DefaultChart
>>> AttributeError: 'module' object has no attribute 'Server'
</pre>
<p>So how to access the running instance from Terminal?</p>
| 0 | 2009-09-13T17:14:22Z | 1,418,356 | <p>If importing <code>Data.py</code> implicitly creates an instance of the <code>Data.ServerData</code> class (somewhat dubious, but OK in certain cases), that still tells us nothing about how that module chose to name that one instance. Do <code>dir(Data)</code> at the <code>>>></code> prompt to see all the names defined in the <code>Data</code> module; if you want to see what names (if any!) have values that are instances of <code>Data.ServerData</code>, e.g.:</p>
<pre><code>>>> [n for n in dir(Data) if isinstance(getattr(Data,n), Data.ServerData)]
</code></pre>
<p>Reading <code>Data.py</code>'s source code might be simpler, but you do have many other options for such introspection to find out exactly what's going on (and how it differ from what you EXPECTED [[not sure on what basis!]] to be going on).</p>
| 2 | 2009-09-13T17:46:48Z | [
"python",
"class",
"module",
"instance",
"interactive"
] |
Which is more pythonic for array removal? | 1,418,266 | <p>I'm removing an item from an array if it exists.</p>
<p>Two ways I can think of to do this</p>
<h2>Way #1</h2>
<pre>
# x array, r item to remove
if r in x :
x.remove( r )
</pre>
<h2>Way #2</h2>
<pre>
try :
x.remove( r )
except :
pass
</pre>
<p>Timing it shows the try/except way <b>can be</b> faster</p>
<p>(some times i'm getting:)</p>
<pre>
1.16225508968e-06
8.80804972547e-07
1.14314196588e-06
8.73752536492e-07
</pre>
<pre>
import timeit
runs = 10000
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
code1 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
if r in x :
x.remove(r)
"""
print timeit.Timer( code1 ).timeit( runs ) / runs
code2 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
try :
x.remove( r )
except :
pass
"""
print timeit.Timer( code2 ).timeit( runs ) / runs
</pre>
<p>Which is more pythonic?</p>
| 2 | 2009-09-13T17:15:54Z | 1,418,275 | <p>The try/except way</p>
| 2 | 2009-09-13T17:18:56Z | [
"python"
] |
Which is more pythonic for array removal? | 1,418,266 | <p>I'm removing an item from an array if it exists.</p>
<p>Two ways I can think of to do this</p>
<h2>Way #1</h2>
<pre>
# x array, r item to remove
if r in x :
x.remove( r )
</pre>
<h2>Way #2</h2>
<pre>
try :
x.remove( r )
except :
pass
</pre>
<p>Timing it shows the try/except way <b>can be</b> faster</p>
<p>(some times i'm getting:)</p>
<pre>
1.16225508968e-06
8.80804972547e-07
1.14314196588e-06
8.73752536492e-07
</pre>
<pre>
import timeit
runs = 10000
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
code1 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
if r in x :
x.remove(r)
"""
print timeit.Timer( code1 ).timeit( runs ) / runs
code2 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
try :
x.remove( r )
except :
pass
"""
print timeit.Timer( code2 ).timeit( runs ) / runs
</pre>
<p>Which is more pythonic?</p>
| 2 | 2009-09-13T17:15:54Z | 1,418,293 | <p>that would be:</p>
<pre><code>try:
x.remove(r)
except ValueError:
pass
</code></pre>
<p>btw, you should have tried to remove an item that is not in the list, to have a comprehensive comparison.</p>
| 5 | 2009-09-13T17:22:19Z | [
"python"
] |
Which is more pythonic for array removal? | 1,418,266 | <p>I'm removing an item from an array if it exists.</p>
<p>Two ways I can think of to do this</p>
<h2>Way #1</h2>
<pre>
# x array, r item to remove
if r in x :
x.remove( r )
</pre>
<h2>Way #2</h2>
<pre>
try :
x.remove( r )
except :
pass
</pre>
<p>Timing it shows the try/except way <b>can be</b> faster</p>
<p>(some times i'm getting:)</p>
<pre>
1.16225508968e-06
8.80804972547e-07
1.14314196588e-06
8.73752536492e-07
</pre>
<pre>
import timeit
runs = 10000
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
code1 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
if r in x :
x.remove(r)
"""
print timeit.Timer( code1 ).timeit( runs ) / runs
code2 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
try :
x.remove( r )
except :
pass
"""
print timeit.Timer( code2 ).timeit( runs ) / runs
</pre>
<p>Which is more pythonic?</p>
| 2 | 2009-09-13T17:15:54Z | 1,418,308 | <p>The first way looks cleaner. The second looks like a lot of extra effort just to remove an item from a list.</p>
<p>There's nothing about it in <a href="http://python.org/dev/peps/pep-0008/" rel="nofollow">PEP-8</a>, though, so whichever you prefer is the 'real' answer.</p>
<p>Speaking of PEP-8... having that space before the colon falls under the definition of 'extraneous whitespace'.</p>
| 1 | 2009-09-13T17:29:16Z | [
"python"
] |
Which is more pythonic for array removal? | 1,418,266 | <p>I'm removing an item from an array if it exists.</p>
<p>Two ways I can think of to do this</p>
<h2>Way #1</h2>
<pre>
# x array, r item to remove
if r in x :
x.remove( r )
</pre>
<h2>Way #2</h2>
<pre>
try :
x.remove( r )
except :
pass
</pre>
<p>Timing it shows the try/except way <b>can be</b> faster</p>
<p>(some times i'm getting:)</p>
<pre>
1.16225508968e-06
8.80804972547e-07
1.14314196588e-06
8.73752536492e-07
</pre>
<pre>
import timeit
runs = 10000
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
code1 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
if r in x :
x.remove(r)
"""
print timeit.Timer( code1 ).timeit( runs ) / runs
code2 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
try :
x.remove( r )
except :
pass
"""
print timeit.Timer( code2 ).timeit( runs ) / runs
</pre>
<p>Which is more pythonic?</p>
| 2 | 2009-09-13T17:15:54Z | 1,418,310 | <p>I've always gone with the first method. <code>if in</code> reads far more clearly than exception handling does.</p>
| 6 | 2009-09-13T17:30:13Z | [
"python"
] |
Which is more pythonic for array removal? | 1,418,266 | <p>I'm removing an item from an array if it exists.</p>
<p>Two ways I can think of to do this</p>
<h2>Way #1</h2>
<pre>
# x array, r item to remove
if r in x :
x.remove( r )
</pre>
<h2>Way #2</h2>
<pre>
try :
x.remove( r )
except :
pass
</pre>
<p>Timing it shows the try/except way <b>can be</b> faster</p>
<p>(some times i'm getting:)</p>
<pre>
1.16225508968e-06
8.80804972547e-07
1.14314196588e-06
8.73752536492e-07
</pre>
<pre>
import timeit
runs = 10000
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
code1 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
if r in x :
x.remove(r)
"""
print timeit.Timer( code1 ).timeit( runs ) / runs
code2 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'
try :
x.remove( r )
except :
pass
"""
print timeit.Timer( code2 ).timeit( runs ) / runs
</pre>
<p>Which is more pythonic?</p>
| 2 | 2009-09-13T17:15:54Z | 1,418,321 | <p>Speed depends on the ratio of hits to misses. To be pythonic choose the clearer method.</p>
<p>Personally I think way#1 is clearer (It takes less lines to have an 'if' block rather than an exception block and also uses less brain space). It will also be faster when there are more hits than misses (an exception is more expensive than skipping a if block).</p>
| 3 | 2009-09-13T17:34:35Z | [
"python"
] |
Auto executable python file without opening from terminal? | 1,418,553 | <p>Sorry if this is on the wrong site ( maybe superuser ) but I'm trying to make my python.py file executable so I can click on it and it automatically does its thing, without me specifying it to open in the terminal by that default prompt, and I already have 'chmod +x' for its permissions.</p>
<p><strong>Clarification:</strong></p>
<ul>
<li>I want to run it by clicking on it, not through the terminal ( I meant that when I said 'can click on it and it automatically does its thing ' )</li>
<li>Already have a shebang line</li>
<li>When I click it right now, it prompts me with do you want to open it in a text file, terminal - can I make it always default to opening in the terminal or is this just an oddball request?</li>
</ul>
| 2 | 2009-09-13T18:53:39Z | 1,418,559 | <p>Have you placed this at the beginning of the file:</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>?</p>
| 0 | 2009-09-13T18:55:03Z | [
"python",
"linux"
] |
Auto executable python file without opening from terminal? | 1,418,553 | <p>Sorry if this is on the wrong site ( maybe superuser ) but I'm trying to make my python.py file executable so I can click on it and it automatically does its thing, without me specifying it to open in the terminal by that default prompt, and I already have 'chmod +x' for its permissions.</p>
<p><strong>Clarification:</strong></p>
<ul>
<li>I want to run it by clicking on it, not through the terminal ( I meant that when I said 'can click on it and it automatically does its thing ' )</li>
<li>Already have a shebang line</li>
<li>When I click it right now, it prompts me with do you want to open it in a text file, terminal - can I make it always default to opening in the terminal or is this just an oddball request?</li>
</ul>
| 2 | 2009-09-13T18:53:39Z | 1,418,563 | <p>On the first line in your python file, add this:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>So if you have:</p>
<pre><code>print "Hello World"
</code></pre>
<p>You should then have:</p>
<pre><code>#!/usr/bin/env python
print "Hello World"
</code></pre>
| 4 | 2009-09-13T18:56:01Z | [
"python",
"linux"
] |
Auto executable python file without opening from terminal? | 1,418,553 | <p>Sorry if this is on the wrong site ( maybe superuser ) but I'm trying to make my python.py file executable so I can click on it and it automatically does its thing, without me specifying it to open in the terminal by that default prompt, and I already have 'chmod +x' for its permissions.</p>
<p><strong>Clarification:</strong></p>
<ul>
<li>I want to run it by clicking on it, not through the terminal ( I meant that when I said 'can click on it and it automatically does its thing ' )</li>
<li>Already have a shebang line</li>
<li>When I click it right now, it prompts me with do you want to open it in a text file, terminal - can I make it always default to opening in the terminal or is this just an oddball request?</li>
</ul>
| 2 | 2009-09-13T18:53:39Z | 1,418,600 | <p>As others have said, you need put the <a href="http://en.wikipedia.org/wiki/Shebang%5F(Unix)" rel="nofollow">"shebang"</a> at the start of the file, to say which interpreter to use to execute the file.</p>
<p>As mentioned in the above link, the most portable way is to use the <code>env</code> command (instead of a fixed path to <code>python</code>) - put this as the first line in the file:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>The shell will look in <code>$PATH</code> for your <code>python</code>, rather than looking for <code>/usr/local/bin/python</code> then failing. This means it will work if Python is installed in a non-standard location.</p>
<p>For example:</p>
<pre><code>$ cat example.py
print "Test"
$ file example.py #Â it is treated as an ASCII file
example.py: ASCII text
$ chmod +x example.py
$ ./example.py # when executed, it defaults to being executed as a shell script
./example.py: line 1: print: command not found
</code></pre>
<p>Now, if I add the "shebang" line...</p>
<pre><code>$ cat example.py
#!/usr/bin/env python
print "Test"
$ file example.py #Â it is recognised as a Python script
example.py: a python script text executable
$ ./example.py # and executes correctly
Test
</code></pre>
| 0 | 2009-09-13T19:13:12Z | [
"python",
"linux"
] |
Auto executable python file without opening from terminal? | 1,418,553 | <p>Sorry if this is on the wrong site ( maybe superuser ) but I'm trying to make my python.py file executable so I can click on it and it automatically does its thing, without me specifying it to open in the terminal by that default prompt, and I already have 'chmod +x' for its permissions.</p>
<p><strong>Clarification:</strong></p>
<ul>
<li>I want to run it by clicking on it, not through the terminal ( I meant that when I said 'can click on it and it automatically does its thing ' )</li>
<li>Already have a shebang line</li>
<li>When I click it right now, it prompts me with do you want to open it in a text file, terminal - can I make it always default to opening in the terminal or is this just an oddball request?</li>
</ul>
| 2 | 2009-09-13T18:53:39Z | 1,419,455 | <p>First, pick a file extension you want for files you want to have this behavior. pyw is probably a good choice. </p>
<p>Name your file that, and in your file browser associate that file type with python. In GNOME, you'd open its Properties window, go to the Open With tab, and enter python as a custom command. </p>
<p>Now here's the important part: That little dialog you've been getting asking you what you'd like to do with the file is because it is marked as executable. Remove the executable bit with chmod -x. Now when you double click it, it will simply be opened with the associated program.</p>
<p>Of course, if you want to run it from the command line, you'll now have to start it with python explicitly since it isn't marked executable. The shebang line doesn't matter anymore, but I'd leave it in anyway in case someone else marks it executable and expects it to work.</p>
| 3 | 2009-09-14T02:30:50Z | [
"python",
"linux"
] |
Auto executable python file without opening from terminal? | 1,418,553 | <p>Sorry if this is on the wrong site ( maybe superuser ) but I'm trying to make my python.py file executable so I can click on it and it automatically does its thing, without me specifying it to open in the terminal by that default prompt, and I already have 'chmod +x' for its permissions.</p>
<p><strong>Clarification:</strong></p>
<ul>
<li>I want to run it by clicking on it, not through the terminal ( I meant that when I said 'can click on it and it automatically does its thing ' )</li>
<li>Already have a shebang line</li>
<li>When I click it right now, it prompts me with do you want to open it in a text file, terminal - can I make it always default to opening in the terminal or is this just an oddball request?</li>
</ul>
| 2 | 2009-09-13T18:53:39Z | 7,682,271 | <p><a href="http://supervisord.org" rel="nofollow">http://supervisord.org</a> is better choice. </p>
| 1 | 2011-10-07T01:38:47Z | [
"python",
"linux"
] |
How expensive are Python dictionaries to handle? | 1,418,588 | <p>As the title states, how expensive are Python dictionaries to handle? Creation, insertion, updating, deletion, all of it.</p>
<p>Asymptotic time complexities are interesting themselves, but also how they compare to e.g. tuples or normal lists.</p>
| 23 | 2009-09-13T19:03:50Z | 1,418,591 | <p>Dictionaries are one of the more heavily tuned parts of Python, since they underlie so much of the language. For example, members of a class, and variables in a stack frame are both stored internally in dictionaries. They will be a good choice if they are the right data structure.</p>
<p>Choosing between lists and dicts based on performance seems odd: they do different things. Maybe you can tell us more about the problem you are trying to solve.</p>
| 10 | 2009-09-13T19:05:33Z | [
"python",
"performance",
"data-structures",
"dictionary"
] |
How expensive are Python dictionaries to handle? | 1,418,588 | <p>As the title states, how expensive are Python dictionaries to handle? Creation, insertion, updating, deletion, all of it.</p>
<p>Asymptotic time complexities are interesting themselves, but also how they compare to e.g. tuples or normal lists.</p>
| 23 | 2009-09-13T19:03:50Z | 1,419,324 | <p><code>dicts</code> (just like <code>set</code>s when you don't need to associate a value to each key but simply record if a key is present or absent) are pretty heavily optimized. Creating a <code>dict</code> from N keys or key/value pairs is <code>O(N)</code>, fetching is <code>O(1)</code>, putting is amortized <code>O(1)</code>, and so forth. Can't really do anything substantially better for any non-tiny container!</p>
<p>For tiny containers, you can easily check the boundaries with <code>timeit</code>-based benchmarks. For example:</p>
<pre><code>$ python -mtimeit -s'empty=()' '23 in empty'
10000000 loops, best of 3: 0.0709 usec per loop
$ python -mtimeit -s'empty=set()' '23 in empty'
10000000 loops, best of 3: 0.101 usec per loop
$ python -mtimeit -s'empty=[]' '23 in empty'
10000000 loops, best of 3: 0.0716 usec per loop
$ python -mtimeit -s'empty=dict()' '23 in empty'
10000000 loops, best of 3: 0.0926 usec per loop
</code></pre>
<p>this shows that checking membership in empty lists or tuples is faster, by a whopping 20-30 nanoseconds, than checking membership in empty sets or dicts; when every nanosecond matters, this info might be relevant to you. Moving up a bit...:</p>
<pre><code>$ python -mtimeit -s'empty=range(7)' '23 in empty'
1000000 loops, best of 3: 0.318 usec per loop
$ python -mtimeit -s'empty=tuple(range(7))' '23 in empty'
1000000 loops, best of 3: 0.311 usec per loop
$ python -mtimeit -s'empty=set(range(7))' '23 in empty'
10000000 loops, best of 3: 0.109 usec per loop
$ python -mtimeit -s'empty=dict.fromkeys(range(7))' '23 in empty'
10000000 loops, best of 3: 0.0933 usec per loop
</code></pre>
<p>you see that for 7-items containers (not including the one of interest) the balance of performance has shifted, and now dicts and sets have the advantages by HUNDREDS of nanoseconds. When the item of interest IS present:</p>
<pre><code>$ python -mtimeit -s'empty=range(7)' '5 in empty'
1000000 loops, best of 3: 0.246 usec per loop
$ python -mtimeit -s'empty=tuple(range(7))' '5 in empty'
1000000 loops, best of 3: 0.25 usec per loop
$ python -mtimeit -s'empty=dict.fromkeys(range(7))' '5 in empty'
10000000 loops, best of 3: 0.0921 usec per loop
$ python -mtimeit -s'empty=set(range(7))' '5 in empty'
10000000 loops, best of 3: 0.112 usec per loop
</code></pre>
<p>dicts and sets don't gain much, but tuples and list do, even though dicts and set remain vastly faster.</p>
<p>And so on, and so forth -- <code>timeit</code> makes it trivially easy to run micro-benchmarks (strictly speaking, warranted only for those exceedingly rare situations where nanoseconds DO matter, but, easy enough to do, that it's no big hardship to check for OTHER cases;-).</p>
| 40 | 2009-09-14T01:27:52Z | [
"python",
"performance",
"data-structures",
"dictionary"
] |
Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...) | 1,418,825 | <p>Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., <code>__init__</code>, <code>__new__</code>, <code>__len__</code>, <code>__add__</code>)</p>
| 11 | 2009-09-13T21:02:02Z | 1,418,832 | <p>Please take a look at the <a href="http://docs.python.org/reference/datamodel.html#special-method-names">special method names section</a> in the Python language reference.</p>
| 31 | 2009-09-13T21:05:41Z | [
"python",
"class",
"methods",
"double-underscore"
] |
Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...) | 1,418,825 | <p>Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., <code>__init__</code>, <code>__new__</code>, <code>__len__</code>, <code>__add__</code>)</p>
| 11 | 2009-09-13T21:02:02Z | 1,418,834 | <p>Here is a <a href="http://www.ironpythoninaction.com/magic-methods.html">complete reference of all the Python magic methods</a>.</p>
| 5 | 2009-09-13T21:06:14Z | [
"python",
"class",
"methods",
"double-underscore"
] |
Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...) | 1,418,825 | <p>Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., <code>__init__</code>, <code>__new__</code>, <code>__len__</code>, <code>__add__</code>)</p>
| 11 | 2009-09-13T21:02:02Z | 1,418,844 | <p>Dive Into Python has <a href="http://web.archive.org/web/20110131211638/http://diveintopython3.org/special-method-names.html" rel="nofollow">an excellent appendix</a> for them.</p>
| 7 | 2009-09-13T21:11:25Z | [
"python",
"class",
"methods",
"double-underscore"
] |
Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...) | 1,418,825 | <p>Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., <code>__init__</code>, <code>__new__</code>, <code>__len__</code>, <code>__add__</code>)</p>
| 11 | 2009-09-13T21:02:02Z | 1,418,856 | <p>See <a href="http://rgruet.free.fr/PQR25/PQR2.5.html#SpecialMethods" rel="nofollow">Python Quick reference</a></p>
| 3 | 2009-09-13T21:16:10Z | [
"python",
"class",
"methods",
"double-underscore"
] |
Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...) | 1,418,825 | <p>Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., <code>__init__</code>, <code>__new__</code>, <code>__len__</code>, <code>__add__</code>)</p>
| 11 | 2009-09-13T21:02:02Z | 1,418,931 | <p>Familiarize yourself with the dir function.</p>
| 0 | 2009-09-13T21:49:58Z | [
"python",
"class",
"methods",
"double-underscore"
] |
Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...) | 1,418,825 | <p>Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., <code>__init__</code>, <code>__new__</code>, <code>__len__</code>, <code>__add__</code>)</p>
| 11 | 2009-09-13T21:02:02Z | 18,661,094 | <p>For somebody who is relatively new to Python, and for whom the documentation is often not quite accessible enough (like myself): somebody wrote a <a href="http://www.rafekettler.com/magicmethods.html" rel="nofollow">nice introduction</a> with lots of examples on how the special (magic) methods work, how to use them, etc.</p>
| 2 | 2013-09-06T15:16:59Z | [
"python",
"class",
"methods",
"double-underscore"
] |
Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...) | 1,418,825 | <p>Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., <code>__init__</code>, <code>__new__</code>, <code>__len__</code>, <code>__add__</code>)</p>
| 11 | 2009-09-13T21:02:02Z | 37,172,655 | <p>If, like me, you want a plain, unadorned list, here it is. I compiled it based on the <a href="https://docs.python.org/2/reference/datamodel.html#special-method-names" rel="nofollow">Python documentation link</a> from the accepted answer.</p>
<pre><code>__abs__
__add__
__and__
__call__
__class__
__cmp__
__coerce__
__complex__
__contains__
__del__
__delattr__
__delete__
__delitem__
__delslice__
__dict__
__div__
__divmod__
__eq__
__float__
__floordiv__
__ge__
__get__
__getattr__
__getattribute__
__getitem__
__getslice__
__gt__
__hash__
__hex__
__iadd__
__iand__
__idiv__
__ifloordiv__
__ilshift__
__imod__
__imul__
__index__
__init__
__instancecheck__
__int__
__invert__
__ior__
__ipow__
__irshift__
__isub__
__iter__
__itruediv__
__ixor__
__le__
__len__
__long__
__lshift__
__lt__
__metaclass__
__mod__
__mro__
__mul__
__ne__
__neg__
__new__
__nonzero__
__oct__
__or__
__pos__
__pow__
__radd__
__rand__
__rcmp__
__rdiv__
__rdivmod__
__repr__
__reversed__
__rfloordiv__
__rlshift__
__rmod__
__rmul__
__ror__
__rpow__
__rrshift__
__rshift__
__rsub__
__rtruediv__
__rxor__
__set__
__setattr__
__setitem__
__setslice__
__slots__
__str__
__sub__
__subclasscheck__
__truediv__
__unicode__
__weakref__
__xor__
</code></pre>
| 1 | 2016-05-11T20:26:07Z | [
"python",
"class",
"methods",
"double-underscore"
] |
Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...) | 1,418,825 | <p>Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., <code>__init__</code>, <code>__new__</code>, <code>__len__</code>, <code>__add__</code>)</p>
| 11 | 2009-09-13T21:02:02Z | 37,850,243 | <p>Do this if you prefer reading documentation from a CLI instead of the browser. </p>
<p><code>$ pydoc SPECIALMETHODS</code></p>
| 0 | 2016-06-16T05:03:20Z | [
"python",
"class",
"methods",
"double-underscore"
] |
Are Python list comprehensions the same thing as map/grep in Perl? | 1,418,912 | <p>I was having some trouble grokking the list comprehension syntax in Python, so I started thinking about how to achieve the same thing in Perl, which I'm more familiar with. I realized that the basic examples (taken from <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk">this page</a>) can all be done in Perl with <code>map</code> or <code>grep</code>.</p>
<p>E.g.</p>
<pre><code>(python) (perl)
S = [x**2 for x in range(10)] @S = map { $_**2 } ( 0..9 );
V = [2**i for i in range(13)] @V = map { 2**$_ } ( 0..12 );
M = [x for x in S if x % 2 == 0] @M = grep { $_ % 2 == 0 } @S;
</code></pre>
<p>So is "list comprehension" just a fancy term for "map and/or filter a list" or is there more to it?</p>
| 14 | 2009-09-13T21:41:58Z | 1,418,915 | <p>You are correct: a list comprehension is essentially just syntactic sugar for map and filter (terms from the functional programming world).</p>
<p>Hopefully this sample code demonstrates their equality:</p>
<pre><code>>>> # Python 2
>>> [x**2 for x in range(10)] == map(lambda x: x**2, range(10))
True
>>> [2**i for i in range(13)] == map(lambda x: 2**x, range(13))
True
>>> S = [x**2 for x in range(10)]
>>> [x for x in S if x % 2 == 0] == filter(lambda x: x % 2 == 0, S)
True
</code></pre>
<p>Note that this is only valid in Python 2.X, as SilentGhost pointed out in the comment. To make this compatible with Python 3, you'll have to wrap the calls to map or filter in the <code>list</code> constructor, because map and filter have been updated to return iterators, not lists.</p>
<pre><code>>>> # Python 3
>>> [x**2 for x in range(10)] == list(map(lambda x: x**2, range(10)))
True
>>> [2**i for i in range(13)] == list(map(lambda x: 2**x, range(13)))
True
>>> S = [x**2 for x in range(10)]
>>> [x for x in S if x % 2 == 0] == list(filter(lambda x: x % 2 == 0, S))
True
</code></pre>
| 13 | 2009-09-13T21:43:16Z | [
"python",
"perl",
"list"
] |
Are Python list comprehensions the same thing as map/grep in Perl? | 1,418,912 | <p>I was having some trouble grokking the list comprehension syntax in Python, so I started thinking about how to achieve the same thing in Perl, which I'm more familiar with. I realized that the basic examples (taken from <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk">this page</a>) can all be done in Perl with <code>map</code> or <code>grep</code>.</p>
<p>E.g.</p>
<pre><code>(python) (perl)
S = [x**2 for x in range(10)] @S = map { $_**2 } ( 0..9 );
V = [2**i for i in range(13)] @V = map { 2**$_ } ( 0..12 );
M = [x for x in S if x % 2 == 0] @M = grep { $_ % 2 == 0 } @S;
</code></pre>
<p>So is "list comprehension" just a fancy term for "map and/or filter a list" or is there more to it?</p>
| 14 | 2009-09-13T21:41:58Z | 1,418,925 | <p>List comprehensions are more powerful than map or filter as they allow you to abstractly play with lists.</p>
<p>It also more convenient to use them when your maps are further nested with more maps and filter calls.</p>
| 0 | 2009-09-13T21:46:46Z | [
"python",
"perl",
"list"
] |
Are Python list comprehensions the same thing as map/grep in Perl? | 1,418,912 | <p>I was having some trouble grokking the list comprehension syntax in Python, so I started thinking about how to achieve the same thing in Perl, which I'm more familiar with. I realized that the basic examples (taken from <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk">this page</a>) can all be done in Perl with <code>map</code> or <code>grep</code>.</p>
<p>E.g.</p>
<pre><code>(python) (perl)
S = [x**2 for x in range(10)] @S = map { $_**2 } ( 0..9 );
V = [2**i for i in range(13)] @V = map { 2**$_ } ( 0..12 );
M = [x for x in S if x % 2 == 0] @M = grep { $_ % 2 == 0 } @S;
</code></pre>
<p>So is "list comprehension" just a fancy term for "map and/or filter a list" or is there more to it?</p>
| 14 | 2009-09-13T21:41:58Z | 1,418,933 | <p>Yes, they are basically the same.</p>
<p>In fact Python also has a map function:</p>
<pre><code>S = map(lambda x: x**2, range(10))
</code></pre>
<p>is the same as your first examples above. However, the list comprehension syntax is strongly preferred in Python. I believe Guido has been quoted as saying he regrets introducing the functional syntax at all.</p>
<p>However, where it gets really interesting is in the next evolution of list comprehensions, which is generators. These allow you to return an iterator - rather than processing the whole list at once, it does a single iteration and then returns, so that you don't have to hold the whole list in memory at the same time. Very powerful.</p>
| 3 | 2009-09-13T21:50:10Z | [
"python",
"perl",
"list"
] |
Are Python list comprehensions the same thing as map/grep in Perl? | 1,418,912 | <p>I was having some trouble grokking the list comprehension syntax in Python, so I started thinking about how to achieve the same thing in Perl, which I'm more familiar with. I realized that the basic examples (taken from <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk">this page</a>) can all be done in Perl with <code>map</code> or <code>grep</code>.</p>
<p>E.g.</p>
<pre><code>(python) (perl)
S = [x**2 for x in range(10)] @S = map { $_**2 } ( 0..9 );
V = [2**i for i in range(13)] @V = map { 2**$_ } ( 0..12 );
M = [x for x in S if x % 2 == 0] @M = grep { $_ % 2 == 0 } @S;
</code></pre>
<p>So is "list comprehension" just a fancy term for "map and/or filter a list" or is there more to it?</p>
| 14 | 2009-09-13T21:41:58Z | 1,418,948 | <p>Yes. The power of the Python syntax is that the same syntax (within round rather than square brackets) is also used to define generators, which produce sequences of values on demand.</p>
| 0 | 2009-09-13T21:57:13Z | [
"python",
"perl",
"list"
] |
Are Python list comprehensions the same thing as map/grep in Perl? | 1,418,912 | <p>I was having some trouble grokking the list comprehension syntax in Python, so I started thinking about how to achieve the same thing in Perl, which I'm more familiar with. I realized that the basic examples (taken from <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk">this page</a>) can all be done in Perl with <code>map</code> or <code>grep</code>.</p>
<p>E.g.</p>
<pre><code>(python) (perl)
S = [x**2 for x in range(10)] @S = map { $_**2 } ( 0..9 );
V = [2**i for i in range(13)] @V = map { 2**$_ } ( 0..12 );
M = [x for x in S if x % 2 == 0] @M = grep { $_ % 2 == 0 } @S;
</code></pre>
<p>So is "list comprehension" just a fancy term for "map and/or filter a list" or is there more to it?</p>
| 14 | 2009-09-13T21:41:58Z | 1,419,002 | <p>They're the "pythonic" version for mapping and filtering sequences, but they allow to do some others things, like flattening a (fixed level) nested list, for example:</p>
<pre><code>[j for i in nested_list for j in i]
</code></pre>
<p>Another thing that you cannot do with a regular <em>map</em> and a lambda expression is to structurally decompose the iterating values, for example:</p>
<pre><code>[(x%y)*z for x,y,z in list_with_triplets_of_ints]
</code></pre>
<p>of course there are workarounds like:</p>
<pre><code>aux = lambda x,y,z: (x%y)*z
map(lambda t: aux(*t), list_with_triplets_of_ints)
</code></pre>
<p>but when the transformation you need to apply is already defined, then usually it's just simpler to use a map, like in:</p>
<pre><code>map(int, list_of_str_values)
</code></pre>
<p>rather than</p>
<pre><code>[int(i) for i in list_of_str_values]
</code></pre>
| 2 | 2009-09-13T22:18:41Z | [
"python",
"perl",
"list"
] |
Are Python list comprehensions the same thing as map/grep in Perl? | 1,418,912 | <p>I was having some trouble grokking the list comprehension syntax in Python, so I started thinking about how to achieve the same thing in Perl, which I'm more familiar with. I realized that the basic examples (taken from <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk">this page</a>) can all be done in Perl with <code>map</code> or <code>grep</code>.</p>
<p>E.g.</p>
<pre><code>(python) (perl)
S = [x**2 for x in range(10)] @S = map { $_**2 } ( 0..9 );
V = [2**i for i in range(13)] @V = map { 2**$_ } ( 0..12 );
M = [x for x in S if x % 2 == 0] @M = grep { $_ % 2 == 0 } @S;
</code></pre>
<p>So is "list comprehension" just a fancy term for "map and/or filter a list" or is there more to it?</p>
| 14 | 2009-09-13T21:41:58Z | 1,419,036 | <p>List comprehensions also flatten out things:</p>
<p>For example:</p>
<p>[(x, y) for x in xrange(10) if x%2 == 0 for y in xrange(20) if x!=y]</p>
<p>If you used nested maps here, you'd have to use concat (summing the lists) too.</p>
| 2 | 2009-09-13T22:46:25Z | [
"python",
"perl",
"list"
] |
What variable name do you use for file descriptors? | 1,419,039 | <p>A pretty silly trivial question. The canonical example is <code>f = open('filename')</code>, but</p>
<ul>
<li><code>f</code> is not very descriptive. After not looking at code in a while,
you can forget whether it means
"file" or "function f(x)" or "fourier
transform results" or something else. EIBTI.</li>
<li>In Python, <code>file</code> is already taken by a function.</li>
</ul>
<p>What else do you use?</p>
| 4 | 2009-09-13T22:48:42Z | 1,419,048 | <pre><code> data_file
settings_file
results_file
.... etc
</code></pre>
| 4 | 2009-09-13T22:55:08Z | [
"python",
"file",
"naming-conventions",
"explicit",
"variable-names"
] |
What variable name do you use for file descriptors? | 1,419,039 | <p>A pretty silly trivial question. The canonical example is <code>f = open('filename')</code>, but</p>
<ul>
<li><code>f</code> is not very descriptive. After not looking at code in a while,
you can forget whether it means
"file" or "function f(x)" or "fourier
transform results" or something else. EIBTI.</li>
<li>In Python, <code>file</code> is already taken by a function.</li>
</ul>
<p>What else do you use?</p>
| 4 | 2009-09-13T22:48:42Z | 1,419,050 | <p>generally I'll use "fp" for a short-lifetime file pointer.</p>
<p>for a longer-lived descriptor, I'll be more descriptive. "fpDebugLog", for example.</p>
| 1 | 2009-09-13T22:55:33Z | [
"python",
"file",
"naming-conventions",
"explicit",
"variable-names"
] |
What variable name do you use for file descriptors? | 1,419,039 | <p>A pretty silly trivial question. The canonical example is <code>f = open('filename')</code>, but</p>
<ul>
<li><code>f</code> is not very descriptive. After not looking at code in a while,
you can forget whether it means
"file" or "function f(x)" or "fourier
transform results" or something else. EIBTI.</li>
<li>In Python, <code>file</code> is already taken by a function.</li>
</ul>
<p>What else do you use?</p>
| 4 | 2009-09-13T22:48:42Z | 1,419,054 | <p>You can append it to the beginning, Hungarian-like "file_fft".</p>
<p>However, I would try to close file descriptors as soon as possible, and I recommend using the with statement like this so you don't have to worry about closing it, and it makes it easier to not lose track of it.</p>
<pre><code>with open("x.txt") as f:
data = f.read()
do something with data
</code></pre>
| 3 | 2009-09-13T22:56:23Z | [
"python",
"file",
"naming-conventions",
"explicit",
"variable-names"
] |
What variable name do you use for file descriptors? | 1,419,039 | <p>A pretty silly trivial question. The canonical example is <code>f = open('filename')</code>, but</p>
<ul>
<li><code>f</code> is not very descriptive. After not looking at code in a while,
you can forget whether it means
"file" or "function f(x)" or "fourier
transform results" or something else. EIBTI.</li>
<li>In Python, <code>file</code> is already taken by a function.</li>
</ul>
<p>What else do you use?</p>
| 4 | 2009-09-13T22:48:42Z | 1,419,303 | <p>I'm happy to use <code>f</code> (for either a function OR a file;-) if that identifier's scope is constrained to a pretty small compass (such as <code>with open('zap') as f:</code> would normally portend, say). In general, identifiers with large lexical scopes should be longer and more explicit, ones with lexically small/short scopes/lifespans can be shorter and less explicit, and this applies to open file object just about as much as to any other kind of object!-)</p>
| 3 | 2009-09-14T01:15:12Z | [
"python",
"file",
"naming-conventions",
"explicit",
"variable-names"
] |
What variable name do you use for file descriptors? | 1,419,039 | <p>A pretty silly trivial question. The canonical example is <code>f = open('filename')</code>, but</p>
<ul>
<li><code>f</code> is not very descriptive. After not looking at code in a while,
you can forget whether it means
"file" or "function f(x)" or "fourier
transform results" or something else. EIBTI.</li>
<li>In Python, <code>file</code> is already taken by a function.</li>
</ul>
<p>What else do you use?</p>
| 4 | 2009-09-13T22:48:42Z | 1,420,872 | <p>I rather use one of: <code>f, fp, fd</code>.</p>
<p>Sometimes <code>inf</code> / <code>outf</code> for input and output file.</p>
| -1 | 2009-09-14T10:56:30Z | [
"python",
"file",
"naming-conventions",
"explicit",
"variable-names"
] |
What variable name do you use for file descriptors? | 1,419,039 | <p>A pretty silly trivial question. The canonical example is <code>f = open('filename')</code>, but</p>
<ul>
<li><code>f</code> is not very descriptive. After not looking at code in a while,
you can forget whether it means
"file" or "function f(x)" or "fourier
transform results" or something else. EIBTI.</li>
<li>In Python, <code>file</code> is already taken by a function.</li>
</ul>
<p>What else do you use?</p>
| 4 | 2009-09-13T22:48:42Z | 1,420,921 | <p>Generally if the scope of a file object is only a few lines, <code>f</code> is perfectly readable - the variable name for the filename in the open call is probably descriptive enough. otherwise <code>something_file</code> is probably a good idea.</p>
| 1 | 2009-09-14T11:08:03Z | [
"python",
"file",
"naming-conventions",
"explicit",
"variable-names"
] |
Python normal arguments vs. keyword arguments | 1,419,046 | <p>How are "keyword arguments" different from regular arguments? Can't all arguments be passed as <code>name=value</code> instead of using positional syntax?</p>
| 115 | 2009-09-13T22:54:00Z | 1,419,098 | <p>There are two ways to assign argument values to function parameters, both are used.</p>
<ol>
<li><p>By Position. Positional arguments do not have keywords and are assigned first.</p></li>
<li><p>By Keyword. Keyword arguments have keywords and are assigned second, after positional arguments.</p></li>
</ol>
<p>Note that <em>you</em> have the option to use positional arguments.</p>
<p>If <em>you</em> don't use positional arguments, then -- yes -- everything <em>you</em> wrote turns out to be a keyword argument.</p>
<p>When <em>you</em> call a function you make a decision to use position or keyword or a mixture. You can choose to do all keywords if you want. Some of us do not make this choice and use positional arguments.</p>
| 17 | 2009-09-13T23:14:16Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] |
Python normal arguments vs. keyword arguments | 1,419,046 | <p>How are "keyword arguments" different from regular arguments? Can't all arguments be passed as <code>name=value</code> instead of using positional syntax?</p>
| 115 | 2009-09-13T22:54:00Z | 1,419,107 | <p>Using keyword arguments is the same thing as normal arguments except order doesn't matter. For example the two functions calls below are the same:</p>
<pre><code>def foo(bar, baz):
pass
foo(1, 2)
foo(baz=2, bar=1)
</code></pre>
| 44 | 2009-09-13T23:17:03Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] |
Python normal arguments vs. keyword arguments | 1,419,046 | <p>How are "keyword arguments" different from regular arguments? Can't all arguments be passed as <code>name=value</code> instead of using positional syntax?</p>
| 115 | 2009-09-13T22:54:00Z | 1,419,110 | <h1>Normal Arguments</h1>
<p>They have no keywords before them. The order is important!</p>
<pre><code>func(1,2,3, "foo")
</code></pre>
<h1>Keyword Arguments</h1>
<p>They have keywords in the front. They can be in any order!</p>
<pre><code>func(foo="bar", baz=5, hello=123)
func(baz=5, foo="bar", hello=123)
</code></pre>
<p>You should also know that if you use default arguments and neglect to insert the keywords, then the order will then matter!</p>
<pre><code>def func(foo=1, baz=2, hello=3): ...
func("bar", 5, 123)
</code></pre>
| 17 | 2009-09-13T23:17:40Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] |
Python normal arguments vs. keyword arguments | 1,419,046 | <p>How are "keyword arguments" different from regular arguments? Can't all arguments be passed as <code>name=value</code> instead of using positional syntax?</p>
| 115 | 2009-09-13T22:54:00Z | 1,419,149 | <p>I'm surprised no one has mentioned the fact that you can mix positional and keyword arguments to do sneaky things like this using <code>*args</code> and <code>**kwargs</code> (<a href="http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/">from this site</a>):</p>
<pre><code>def test_var_kwargs(farg, **kwargs):
print "formal arg:", farg
for key in kwargs:
print "another keyword arg: %s: %s" % (key, kwargs[key])
</code></pre>
<p>This allows you to use arbitrary keyword arguments that may have keys you don't want to define upfront.</p>
| 7 | 2009-09-13T23:52:00Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] |
Python normal arguments vs. keyword arguments | 1,419,046 | <p>How are "keyword arguments" different from regular arguments? Can't all arguments be passed as <code>name=value</code> instead of using positional syntax?</p>
| 115 | 2009-09-13T22:54:00Z | 1,419,159 | <p>There is one last language feature where the distinction is important. Consider the following function:</p>
<pre><code>def foo(*positional, **keywords):
print "Positional:", positional
print "Keywords:", keywords
</code></pre>
<p>The <code>*positional</code> argument will store all of the positional arguments passed to <code>foo()</code>, with no limit to how many you can provide.</p>
<pre><code>>>> foo('one', 'two', 'three')
Positional: ('one', 'two', 'three')
Keywords: {}
</code></pre>
<p>The <code>**keywords</code> argument will store any keyword arguments:</p>
<pre><code>>>> foo(a='one', b='two', c='three')
Positional: ()
Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}
</code></pre>
<p>And of course, you can use both at the same time:</p>
<pre><code>>>> foo('one','two',c='three',d='four')
Positional: ('one', 'two')
Keywords: {'c': 'three', 'd': 'four'}
</code></pre>
<p>These features are rarely used, but occasionally they are very useful, and it's important to know which arguments are positional or keywords.</p>
| 78 | 2009-09-13T23:58:17Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] |
Python normal arguments vs. keyword arguments | 1,419,046 | <p>How are "keyword arguments" different from regular arguments? Can't all arguments be passed as <code>name=value</code> instead of using positional syntax?</p>
| 115 | 2009-09-13T22:54:00Z | 1,419,160 | <p>there are two related concepts, both called "keyword arguments".</p>
<p>On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all.</p>
<p>The other concept is on the function definition side: You can define a function that takes parameters by name -- and you don't even have to specify what those names are. These are pure keyword arguments, and can't be passed positionally. The syntax is</p>
<pre><code>def my_function(arg1, arg2, **kwargs)
</code></pre>
<p>Any keyword arguments you pass into this function will be placed into a dictionary named kwargs. You can examine the keys of this dictionary at run-time, like this:</p>
<pre><code>def my_function(**kwargs):
print str(kwargs)
my_function(a=12, b="abc")
{'a': 12, 'b': 'abc'}
</code></pre>
| 142 | 2009-09-13T23:58:51Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] |
Python normal arguments vs. keyword arguments | 1,419,046 | <p>How are "keyword arguments" different from regular arguments? Can't all arguments be passed as <code>name=value</code> instead of using positional syntax?</p>
| 115 | 2009-09-13T22:54:00Z | 16,368,276 | <p>I'm surprised that no one seems to have pointed out that one can pass a dictionary of keyed argument parameters, that satisfy the formal parameters, like so.</p>
<pre><code>>>> def func(a='a', b='b', c='c', **kwargs):
... print 'a:%s, b:%s, c:%s' % (a, b, c)
...
>>> func()
a:a, b:b, c:c
>>> func(**{'a' : 'z', 'b':'q', 'c':'v'})
a:z, b:q, c:v
>>>
</code></pre>
| 10 | 2013-05-03T22:07:55Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] |
Python normal arguments vs. keyword arguments | 1,419,046 | <p>How are "keyword arguments" different from regular arguments? Can't all arguments be passed as <code>name=value</code> instead of using positional syntax?</p>
| 115 | 2009-09-13T22:54:00Z | 36,446,353 | <p>Using <strong>Python 3</strong> you can have both required and non-required keyword <a href="https://docs.python.org/3/reference/expressions.html#calls" rel="nofollow">arguments</a>:</p>
<p><strong>Optional</strong>: (default value defined for 'b')</p>
<pre><code>def func1(a, *, b=42):
...
func1(value_for_a) # b is optional and will default to 42
</code></pre>
<p><strong>Required</strong> (no default value defined for 'b'):</p>
<pre><code>def func2(a, *, b):
...
func2(value_for_a, b=21) # b is set to 21 by the function call
func2(value_for_a) # ERROR: missing 1 required keyword-only argument: 'b'`
</code></pre>
<p>This can help in cases where you have a many similar arguments next to each other especially when of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.</p>
| 1 | 2016-04-06T09:04:20Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] |
Python memory leaks? | 1,419,065 | <p>I am writing a python extension that seems to be leaking memory. I am trying to figure out the soure of the problem using valgrind. </p>
<p>However, it seems that python itself is leaking memory according to valgrind. Using the following simple script:</p>
<p><strong>hello.py</strong></p>
<pre><code> print "Hello World!"
</code></pre>
<p>and doing </p>
<pre><code>> valgrind --tool=memcheck python ./hello.py
(...)
==7937== ERROR SUMMARY: 580 errors from 34 contexts (suppressed: 21 from 1)
==7937== malloc/free: in use at exit: 721,878 bytes in 190 blocks.
==7937== malloc/free: 2,436 allocs, 2,246 frees, 1,863,631 bytes allocated.
==7937== For counts of detected errors, rerun with: -v
==7937== Use --track-origins=yes to see where uninitialised values come from
==7937== searching for pointers to 190 not-freed blocks.
==7937== checked 965,952 bytes.
==7937==
==7937== LEAK SUMMARY:
==7937== definitely lost: 0 bytes in 0 blocks.
==7937== possibly lost: 4,612 bytes in 13 blocks.
==7937== still reachable: 717,266 bytes in 177 blocks.
==7937== suppressed: 0 bytes in 0 blocks.
==7937== Rerun with --leak-check=full to see details of leaked memory.
</code></pre>
<p>Does anybody have an explanation for this strage behavior? Is the python interpreter really leaking memory?</p>
<p>What tool do python developers use to debug their memory leaks?</p>
| 7 | 2009-09-13T23:03:01Z | 1,419,083 | <p>The leak is most likely coming from your own extension, not from Python. Large systems often exit with memory still allocated, simply because it isn't worth it to explicitly free it if the process is about to end anyway.</p>
| 1 | 2009-09-13T23:09:53Z | [
"python",
"memory",
"memory-management",
"valgrind"
] |
Python memory leaks? | 1,419,065 | <p>I am writing a python extension that seems to be leaking memory. I am trying to figure out the soure of the problem using valgrind. </p>
<p>However, it seems that python itself is leaking memory according to valgrind. Using the following simple script:</p>
<p><strong>hello.py</strong></p>
<pre><code> print "Hello World!"
</code></pre>
<p>and doing </p>
<pre><code>> valgrind --tool=memcheck python ./hello.py
(...)
==7937== ERROR SUMMARY: 580 errors from 34 contexts (suppressed: 21 from 1)
==7937== malloc/free: in use at exit: 721,878 bytes in 190 blocks.
==7937== malloc/free: 2,436 allocs, 2,246 frees, 1,863,631 bytes allocated.
==7937== For counts of detected errors, rerun with: -v
==7937== Use --track-origins=yes to see where uninitialised values come from
==7937== searching for pointers to 190 not-freed blocks.
==7937== checked 965,952 bytes.
==7937==
==7937== LEAK SUMMARY:
==7937== definitely lost: 0 bytes in 0 blocks.
==7937== possibly lost: 4,612 bytes in 13 blocks.
==7937== still reachable: 717,266 bytes in 177 blocks.
==7937== suppressed: 0 bytes in 0 blocks.
==7937== Rerun with --leak-check=full to see details of leaked memory.
</code></pre>
<p>Does anybody have an explanation for this strage behavior? Is the python interpreter really leaking memory?</p>
<p>What tool do python developers use to debug their memory leaks?</p>
| 7 | 2009-09-13T23:03:01Z | 1,419,264 | <p>There's a whole README.valgrind in the Python sources that explains the various caveats trying to use Valgrind with Python:</p>
<p><a href="http://svn.python.org/projects/python/trunk/Misc/README.valgrind">http://svn.python.org/projects/python/trunk/Misc/README.valgrind</a></p>
<pre><code>Python uses its own small-object allocation scheme on top of malloc,
called PyMalloc.
Valgrind may show some unexpected results when PyMalloc is used.
Starting with Python 2.3, PyMalloc is used by default. You can disable
PyMalloc when configuring python by adding the --without-pymalloc option.
If you disable PyMalloc, most of the information in this document and
the supplied suppressions file will not be useful. As discussed above,
disabling PyMalloc can catch more problems.
If you use valgrind on a default build of Python, you will see
many errors like:
==6399== Use of uninitialised value of size 4
==6399== at 0x4A9BDE7E: PyObject_Free (obmalloc.c:711)
==6399== by 0x4A9B8198: dictresize (dictobject.c:477)
These are expected and not a problem.
</code></pre>
| 12 | 2009-09-14T01:01:03Z | [
"python",
"memory",
"memory-management",
"valgrind"
] |
In python, is there a "pass" equivalent for a variable assignment | 1,419,077 | <p>I am using a library function called get_count_and_price which returns a 2-tuple (count,price). In many places I use both time and price. However, in some I only need time or price. So right now, if I only need count, I assign to (count,price) and leave the price unused.</p>
<p>This works great and causes no trouble in and of itself.</p>
<p>However...</p>
<p>I use Eclipse with PyDev, and the new version 1.5 automatically shows errors and warnings. One of the warnings it shows is unused variables. In the above example, it flags price as unused. This is the sort of behavior which is great and I really appreciate PyDev doing this for me. However, I would like to skip the assignment to price altogether. Ideally, I would like something like:</p>
<pre><code>(count,None) = get_count_and_price()
</code></pre>
<p>Now as we all know, None cannot be assigned to. Is there something else I could do in this case? </p>
<p>I know I could do something like </p>
<pre><code>count = get_count_and_price()[0]
</code></pre>
<p>but I am asking just to see if anyone has any better suggestions.</p>
| 25 | 2009-09-13T23:08:25Z | 1,419,082 | <p>I think there's nothing wrong with using the [0] subscript, but sometimes people use the "throwaway" variable _. It's actually just like any other variable (with special usage in the console), except that some Python users decided to have it be "throwaway" as a convention.</p>
<pre><code>count, _ = get_count_and_price()
</code></pre>
<p>About the PyDev problem, you should just use the [0] subscript anyway. But if you really want to use _ the only solution is to disable the unused variable warnings if that bothers you.</p>
| 28 | 2009-09-13T23:09:51Z | [
"python",
"core"
] |
In python, is there a "pass" equivalent for a variable assignment | 1,419,077 | <p>I am using a library function called get_count_and_price which returns a 2-tuple (count,price). In many places I use both time and price. However, in some I only need time or price. So right now, if I only need count, I assign to (count,price) and leave the price unused.</p>
<p>This works great and causes no trouble in and of itself.</p>
<p>However...</p>
<p>I use Eclipse with PyDev, and the new version 1.5 automatically shows errors and warnings. One of the warnings it shows is unused variables. In the above example, it flags price as unused. This is the sort of behavior which is great and I really appreciate PyDev doing this for me. However, I would like to skip the assignment to price altogether. Ideally, I would like something like:</p>
<pre><code>(count,None) = get_count_and_price()
</code></pre>
<p>Now as we all know, None cannot be assigned to. Is there something else I could do in this case? </p>
<p>I know I could do something like </p>
<pre><code>count = get_count_and_price()[0]
</code></pre>
<p>but I am asking just to see if anyone has any better suggestions.</p>
| 25 | 2009-09-13T23:08:25Z | 1,419,085 | <p>We often do this.</p>
<pre><code>count, _ = get_count_and_price()
</code></pre>
<p>or this</p>
<pre><code>count, junk = get_count_and_price()
</code></pre>
| 3 | 2009-09-13T23:10:12Z | [
"python",
"core"
] |
In python, is there a "pass" equivalent for a variable assignment | 1,419,077 | <p>I am using a library function called get_count_and_price which returns a 2-tuple (count,price). In many places I use both time and price. However, in some I only need time or price. So right now, if I only need count, I assign to (count,price) and leave the price unused.</p>
<p>This works great and causes no trouble in and of itself.</p>
<p>However...</p>
<p>I use Eclipse with PyDev, and the new version 1.5 automatically shows errors and warnings. One of the warnings it shows is unused variables. In the above example, it flags price as unused. This is the sort of behavior which is great and I really appreciate PyDev doing this for me. However, I would like to skip the assignment to price altogether. Ideally, I would like something like:</p>
<pre><code>(count,None) = get_count_and_price()
</code></pre>
<p>Now as we all know, None cannot be assigned to. Is there something else I could do in this case? </p>
<p>I know I could do something like </p>
<pre><code>count = get_count_and_price()[0]
</code></pre>
<p>but I am asking just to see if anyone has any better suggestions.</p>
| 25 | 2009-09-13T23:08:25Z | 1,419,093 | <p>If you go to the Eclipse -> Preferences⦠window, you can actually specify which variable names PyDev should ignore if they're unused (I'm looking at the newest PyDev 1.5.X).</p>
<p>If you go to PyDev -> Editor -> Code Analysis and look at the last field that says "Don't report unused variable if name starts with"</p>
<p>Enter whatever names you want in there and then use that name to restrict what variable names PyDev will ignore unused warnings for. </p>
<p>By default, it looks like PyDev will hide unused variable warnings for any variables that have names beginning with "dummy", "_", or "unused".</p>
<p>As @TokenMacGuy said below, I'd recommend against using just "_" because it has special meaning in certain scenarios in Python (specifically it's used in the interactive interpreter).</p>
| 7 | 2009-09-13T23:12:10Z | [
"python",
"core"
] |
In python, is there a "pass" equivalent for a variable assignment | 1,419,077 | <p>I am using a library function called get_count_and_price which returns a 2-tuple (count,price). In many places I use both time and price. However, in some I only need time or price. So right now, if I only need count, I assign to (count,price) and leave the price unused.</p>
<p>This works great and causes no trouble in and of itself.</p>
<p>However...</p>
<p>I use Eclipse with PyDev, and the new version 1.5 automatically shows errors and warnings. One of the warnings it shows is unused variables. In the above example, it flags price as unused. This is the sort of behavior which is great and I really appreciate PyDev doing this for me. However, I would like to skip the assignment to price altogether. Ideally, I would like something like:</p>
<pre><code>(count,None) = get_count_and_price()
</code></pre>
<p>Now as we all know, None cannot be assigned to. Is there something else I could do in this case? </p>
<p>I know I could do something like </p>
<pre><code>count = get_count_and_price()[0]
</code></pre>
<p>but I am asking just to see if anyone has any better suggestions.</p>
| 25 | 2009-09-13T23:08:25Z | 1,419,265 | <p>Using <code>_</code> as severally proposed may have some issues (though it's mostly OK). By the Python style guidelines we use at work I'd normally use <code>count, unused_price = ...</code> since pylint is configured to ignore assignments to barenames starting with <code>unused_</code> (and warn on USE of any such barename instead!-). But I don't know how to instruct <code>PyDev</code> to behave that way!</p>
| 20 | 2009-09-14T01:01:15Z | [
"python",
"core"
] |
In python, is there a "pass" equivalent for a variable assignment | 1,419,077 | <p>I am using a library function called get_count_and_price which returns a 2-tuple (count,price). In many places I use both time and price. However, in some I only need time or price. So right now, if I only need count, I assign to (count,price) and leave the price unused.</p>
<p>This works great and causes no trouble in and of itself.</p>
<p>However...</p>
<p>I use Eclipse with PyDev, and the new version 1.5 automatically shows errors and warnings. One of the warnings it shows is unused variables. In the above example, it flags price as unused. This is the sort of behavior which is great and I really appreciate PyDev doing this for me. However, I would like to skip the assignment to price altogether. Ideally, I would like something like:</p>
<pre><code>(count,None) = get_count_and_price()
</code></pre>
<p>Now as we all know, None cannot be assigned to. Is there something else I could do in this case? </p>
<p>I know I could do something like </p>
<pre><code>count = get_count_and_price()[0]
</code></pre>
<p>but I am asking just to see if anyone has any better suggestions.</p>
| 25 | 2009-09-13T23:08:25Z | 8,697,239 | <p>I'd rather name it <code>_price</code> instead, for these reasons:</p>
<ul>
<li><p>It solves the conflict with gettext and the interactive prompt, which both use <code>_</code></p></li>
<li><p>It's easy to change back into <code>price</code> if you end up needing it later.</p></li>
<li><p>As others have pointed out, the leading underscore already has a connotation of "internal" or "unused" in many languages.</p></li>
</ul>
<p>So your code would end up looking like this:</p>
<pre><code>(count, _price) = get_count_and_price()
</code></pre>
| 2 | 2012-01-02T03:46:23Z | [
"python",
"core"
] |
In python, is there a "pass" equivalent for a variable assignment | 1,419,077 | <p>I am using a library function called get_count_and_price which returns a 2-tuple (count,price). In many places I use both time and price. However, in some I only need time or price. So right now, if I only need count, I assign to (count,price) and leave the price unused.</p>
<p>This works great and causes no trouble in and of itself.</p>
<p>However...</p>
<p>I use Eclipse with PyDev, and the new version 1.5 automatically shows errors and warnings. One of the warnings it shows is unused variables. In the above example, it flags price as unused. This is the sort of behavior which is great and I really appreciate PyDev doing this for me. However, I would like to skip the assignment to price altogether. Ideally, I would like something like:</p>
<pre><code>(count,None) = get_count_and_price()
</code></pre>
<p>Now as we all know, None cannot be assigned to. Is there something else I could do in this case? </p>
<p>I know I could do something like </p>
<pre><code>count = get_count_and_price()[0]
</code></pre>
<p>but I am asking just to see if anyone has any better suggestions.</p>
| 25 | 2009-09-13T23:08:25Z | 11,372,836 | <p>I'll go after a Necromancer badge. :)</p>
<p>You said you're using PyDev. In PyDev (at least recent versions - I didn't check how far back), any variable name that starts with "unused" will be exempt from the Unused Variable warning. Other static analysis tool may still complain, though (pyflakes does - but it seems to ignore this warning in a tuple-unpacking context anyway).</p>
| 1 | 2012-07-07T06:30:11Z | [
"python",
"core"
] |
Cannot import file in Python/Django | 1,419,224 | <p>I'm not sure what's going on, but on my own laptop, everything works okay. When I upload to my host with Python 2.3.5, my views.py can't find anything in my models.py. I have:</p>
<pre><code>from dtms.models import User
from dtms.item_list import *
</code></pre>
<p>where my models, item_list, and views files are in /mysite/dtms/</p>
<p>It ends up telling me it can't find User. Any ideas?</p>
<p>Also, when I use the django shell, I can do "from dtms.models import *" and it works just fine.</p>
<p>Okay, after doing the suggestion below, I get a log file of:</p>
<pre><code>syspath = ['/home/victor/django/django_projects', '/home/victor/django/django_projects/mysite']
DEBUG:root:something <module 'dtms' from '/home/victor/django/django_projects/mysite/dtms/__init__.pyc'>
DEBUG:root:/home/victor/django/django_projects/mysite/dtms/__init__.pyc
DEBUG:root:['/home/victor/django/django_projects/mysite/dtms']
</code></pre>
<p>I'm not entirely sure what this means - my file is in mysite/dtms/item_list.py. Does this mean it's being loaded? I see the dtms module is being loaded, but it still can't find dtms.models</p>
| 0 | 2009-09-14T00:34:57Z | 1,419,228 | <p>Make sure your project (or the folder above your "dtms" app) is in python's <a href="http://docs.python.org/tutorial/modules.html#the-module-search-path" rel="nofollow">module search path</a>.</p>
<p>This is something you may need to set in your web server's configuration. The reason it works in the django shell is probably because you are in your project's folder when you run the shell.</p>
<p>This is explained <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/" rel="nofollow">here</a> if you're using apache with mod_python.</p>
| 0 | 2009-09-14T00:37:52Z | [
"python",
"django"
] |
Cannot import file in Python/Django | 1,419,224 | <p>I'm not sure what's going on, but on my own laptop, everything works okay. When I upload to my host with Python 2.3.5, my views.py can't find anything in my models.py. I have:</p>
<pre><code>from dtms.models import User
from dtms.item_list import *
</code></pre>
<p>where my models, item_list, and views files are in /mysite/dtms/</p>
<p>It ends up telling me it can't find User. Any ideas?</p>
<p>Also, when I use the django shell, I can do "from dtms.models import *" and it works just fine.</p>
<p>Okay, after doing the suggestion below, I get a log file of:</p>
<pre><code>syspath = ['/home/victor/django/django_projects', '/home/victor/django/django_projects/mysite']
DEBUG:root:something <module 'dtms' from '/home/victor/django/django_projects/mysite/dtms/__init__.pyc'>
DEBUG:root:/home/victor/django/django_projects/mysite/dtms/__init__.pyc
DEBUG:root:['/home/victor/django/django_projects/mysite/dtms']
</code></pre>
<p>I'm not entirely sure what this means - my file is in mysite/dtms/item_list.py. Does this mean it's being loaded? I see the dtms module is being loaded, but it still can't find dtms.models</p>
| 0 | 2009-09-14T00:34:57Z | 1,419,281 | <p>The fact that <code>from X import *</code> works does not guarantee that <code>from X import Wowie</code> will work too, you know (if you could wean yourself away from that <code>import *</code> addiction you'd be WAY happier on the long run, but, that's another issue;-).</p>
<p>My general advice in import problems is to bracket the problematic import with try/except:</p>
<pre><code>try:
from blah import bluh
except ImportError, e:
import sys
print 'Import error:', e
print 'sys.path:', sys.path
blah = __import__('blah')
print 'blah is %r' % blah
try:
print 'blah is at %s (%s)' % (blah.__file__, blah.__path__)
except Exception, e:
print 'Cannot give details on blah (%s)' % e
</code></pre>
<p>and the like. That generally shows you pretty quickly that your sys.path isn't what you thought it would be, and/or blah is at some weird place or with weird path, and the like.</p>
| 4 | 2009-09-14T01:07:53Z | [
"python",
"django"
] |
Cannot import file in Python/Django | 1,419,224 | <p>I'm not sure what's going on, but on my own laptop, everything works okay. When I upload to my host with Python 2.3.5, my views.py can't find anything in my models.py. I have:</p>
<pre><code>from dtms.models import User
from dtms.item_list import *
</code></pre>
<p>where my models, item_list, and views files are in /mysite/dtms/</p>
<p>It ends up telling me it can't find User. Any ideas?</p>
<p>Also, when I use the django shell, I can do "from dtms.models import *" and it works just fine.</p>
<p>Okay, after doing the suggestion below, I get a log file of:</p>
<pre><code>syspath = ['/home/victor/django/django_projects', '/home/victor/django/django_projects/mysite']
DEBUG:root:something <module 'dtms' from '/home/victor/django/django_projects/mysite/dtms/__init__.pyc'>
DEBUG:root:/home/victor/django/django_projects/mysite/dtms/__init__.pyc
DEBUG:root:['/home/victor/django/django_projects/mysite/dtms']
</code></pre>
<p>I'm not entirely sure what this means - my file is in mysite/dtms/item_list.py. Does this mean it's being loaded? I see the dtms module is being loaded, but it still can't find dtms.models</p>
| 0 | 2009-09-14T00:34:57Z | 1,419,726 | <p>I could be way off with this, but did you set the DJANGO_SETTINGS_MODULE environment variable yet? It affects what you can import. Set it to ".settings". It's also something that gets set when you fire up manage.py, so things work there that won't work in other situations with setting the variable beforehand.</p>
<p>Here's what I do on my system:</p>
<pre><code>export DJANGO_SETTINGS_MODULE=<project name>.settings
</code></pre>
<p>or</p>
<pre><code>import os
os.environ['DJANGO_SETTINGS_MODULE']='<project name>.settings'
</code></pre>
<p>Sorry if this misses the point, but when I hear of problems importing models.py, I immediately thing of environment variables. Also, the project directory has to be on PYTHONPATH, but you probably already know that.</p>
| 0 | 2009-09-14T04:51:41Z | [
"python",
"django"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.