title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
How would one log into a phpBB3 forum through a Python script using urllib, urllib2 and ClientCookie? | 112,768 | <p>(ClientCookie is a module for (automatic) cookie-handling: <a href="http://wwwsearch.sourceforge.net/ClientCookie" rel="nofollow">http://wwwsearch.sourceforge.net/ClientCookie</a>)</p>
<pre><code># I encode the data I'll be sending:
data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'})
# And I send it and read the page:
page = ClientCookie.urlopen('http://www.forum.com/ucp.php?mode=login', data)
output = page.read()
</code></pre>
<p>The script doesn't log in, but rather seems to get redirected back to the same login page asking it for a username and password. What am I doing wrong?</p>
<p>Any help would be greatly appreciated! Thanks!</p>
| 2 | 2008-09-22T01:28:57Z | 112,819 | <p>Have you tried fetching the login page first?</p>
<p>I would suggest using <a href="https://addons.mozilla.org/en-US/firefox/addon/966" rel="nofollow">Tamper Data</a> to have a peek at exactly what's being sent when you request the login page and then log in normally using a web browser from a fresh start, with no initial cookies in place, so that your script can replicate it exactly.</p>
<p>That's the approach I used when writing the following, extracted from a script which needs to login to an Invision Power Board forum, using cookielib and urllib2 - you may find it useful as a reference.</p>
<pre><code>import cookielib
import logging
import sys
import urllib
import urllib2
cookies = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
urllib2.install_opener(opener)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',
'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'Accept-Language': 'en-gb,en;q=0.5',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
}
# Fetch the login page to set initial cookies
urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=00', None, headers))
# Login so we can access the Off Topic forum
login_headers = headers.copy()
login_headers.update({
'Referer': 'http://www.rllmukforum.com/index.php?act=Login&CODE=00',
'Content-Type': 'application/x-www-form-urlencoded',
})
html = urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=01',
urllib.urlencode({
'referer': 'http://www.rllmukforum.com/index.php?',
'UserName': RLLMUK_USERNAME,
'PassWord': RLLMUK_PASSWORD,
}),
login_headers)).read()
if 'The following errors were found' in html:
logging.error('RLLMUK login failed')
logging.info(html)
sys.exit(1)
</code></pre>
| 2 | 2008-09-22T01:54:20Z | [
"python",
"post",
"urllib"
] |
How would one log into a phpBB3 forum through a Python script using urllib, urllib2 and ClientCookie? | 112,768 | <p>(ClientCookie is a module for (automatic) cookie-handling: <a href="http://wwwsearch.sourceforge.net/ClientCookie" rel="nofollow">http://wwwsearch.sourceforge.net/ClientCookie</a>)</p>
<pre><code># I encode the data I'll be sending:
data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'})
# And I send it and read the page:
page = ClientCookie.urlopen('http://www.forum.com/ucp.php?mode=login', data)
output = page.read()
</code></pre>
<p>The script doesn't log in, but rather seems to get redirected back to the same login page asking it for a username and password. What am I doing wrong?</p>
<p>Any help would be greatly appreciated! Thanks!</p>
| 2 | 2008-09-22T01:28:57Z | 112,895 | <p>I'd recommend taking a look at the <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> library; it's designed for precisely this type of task. It's also far easier than doing it by hand.</p>
| 1 | 2008-09-22T02:33:43Z | [
"python",
"post",
"urllib"
] |
Python - When to use file vs open | 112,970 | <p>What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)</p>
| 119 | 2008-09-22T03:04:14Z | 112,980 | <p>You should always use <code>open()</code>.</p>
<p>As the <a href="http://docs.python.org/2/library/functions.html#file" rel="nofollow" title="BuiltinFuncs Doc">documentation</a> states:</p>
<blockquote>
<p>When opening a file, it's preferable
to use open() instead of invoking this
constructor directly. file is more
suited to type testing (for example,
writing "isinstance(f, file)").</p>
</blockquote>
<p>Also, <code>file()</code> <a href="http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins" rel="nofollow">has been removed</a> since Python 3.0.</p>
| 129 | 2008-09-22T03:07:44Z | [
"python",
"file"
] |
Python - When to use file vs open | 112,970 | <p>What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)</p>
| 119 | 2008-09-22T03:04:14Z | 112,982 | <p>Functionally, the two are the same; <code>open</code> will call <code>file</code> anyway, so currently the difference is a matter of style. The <a href="http://docs.python.org/lib/built-in-funcs.html" rel="nofollow">Python docs</a> recommend using <code>open</code>. </p>
<blockquote>
<p>When opening a file, it's preferable to use open() instead of invoking the file constructor directly. </p>
</blockquote>
<p>The reason is that in future versions they is not guaranteed to be the same (<code>open</code> will become a factory function, which returns objects of different types depending on the path it's opening).</p>
| 4 | 2008-09-22T03:08:37Z | [
"python",
"file"
] |
Python - When to use file vs open | 112,970 | <p>What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)</p>
| 119 | 2008-09-22T03:04:14Z | 112,989 | <p>Two reasons: The python philosophy of "There ought to be one way to do it" and <code>file</code> is going away.</p>
<p><code>file</code> is the actual type (using e.g. <code>file('myfile.txt')</code> is calling its constructor). <code>open</code> is a factory function that will return a file object.</p>
<p>In python 3.0 <code>file</code> is going to move from being a built-in to being implemented by multiple classes in the <code>io</code> library (somewhat similar to Java with buffered readers, etc.)</p>
| 28 | 2008-09-22T03:10:16Z | [
"python",
"file"
] |
Python - When to use file vs open | 112,970 | <p>What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)</p>
| 119 | 2008-09-22T03:04:14Z | 112,990 | <p>Only ever use open() for opening files. file() is actually being removed in 3.0, and it's deprecated at the moment. They've had a sort of strange relationship, but file() is going now, so there's no need to worry anymore.</p>
<p>The following is from the Python 2.6 docs. [bracket stuff] added by me.</p>
<blockquote>
<p>When opening a file, itâs preferable to use open() instead of invoking this [file()] constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)</p>
</blockquote>
| 3 | 2008-09-22T03:10:45Z | [
"python",
"file"
] |
Python - When to use file vs open | 112,970 | <p>What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)</p>
| 119 | 2008-09-22T03:04:14Z | 112,993 | <p>According to Mr Van Rossum, although open() is currently an alias for file() you should use open() because this might change in the future.</p>
| 1 | 2008-09-22T03:12:27Z | [
"python",
"file"
] |
Python - When to use file vs open | 112,970 | <p>What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)</p>
| 119 | 2008-09-22T03:04:14Z | 113,050 | <p><code>file()</code> is a type, like an int or a list. <code>open()</code> is a function for opening files, and will return a <code>file</code> object.</p>
<p>This is an example of when you should use open:</p>
<pre><code>f = open(filename, 'r')
for line in f:
process(line)
f.close()
</code></pre>
<p>This is an example of when you should use file:</p>
<pre><code>class LoggingFile(file):
def write(self, data):
sys.stderr.write("Wrote %d bytes\n" % len(data))
super(LoggingFile, self).write(data)
</code></pre>
<p>As you can see, there's a good reason for both to exist, and a clear use-case for both.</p>
| 16 | 2008-09-22T03:32:08Z | [
"python",
"file"
] |
Writing to the windows logs in Python | 113,007 | <p>Is it possible to write to the windows logs in python?</p>
| 9 | 2008-09-22T03:15:31Z | 113,011 | <p>Yes, just use Windows Python Extension, as stated <a href="http://www.ravenbrook.com/project/p4dti/master/design/win32-eventlog/">here</a>.</p>
<pre><code>import win32evtlogutil
win32evtlogutil.ReportEvent(ApplicationName, EventID, EventCategory,
EventType, Inserts, Data, SID)
</code></pre>
| 12 | 2008-09-22T03:16:58Z | [
"python",
"windows",
"logging"
] |
What are the Python equivalents of the sighold and sigrelse functions found in C? | 113,170 | <p>It appears the Python signal module doesn't have anything similar to the sighold and sigrelse functions found in C, using signal.h. Are there Python equivalents of <em>any</em> sort?</p>
<p>Many thanks!</p>
| 3 | 2008-09-22T04:25:22Z | 113,201 | <p>There is no way to ``block'' signals temporarily from critical sections (since this is not supported by all Unix flavors).</p>
<p><a href="https://docs.python.org/library/signal.html" rel="nofollow">https://docs.python.org/library/signal.html</a></p>
| 2 | 2008-09-22T04:36:29Z | [
"python",
"signals"
] |
What are the Python equivalents of the sighold and sigrelse functions found in C? | 113,170 | <p>It appears the Python signal module doesn't have anything similar to the sighold and sigrelse functions found in C, using signal.h. Are there Python equivalents of <em>any</em> sort?</p>
<p>Many thanks!</p>
| 3 | 2008-09-22T04:25:22Z | 113,219 | <p>There are no direct bindings for this in Python. Accessing them through ctypes is easy enough; here is an example.</p>
<pre><code>import ctypes, signal
libc = ctypes.cdll.LoadLibrary("libc.so.6")
libc.sighold(signal.SIGKILL)
libc.sigrelse(signal.SIGKILL)
</code></pre>
<p>I'm not familiar with the use of these calls, but be aware that Python's signal handlers work differently than C. When Python code is attached to a signal callback, the signal is caught on the C side of the interpreter and queued. The interpreter is occasionally interrupted for internal housekeeping (and thread switching, etc). It is during that interrupt the Python handler for the signal will be called.</p>
<p>All that to say, just be aware that Python's signal handling is a little less asynchronous than normal C signal handlers.</p>
| 2 | 2008-09-22T04:47:24Z | [
"python",
"signals"
] |
How do I use owfs to read an iButton temperature logger? | 113,185 | <p>I've installed <a href="http://www.owfs.org/" rel="nofollow"><code>owfs</code></a> and am trying to read the data off a <a href="http://www.maxim-ic.com/quick_view2.cfm/qv_pk/4088" rel="nofollow">iButton temperature logger</a>.</p>
<p><code>owfs</code> lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get individual readings by <code>cat</code>ting the files, e.g. <code>cat onewire/{deviceid}/log/temperature.1</code>, but the <code>onewire/{deviceid}/log/temperature.ALL</code> file is "broken" (possible too large, as <code>histogram/temperature.ALL</code> work fine). </p>
<p>A python script to read all files seems to work but takes a very long time. Is there a better way to do it? Does anyone have any examples?</p>
<p>I'm using Ubuntu 8.04 and couldn't get the java "one wire viewer" app to run.</p>
<p><strong>Update</strong>: Using <a href="http://owfs.sourceforge.net/owpython.html" rel="nofollow"><code>owpython</code></a> (installed with owfs), I can get the current temperature but can't figure out how to get access to the recorded logs:</p>
<pre><code>>>> import ow
>>> ow.init("u") # initialize USB
>>> ow.Sensor("/").sensorList()
[Sensor("/81.7FD921000000"), Sensor("/21.C4B912000000")]
>>> x = ow.Sensor("/21.C4B912000000")
>>> print x.type, x.temperature
DS1921 22
</code></pre>
<p><code>x.log</code> gives an <code>AttributeError</code>.</p>
| 9 | 2008-09-22T04:30:19Z | 117,532 | <p>I don't think there is a clever way. owpython doesn't support that telling from the API documentation. I guess <code>/proc</code> is your safest bet. Maybe have a look at the source of the owpython module and check if you can find out how it works.</p>
| 2 | 2008-09-22T20:47:15Z | [
"python",
"ubuntu",
"1wire"
] |
How do I use owfs to read an iButton temperature logger? | 113,185 | <p>I've installed <a href="http://www.owfs.org/" rel="nofollow"><code>owfs</code></a> and am trying to read the data off a <a href="http://www.maxim-ic.com/quick_view2.cfm/qv_pk/4088" rel="nofollow">iButton temperature logger</a>.</p>
<p><code>owfs</code> lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get individual readings by <code>cat</code>ting the files, e.g. <code>cat onewire/{deviceid}/log/temperature.1</code>, but the <code>onewire/{deviceid}/log/temperature.ALL</code> file is "broken" (possible too large, as <code>histogram/temperature.ALL</code> work fine). </p>
<p>A python script to read all files seems to work but takes a very long time. Is there a better way to do it? Does anyone have any examples?</p>
<p>I'm using Ubuntu 8.04 and couldn't get the java "one wire viewer" app to run.</p>
<p><strong>Update</strong>: Using <a href="http://owfs.sourceforge.net/owpython.html" rel="nofollow"><code>owpython</code></a> (installed with owfs), I can get the current temperature but can't figure out how to get access to the recorded logs:</p>
<pre><code>>>> import ow
>>> ow.init("u") # initialize USB
>>> ow.Sensor("/").sensorList()
[Sensor("/81.7FD921000000"), Sensor("/21.C4B912000000")]
>>> x = ow.Sensor("/21.C4B912000000")
>>> print x.type, x.temperature
DS1921 22
</code></pre>
<p><code>x.log</code> gives an <code>AttributeError</code>.</p>
| 9 | 2008-09-22T04:30:19Z | 181,511 | <p>I've also had problems with owfs. I found it to be an overengineered solution to what is a simple problem. Now I'm using the <a href="http://www.digitemp.com/" rel="nofollow">DigiTemp</a> code without a problem. I found it to be flexible and reliable. For instance, I store the room's temperature in a log file every minute by running</p>
<pre><code>/usr/local/bin/digitemp_DS9097U -c /usr/local/etc/digitemp.conf \
-q -t0 -n0 -d60 -l/var/log/temperature
</code></pre>
<p>To reach that point I downloaded the source file, untarred it and then did the following.</p>
<pre><code># Compile the hardware-specific command
make ds9097u
# Initialize the configuration file
./digitemp_DS9097U -s/dev/ttyS0 -i
# Run command to obtain temperature, and verify your setup
./digitemp_DS9097U -a
# Copy the configuration file to an accessible place
cp .digitemprc /usr/local/etc/digitemp.conf
</code></pre>
<p>I also hand-edited my configuration file to adjust it to my setup. This is how it ended-up.</p>
<pre><code>TTY /dev/ttyS0
READ_TIME 1000
LOG_TYPE 1
LOG_FORMAT "%b %d %H:%M:%S Sensor %s C: %.2C F: %.2F"
CNT_FORMAT "%b %d %H:%M:%S Sensor %s #%n %C"
HUM_FORMAT "%b %d %H:%M:%S Sensor %s C: %.2C F: %.2F H: %h%%"
SENSORS 1
ROM 0 0x10 0xD3 0x5B 0x07 0x00 0x00 0x00 0x05
</code></pre>
<p>In my case I also created a /etc/init.d/digitemp file and enabled it to run at startup.</p>
<pre><code>#! /bin/sh
#
# System startup script for the temperature monitoring daemon
#
### BEGIN INIT INFO
# Provides: digitemp
# Required-Start:
# Should-Start:
# Required-Stop:
# Should-Stop:
# Default-Start: 2 3 5
# Default-Stop: 0 1 6
# Description: Start the temperature monitoring daemon
### END INIT INFO
DIGITEMP=/usr/local/bin/digitemp_DS9097U
test -x $DIGITEMP || exit 5
DIGITEMP_CONFIG=/root/digitemp.conf
test -f $DIGITEMP_CONFIG || exit 6
DIGITEMP_LOGFILE=/var/log/temperature
# Source SuSE config
. /etc/rc.status
rc_reset
case "$1" in
start)
echo -n "Starting temperature monitoring daemon"
startproc $DIGITEMP -c $DIGITEMP_CONFIG -q -t0 -n0 -d60 -l$DIGITEMP_LOGFILE
rc_status -v
;;
stop)
echo -n "Shutting down temperature monitoring daemon"
killproc -TERM $DIGITEMP
rc_status -v
;;
try-restart)
$0 status >/dev/null && $0 restart
rc_status
;;
restart)
$0 stop
$0 start
rc_status
;;
force-reload)
$0 try-restart
rc_status
;;
reload)
$0 try-restart
rc_status
;;
status)
echo -n "Checking for temperature monitoring service"
checkproc $DIGITEMP
rc_status -v
;;
*)
echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload}"
exit 1
;;
esac
rc_exit
</code></pre>
| 2 | 2008-10-08T06:07:29Z | [
"python",
"ubuntu",
"1wire"
] |
How do I use owfs to read an iButton temperature logger? | 113,185 | <p>I've installed <a href="http://www.owfs.org/" rel="nofollow"><code>owfs</code></a> and am trying to read the data off a <a href="http://www.maxim-ic.com/quick_view2.cfm/qv_pk/4088" rel="nofollow">iButton temperature logger</a>.</p>
<p><code>owfs</code> lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get individual readings by <code>cat</code>ting the files, e.g. <code>cat onewire/{deviceid}/log/temperature.1</code>, but the <code>onewire/{deviceid}/log/temperature.ALL</code> file is "broken" (possible too large, as <code>histogram/temperature.ALL</code> work fine). </p>
<p>A python script to read all files seems to work but takes a very long time. Is there a better way to do it? Does anyone have any examples?</p>
<p>I'm using Ubuntu 8.04 and couldn't get the java "one wire viewer" app to run.</p>
<p><strong>Update</strong>: Using <a href="http://owfs.sourceforge.net/owpython.html" rel="nofollow"><code>owpython</code></a> (installed with owfs), I can get the current temperature but can't figure out how to get access to the recorded logs:</p>
<pre><code>>>> import ow
>>> ow.init("u") # initialize USB
>>> ow.Sensor("/").sensorList()
[Sensor("/81.7FD921000000"), Sensor("/21.C4B912000000")]
>>> x = ow.Sensor("/21.C4B912000000")
>>> print x.type, x.temperature
DS1921 22
</code></pre>
<p><code>x.log</code> gives an <code>AttributeError</code>.</p>
| 9 | 2008-09-22T04:30:19Z | 3,383,201 | <p>Well I have just started to look at ibuttons and want to use python.</p>
<p>This looks more promising:</p>
<p><a href="http://www.ohloh.net/p/pyonewire" rel="nofollow">http://www.ohloh.net/p/pyonewire</a></p>
| 2 | 2010-08-01T18:22:06Z | [
"python",
"ubuntu",
"1wire"
] |
Python-passing variable between classes | 113,341 | <p>I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes.</p>
<p>Here is an example of what I have:</p>
<pre><code>class BasicInfoPage(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
<---snip--->
self.intelligence = self.genAttribs()
class MOS(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
def eligibleMOS(self, event):
if self.intelligence >= 12:
self.MOS_list.append("Analyst")
</code></pre>
<p>The problem is that I can't figure out how to use the "intelligence" variable from the BasicInfoPage class to the MOS class. I've tried several different things from around the Internet but nothing seems to work. What am I missing?</p>
<p><strong>Edit</strong> I realized after I posted this that I didn't explain it that well. I'm trying to create a computer version of the Twilight 2000 RPG from the 1980s.</p>
<p>I'm using wxPython to create a wizard; the parent class of my classes is the Wizard from wxPython. That wizard will walk a user through the creation of a character, so the Basic Information page (class BasicInfoPage) lets the user give the character's name and "roll" for the character's attributes. That's where the "self.intelligence" comes from.</p>
<p>I'm trying to use the attributes created her for a page further on in the wizard, where the user selects the speciality of the character. The specialities that are available depend on the attributes the character has, e.g. if the intelligence is high enough, the character can be an Intel Anaylst.</p>
<p>It's been several years since I've programmed, especially with OOP ideas. That's why I'm confused on how to create what's essentially a global variable with classes and methods. </p>
| 2 | 2008-09-22T05:49:00Z | 113,374 | <p>If I understood you correctly, then the answer is: You can't.</p>
<p>intelligence should be an attribute of WizardPageSimple, if you'd want both classes to inherit it.</p>
<p>Depending on your situation, you might try to extract intelligence and related attributes into another baseclass. Then you could inherit from both:</p>
<pre><code>class MOS(wiz.WizardPageSimple, wiz.IntelligenceAttributes): # Or something like that.
</code></pre>
<p>In that case you <strong>must</strong> use the co-operative super. In fact, you should be using it already. Instead of calling </p>
<pre><code>wiz.WizardPageSimple.__init__(self, parent)
</code></pre>
<p>call</p>
<pre><code>super(MOS, self).__init__(self, parent)
</code></pre>
| 0 | 2008-09-22T05:59:28Z | [
"python",
"oop",
"variables",
"wxpython"
] |
Python-passing variable between classes | 113,341 | <p>I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes.</p>
<p>Here is an example of what I have:</p>
<pre><code>class BasicInfoPage(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
<---snip--->
self.intelligence = self.genAttribs()
class MOS(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
def eligibleMOS(self, event):
if self.intelligence >= 12:
self.MOS_list.append("Analyst")
</code></pre>
<p>The problem is that I can't figure out how to use the "intelligence" variable from the BasicInfoPage class to the MOS class. I've tried several different things from around the Internet but nothing seems to work. What am I missing?</p>
<p><strong>Edit</strong> I realized after I posted this that I didn't explain it that well. I'm trying to create a computer version of the Twilight 2000 RPG from the 1980s.</p>
<p>I'm using wxPython to create a wizard; the parent class of my classes is the Wizard from wxPython. That wizard will walk a user through the creation of a character, so the Basic Information page (class BasicInfoPage) lets the user give the character's name and "roll" for the character's attributes. That's where the "self.intelligence" comes from.</p>
<p>I'm trying to use the attributes created her for a page further on in the wizard, where the user selects the speciality of the character. The specialities that are available depend on the attributes the character has, e.g. if the intelligence is high enough, the character can be an Intel Anaylst.</p>
<p>It's been several years since I've programmed, especially with OOP ideas. That's why I'm confused on how to create what's essentially a global variable with classes and methods. </p>
| 2 | 2008-09-22T05:49:00Z | 113,388 | <p>All you need is a reference. It's not really a simple problem that I can give some one-line solution to (other than a simple ugly global that would probably break something else), but one of program structure. You don't magically get access to a variable that was created on another instance of another class. You have to either give the intelligence reference to MOS, or take it from BasicInfoPage, however that might happen. It seems to me that the classes are designed rather oddly-- an information page, for one thing, should not generate anything, and if it does, it should give it back to whatever needs to know-- some sort of central place, which should have been the one generating it in the first place. Ordinarily, you'd set the variables there, and get them from there. Or at least, I would.</p>
<p>If you want the basic answer of "how do I pass variables between different classes", then here you go, but I doubt it's exactly what you want, as you look to be using some sort of controlling framework:</p>
<pre><code>class Foo(object):
def __init__(self, var):
self.var = var
class Bar(object):
def do_something(self, var):
print var*3
if __name__ == '__main__':
f = Foo(3)
b = Bar()
# look, I'm using the variable from one instance in another!
b.do_something(f.var)
</code></pre>
| 1 | 2008-09-22T06:05:58Z | [
"python",
"oop",
"variables",
"wxpython"
] |
Python-passing variable between classes | 113,341 | <p>I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes.</p>
<p>Here is an example of what I have:</p>
<pre><code>class BasicInfoPage(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
<---snip--->
self.intelligence = self.genAttribs()
class MOS(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
def eligibleMOS(self, event):
if self.intelligence >= 12:
self.MOS_list.append("Analyst")
</code></pre>
<p>The problem is that I can't figure out how to use the "intelligence" variable from the BasicInfoPage class to the MOS class. I've tried several different things from around the Internet but nothing seems to work. What am I missing?</p>
<p><strong>Edit</strong> I realized after I posted this that I didn't explain it that well. I'm trying to create a computer version of the Twilight 2000 RPG from the 1980s.</p>
<p>I'm using wxPython to create a wizard; the parent class of my classes is the Wizard from wxPython. That wizard will walk a user through the creation of a character, so the Basic Information page (class BasicInfoPage) lets the user give the character's name and "roll" for the character's attributes. That's where the "self.intelligence" comes from.</p>
<p>I'm trying to use the attributes created her for a page further on in the wizard, where the user selects the speciality of the character. The specialities that are available depend on the attributes the character has, e.g. if the intelligence is high enough, the character can be an Intel Anaylst.</p>
<p>It's been several years since I've programmed, especially with OOP ideas. That's why I'm confused on how to create what's essentially a global variable with classes and methods. </p>
| 2 | 2008-09-22T05:49:00Z | 114,114 | <p>You may have "Class" and "Instance" confused. It's not clear from your example, so I'll presume that you're using a lot of class definitions and don't have appropriate object instances of those classes.</p>
<p>Classes don't really have usable attribute values. A class is just a common set of definitions for a collection of objects. You should think of of classes as definitions, not actual things.</p>
<p>Instances of classes, "objects", are actual things that have actual attribute values and execute method functions.</p>
<p>You don't pass variables among <em>classes</em>. You pass variables among <em>instances</em>. As a practical matter only instance variables matter. [Yes, there are class variables, but they're a fairly specialized and often confusing thing, best avoided.]</p>
<p>When you create an object (an instance of a class)</p>
<pre><code>b= BasicInfoPage(...)
</code></pre>
<p>Then <code>b.intelligence</code> is the value of intelligence for the <code>b</code> instance of <code>BasicInfoPage</code>.</p>
<p>A really common thing is </p>
<pre><code>class MOS( wx.wizard.PageSimple ):
def __init__( self, parent, title, basicInfoPage ):
<snip>
self.basicInfo= basicInfoPage
</code></pre>
<p>Now, within MOS methods, you can say <code>self.basicInfo.intelligence</code> because MOS has an object that's a BasicInfoPage available to it.</p>
<p>When you build MOS, you provide it with the instance of BasicInfoPage that it's supposed to use.</p>
<pre><code>someBasicInfoPage= BasicInfoPage( ... )
m= MOS( ..., someBasicInfoPage )
</code></pre>
<p>Now, the object <code>m</code> can examine <code>someBasicInfoPage.intelligence</code> </p>
| 6 | 2008-09-22T10:12:50Z | [
"python",
"oop",
"variables",
"wxpython"
] |
Python-passing variable between classes | 113,341 | <p>I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes.</p>
<p>Here is an example of what I have:</p>
<pre><code>class BasicInfoPage(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
<---snip--->
self.intelligence = self.genAttribs()
class MOS(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
def eligibleMOS(self, event):
if self.intelligence >= 12:
self.MOS_list.append("Analyst")
</code></pre>
<p>The problem is that I can't figure out how to use the "intelligence" variable from the BasicInfoPage class to the MOS class. I've tried several different things from around the Internet but nothing seems to work. What am I missing?</p>
<p><strong>Edit</strong> I realized after I posted this that I didn't explain it that well. I'm trying to create a computer version of the Twilight 2000 RPG from the 1980s.</p>
<p>I'm using wxPython to create a wizard; the parent class of my classes is the Wizard from wxPython. That wizard will walk a user through the creation of a character, so the Basic Information page (class BasicInfoPage) lets the user give the character's name and "roll" for the character's attributes. That's where the "self.intelligence" comes from.</p>
<p>I'm trying to use the attributes created her for a page further on in the wizard, where the user selects the speciality of the character. The specialities that are available depend on the attributes the character has, e.g. if the intelligence is high enough, the character can be an Intel Anaylst.</p>
<p>It's been several years since I've programmed, especially with OOP ideas. That's why I'm confused on how to create what's essentially a global variable with classes and methods. </p>
| 2 | 2008-09-22T05:49:00Z | 114,128 | <p>Each page of a Wizard -- by itself -- shouldn't actually be the container for the information you're gathering.</p>
<p>Read up on the <a href="http://en.wikipedia.org/wiki/Model-view-controller" rel="nofollow">Model-View-Control</a> design pattern. Your pages have the View and Control parts of the design. They aren't the data model, however.</p>
<p>You'll be happier if you have a separate object that is "built" by the pages. Each page will set some attributes of that underlying model object. Then, the pages are independent of each other, since the pages all get and set values of this underlying model object.</p>
<p>Since you're building a character, you'd have some class like this</p>
<pre><code>class Character( object ):
def __init__( self ):
self.intelligence= 10
<default values for all attributes.>
</code></pre>
<p>Then your various Wizard instances just need to be given the underlying Character object as a place to put and get values.</p>
| 3 | 2008-09-22T10:18:04Z | [
"python",
"oop",
"variables",
"wxpython"
] |
Python-passing variable between classes | 113,341 | <p>I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes.</p>
<p>Here is an example of what I have:</p>
<pre><code>class BasicInfoPage(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
<---snip--->
self.intelligence = self.genAttribs()
class MOS(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
def eligibleMOS(self, event):
if self.intelligence >= 12:
self.MOS_list.append("Analyst")
</code></pre>
<p>The problem is that I can't figure out how to use the "intelligence" variable from the BasicInfoPage class to the MOS class. I've tried several different things from around the Internet but nothing seems to work. What am I missing?</p>
<p><strong>Edit</strong> I realized after I posted this that I didn't explain it that well. I'm trying to create a computer version of the Twilight 2000 RPG from the 1980s.</p>
<p>I'm using wxPython to create a wizard; the parent class of my classes is the Wizard from wxPython. That wizard will walk a user through the creation of a character, so the Basic Information page (class BasicInfoPage) lets the user give the character's name and "roll" for the character's attributes. That's where the "self.intelligence" comes from.</p>
<p>I'm trying to use the attributes created her for a page further on in the wizard, where the user selects the speciality of the character. The specialities that are available depend on the attributes the character has, e.g. if the intelligence is high enough, the character can be an Intel Anaylst.</p>
<p>It's been several years since I've programmed, especially with OOP ideas. That's why I'm confused on how to create what's essentially a global variable with classes and methods. </p>
| 2 | 2008-09-22T05:49:00Z | 120,109 | <p>My problem was indeed the confusion of classes vs. instances. I was trying to do everything via classes without ever creating an actual instance. Plus, I was forcing the "BasicInfoPage" class to do too much work.</p>
<p>Ultimately, I created a new class (<strong>BaseAttribs</strong>) to hold all the variables I need. I then created in instance of that class when I run the wizard and pass that instance as an argument to the classes that need it, as shown below:</p>
<pre><code>#---Run the wizard
if __name__ == "__main__":
app = wx.PySimpleApp()
wizard = wiz.Wizard(None, -1, "TW2K Character Creation")
attribs = BaseAttribs
#---Create each page
page1 = IntroPage(wizard, "Introduction")
page2 = BasicInfoPage(wizard, "Basic Info", attribs)
page3 = Ethnicity(wizard, "Ethnicity")
page4 = MOS(wizard, "Military Occupational Specialty", attribs)
</code></pre>
<p>I then used the information S.Lott provided and created individual instances (if that's what it's called) within each class; each class is accessing the same variables though.</p>
<p>Everything works, as far as I can tell. Thanks.</p>
| 2 | 2008-09-23T09:48:59Z | [
"python",
"oop",
"variables",
"wxpython"
] |
Is there a function in Python to split a string without ignoring the spaces? | 113,534 | <p>Is there a function in Python to split a string without ignoring the spaces in the resulting list? </p>
<p>E.g:</p>
<pre><code>s="This is the string I want to split".split()
</code></pre>
<p>gives me</p>
<pre><code>>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']
</code></pre>
<p>I want something like</p>
<pre><code>['This',' ','is',' ', 'the',' ','string', ' ', .....]
</code></pre>
| 12 | 2008-09-22T07:02:04Z | 113,554 | <p>The hard part with what you're trying to do is that you aren't giving it a character to split on. split() explodes a string on the character you provide to it, and removes that character.</p>
<p>Perhaps this may help:</p>
<pre><code>s = "String to split"
mylist = []
for item in s.split():
mylist.append(item)
mylist.append(' ')
mylist = mylist[:-1]
</code></pre>
<p>Messy, but it'll do the trick for you...</p>
| 1 | 2008-09-22T07:07:58Z | [
"python",
"split"
] |
Is there a function in Python to split a string without ignoring the spaces? | 113,534 | <p>Is there a function in Python to split a string without ignoring the spaces in the resulting list? </p>
<p>E.g:</p>
<pre><code>s="This is the string I want to split".split()
</code></pre>
<p>gives me</p>
<pre><code>>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']
</code></pre>
<p>I want something like</p>
<pre><code>['This',' ','is',' ', 'the',' ','string', ' ', .....]
</code></pre>
| 12 | 2008-09-22T07:02:04Z | 113,555 | <pre><code>>>> import re
>>> re.split(r"(\s+)", "This is the string I want to split")
['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split']
</code></pre>
<p>Using the capturing parentheses in re.split() causes the function to return the separators as well.</p>
| 40 | 2008-09-22T07:08:04Z | [
"python",
"split"
] |
Is there a function in Python to split a string without ignoring the spaces? | 113,534 | <p>Is there a function in Python to split a string without ignoring the spaces in the resulting list? </p>
<p>E.g:</p>
<pre><code>s="This is the string I want to split".split()
</code></pre>
<p>gives me</p>
<pre><code>>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']
</code></pre>
<p>I want something like</p>
<pre><code>['This',' ','is',' ', 'the',' ','string', ' ', .....]
</code></pre>
| 12 | 2008-09-22T07:02:04Z | 113,558 | <p>I don't think there is a function in the standard library that does that by itself, but "partition" comes close</p>
<p>The best way is probably to use regular expressions (which is how I'd do this in any language!)</p>
<pre><code>import re
print re.split(r"(\s+)", "Your string here")
</code></pre>
| 4 | 2008-09-22T07:08:59Z | [
"python",
"split"
] |
Is there a function in Python to split a string without ignoring the spaces? | 113,534 | <p>Is there a function in Python to split a string without ignoring the spaces in the resulting list? </p>
<p>E.g:</p>
<pre><code>s="This is the string I want to split".split()
</code></pre>
<p>gives me</p>
<pre><code>>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']
</code></pre>
<p>I want something like</p>
<pre><code>['This',' ','is',' ', 'the',' ','string', ' ', .....]
</code></pre>
| 12 | 2008-09-22T07:02:04Z | 16,123,808 | <p>Silly answer just for the heck of it:</p>
<pre><code>mystring.replace(" ","! !").split("!")
</code></pre>
| 2 | 2013-04-20T18:34:12Z | [
"python",
"split"
] |
Is there a function in python to split a word into a list? | 113,655 | <p>Is there a function in python to split a word into a list of single letters? e.g:</p>
<pre><code>s="Word to Split"
</code></pre>
<p>to get</p>
<pre><code>wordlist=['W','o','r','d','','t','o' ....]
</code></pre>
| 41 | 2008-09-22T07:40:50Z | 113,662 | <pre><code>>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
</code></pre>
| 119 | 2008-09-22T07:42:15Z | [
"python",
"function",
"split"
] |
Is there a function in python to split a word into a list? | 113,655 | <p>Is there a function in python to split a word into a list of single letters? e.g:</p>
<pre><code>s="Word to Split"
</code></pre>
<p>to get</p>
<pre><code>wordlist=['W','o','r','d','','t','o' ....]
</code></pre>
| 41 | 2008-09-22T07:40:50Z | 113,680 | <p>The easiest way is probably just to use <code>list()</code>, but there is at least one other option as well:</p>
<pre><code>s = "Word to Split"
wordlist = list(s) # option 1,
wordlist = [ch for ch in s] # option 2, list comprehension.
</code></pre>
<p>They should <em>both</em> give you what you need:</p>
<pre><code>['W','o','r','d',' ','t','o',' ','S','p','l','i','t']
</code></pre>
<p>As stated, the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff, such as if you want to apply some arbitrary function to the items, such as with:</p>
<pre><code>[doSomethingWith(ch) for ch in s]
</code></pre>
| 9 | 2008-09-22T07:46:45Z | [
"python",
"function",
"split"
] |
Is there a function in python to split a word into a list? | 113,655 | <p>Is there a function in python to split a word into a list of single letters? e.g:</p>
<pre><code>s="Word to Split"
</code></pre>
<p>to get</p>
<pre><code>wordlist=['W','o','r','d','','t','o' ....]
</code></pre>
| 41 | 2008-09-22T07:40:50Z | 113,681 | <p>The list function will do this</p>
<pre><code>>>> list('foo')
['f', 'o', 'o']
</code></pre>
| 1 | 2008-09-22T07:47:20Z | [
"python",
"function",
"split"
] |
Is there a function in python to split a word into a list? | 113,655 | <p>Is there a function in python to split a word into a list of single letters? e.g:</p>
<pre><code>s="Word to Split"
</code></pre>
<p>to get</p>
<pre><code>wordlist=['W','o','r','d','','t','o' ....]
</code></pre>
| 41 | 2008-09-22T07:40:50Z | 115,195 | <p>Abuse of the rules, same result:
(x for x in 'Word to split')</p>
<p>Actually an iterator, not a list. But it's likely you won't really care.</p>
| 2 | 2008-09-22T14:36:35Z | [
"python",
"function",
"split"
] |
Deploying Django: How do you do it? | 114,112 | <p>I have tried following guides like <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/">this one</a> but it just didnt work for me.</p>
<p><strong>So my question is this:</strong> What is a good guide for deploying Django, and how do you deploy your Django.</p>
<p>I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploying code), or even if i want/need to use it or not.</p>
| 12 | 2008-09-22T10:11:48Z | 114,127 | <p>This looks like a good place to start: <a href="http://www.unessa.net/en/hoyci/2007/06/using-capistrano-deploy-django-apps/" rel="nofollow">http://www.unessa.net/en/hoyci/2007/06/using-capistrano-deploy-django-apps/</a></p>
| 0 | 2008-09-22T10:17:53Z | [
"python",
"django-deployment"
] |
Deploying Django: How do you do it? | 114,112 | <p>I have tried following guides like <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/">this one</a> but it just didnt work for me.</p>
<p><strong>So my question is this:</strong> What is a good guide for deploying Django, and how do you deploy your Django.</p>
<p>I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploying code), or even if i want/need to use it or not.</p>
| 12 | 2008-09-22T10:11:48Z | 114,137 | <p>The easiest way would be to use one of the sites on <a href="http://djangofriendly.com/hosts/" rel="nofollow">http://djangofriendly.com/hosts/</a> that will provide the hosting and set up for you, but even if you're wanting to roll your own it will allow you to see what set up other sites are using.</p>
| -2 | 2008-09-22T10:20:42Z | [
"python",
"django-deployment"
] |
Deploying Django: How do you do it? | 114,112 | <p>I have tried following guides like <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/">this one</a> but it just didnt work for me.</p>
<p><strong>So my question is this:</strong> What is a good guide for deploying Django, and how do you deploy your Django.</p>
<p>I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploying code), or even if i want/need to use it or not.</p>
| 12 | 2008-09-22T10:11:48Z | 114,228 | <p>I have had success with <a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango" rel="nofollow">mod_wsgi</a></p>
| 1 | 2008-09-22T10:55:39Z | [
"python",
"django-deployment"
] |
Deploying Django: How do you do it? | 114,112 | <p>I have tried following guides like <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/">this one</a> but it just didnt work for me.</p>
<p><strong>So my question is this:</strong> What is a good guide for deploying Django, and how do you deploy your Django.</p>
<p>I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploying code), or even if i want/need to use it or not.</p>
| 12 | 2008-09-22T10:11:48Z | 114,268 | <p><code>mod_wsgi</code> in combination with a <code>virtualenv</code> for all the dependencies, a mercurial checkout into the virtualenv and a <code>fabric</code> recipe to check out the changes on the server.</p>
<p>I wrote an article about my usual workflow: <a href="http://lucumr.pocoo.org/2008/7/17/deploying-python-web-applications/" rel="nofollow">Deploying Python Web Applications</a>. Hope that helps.</p>
| 7 | 2008-09-22T11:06:01Z | [
"python",
"django-deployment"
] |
Deploying Django: How do you do it? | 114,112 | <p>I have tried following guides like <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/">this one</a> but it just didnt work for me.</p>
<p><strong>So my question is this:</strong> What is a good guide for deploying Django, and how do you deploy your Django.</p>
<p>I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploying code), or even if i want/need to use it or not.</p>
| 12 | 2008-09-22T10:11:48Z | 117,095 | <p>In my previous work we had real genius guy on deployment duties, he deployed application (Python, SQL, Perl and Java code) as set of deb files built for Ubuntu. Unfortunately now, I have no such support. We are deploying apps manually to virtualenv-ed environments with separate nginx configs for FastCGI. We use <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">paver</a> to deploy to remote servers. It's painful, but it works.</p>
| 1 | 2008-09-22T19:48:45Z | [
"python",
"django-deployment"
] |
Deploying Django: How do you do it? | 114,112 | <p>I have tried following guides like <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/">this one</a> but it just didnt work for me.</p>
<p><strong>So my question is this:</strong> What is a good guide for deploying Django, and how do you deploy your Django.</p>
<p>I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploying code), or even if i want/need to use it or not.</p>
| 12 | 2008-09-22T10:11:48Z | 1,546,416 | <p>I use mod_python, and have every site in a git repository with the following subdirs:</p>
<ul>
<li>mysite</li>
<li>template</li>
<li>media</li>
</ul>
<p>I have <code>mysite/settings.py</code> in <code>.gitignore</code>, and work like this:</p>
<ol>
<li>do development on my local machine</li>
<li>create remote repository on webserver</li>
<li>push my changes to webserver repo</li>
<li>set up apache vhost config file, tweak live server settings.py</li>
<li>run <code>git checkout && git reset --hard && sudo /etc/init.d/apache2 restart</code> on webserver repo to get up-to-date version to its working copy and restart apache</li>
<li>repeat steps 1, 3 and 5 whenever change request comes</li>
</ol>
| 0 | 2009-10-09T22:44:18Z | [
"python",
"django-deployment"
] |
Class method differences in Python: bound, unbound and static | 114,214 | <p>What is the difference between the following class methods?</p>
<p>Is it that one is static and the other is not?</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
</code></pre>
| 190 | 2008-09-22T10:49:43Z | 114,232 | <p>When you call a class member, Python automatically uses a reference to the object as the first parameter. The variable <code>self</code> actually means nothing, it's just a coding convention. You could call it <code>gargaloo</code> if you wanted. That said, the call to <code>method_two</code> would raise a <code>TypeError</code>, because Python is automatically trying to pass a parameter (the reference to its parent object) to a method that was defined as having no parameters.</p>
<p>To actually make it work, you could append this to your class definition:</p>
<pre><code>method_two = staticmethod(method_two)
</code></pre>
<p>or you could use the <code>@staticmethod</code> <a href="https://docs.python.org/2/library/functions.html#staticmethod" rel="nofollow">function decorator</a>.</p>
| 10 | 2008-09-22T10:56:27Z | [
"python"
] |
Class method differences in Python: bound, unbound and static | 114,214 | <p>What is the difference between the following class methods?</p>
<p>Is it that one is static and the other is not?</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
</code></pre>
| 190 | 2008-09-22T10:49:43Z | 114,250 | <p>method_two won't work because you're defining a member function but not telling it what the function is a member of. If you execute the last line you'll get:</p>
<pre><code>>>> a_test.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)
</code></pre>
<p>If you're defining member functions for a class the first argument must always be 'self'.</p>
| 4 | 2008-09-22T11:00:29Z | [
"python"
] |
Class method differences in Python: bound, unbound and static | 114,214 | <p>What is the difference between the following class methods?</p>
<p>Is it that one is static and the other is not?</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
</code></pre>
| 190 | 2008-09-22T10:49:43Z | 114,251 | <p>The call to method_two will throw an exception for not accepting the self parameter the Python runtime will automatically pass it.</p>
<p>If you want to create a static method in a Python class, decorate it with the <code>staticmethod decorator</code>.</p>
<pre><code>Class Test(Object):
@staticmethod
def method_two():
print "Called method_two"
Test.method_two()
</code></pre>
| 1 | 2008-09-22T11:00:59Z | [
"python"
] |
Class method differences in Python: bound, unbound and static | 114,214 | <p>What is the difference between the following class methods?</p>
<p>Is it that one is static and the other is not?</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
</code></pre>
| 190 | 2008-09-22T10:49:43Z | 114,267 | <p>In Python, there is a distinction between <em>bound</em> and <em>unbound</em> methods. </p>
<p>Basically, a call to a member function (like <code>method_one</code>), a bound function</p>
<pre><code>a_test.method_one()
</code></pre>
<p>is translated to</p>
<pre><code>Test.method_one(a_test)
</code></pre>
<p>i.e. a call to an unbound method. Because of that, a call to your version of <code>method_two</code> will fail with a <code>TypeError</code></p>
<pre><code>>>> a_test = Test()
>>> a_test.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)
</code></pre>
<p>You can change the behavior of a method using a decorator</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
@staticmethod
def method_two():
print "Called method two"
</code></pre>
<p>The decorator tells the built-in default metaclass <code>type</code> (the class of a class, cf. <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">this question</a>) to not create bound methods for <code>method_two</code>.</p>
<p>Now, you can invoke static method both on an instance or on the class directly:</p>
<pre><code>>>> a_test = Test()
>>> a_test.method_one()
Called method_one
>>> a_test.method_two()
Called method_two
>>> Test.method_two()
Called method_two
</code></pre>
| 325 | 2008-09-22T11:05:54Z | [
"python"
] |
Class method differences in Python: bound, unbound and static | 114,214 | <p>What is the difference between the following class methods?</p>
<p>Is it that one is static and the other is not?</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
</code></pre>
| 190 | 2008-09-22T10:49:43Z | 114,281 | <p>that is an error.</p>
<p>first of all, first line should be like this (be careful of capitals)</p>
<pre><code>class Test(object):
</code></pre>
<p>Whenever you call a method of a class, it gets itself as the first argument (hence the name self) and method_two gives this error </p>
<pre><code>>>> a.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)
</code></pre>
| 1 | 2008-09-22T11:10:01Z | [
"python"
] |
Class method differences in Python: bound, unbound and static | 114,214 | <p>What is the difference between the following class methods?</p>
<p>Is it that one is static and the other is not?</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
</code></pre>
| 190 | 2008-09-22T10:49:43Z | 114,285 | <p>The second one won't work because when you call it like that python internally tries to call it with the a_test instance as the first argument, but your method_two doesn't accept any arguments, so it wont work, you'll get a runtime error.
If you want the equivalent of a static method you can use a class method.
There's much less need for class methods in Python than static methods in languages like Java or C#. Most often the best solution is to use a method in the module, outside a class definition, those work more efficiently than class methods.</p>
| 1 | 2008-09-22T11:11:49Z | [
"python"
] |
Class method differences in Python: bound, unbound and static | 114,214 | <p>What is the difference between the following class methods?</p>
<p>Is it that one is static and the other is not?</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
</code></pre>
| 190 | 2008-09-22T10:49:43Z | 114,289 | <p>Methods in Python are a very, very simple thing once you understood the basics of the descriptor system. Imagine the following class:</p>
<pre><code>class C(object):
def foo(self):
pass
</code></pre>
<p>Now let's have a look at that class in the shell:</p>
<pre><code>>>> C.foo
<unbound method C.foo>
>>> C.__dict__['foo']
<function foo at 0x17d05b0>
</code></pre>
<p>As you can see if you access the <code>foo</code> attribute on the class you get back an unbound method, however inside the class storage (the dict) there is a function. Why's that? The reason for this is that the class of your class implements a <code>__getattribute__</code> that resolves descriptors. Sounds complex, but is not. <code>C.foo</code> is roughly equivalent to this code in that special case:</p>
<pre><code>>>> C.__dict__['foo'].__get__(None, C)
<unbound method C.foo>
</code></pre>
<p>That's because functions have a <code>__get__</code> method which makes them descriptors. If you have an instance of a class it's nearly the same, just that <code>None</code> is the class instance:</p>
<pre><code>>>> c = C()
>>> C.__dict__['foo'].__get__(c, C)
<bound method C.foo of <__main__.C object at 0x17bd4d0>>
</code></pre>
<p>Now why does Python do that? Because the method object binds the first parameter of a function to the instance of the class. That's where self comes from. Now sometimes you don't want your class to make a function a method, that's where <code>staticmethod</code> comes into play:</p>
<pre><code> class C(object):
@staticmethod
def foo():
pass
</code></pre>
<p>The <code>staticmethod</code> decorator wraps your class and implements a dummy <code>__get__</code> that returns the wrapped function as function and not as a method:</p>
<pre><code>>>> C.__dict__['foo'].__get__(None, C)
<function foo at 0x17d0c30>
</code></pre>
<p>Hope that explains it.</p>
| 163 | 2008-09-22T11:12:36Z | [
"python"
] |
Class method differences in Python: bound, unbound and static | 114,214 | <p>What is the difference between the following class methods?</p>
<p>Is it that one is static and the other is not?</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
</code></pre>
| 190 | 2008-09-22T10:49:43Z | 2,696,019 | <pre><code>>>> class Class(object):
... def __init__(self):
... self.i = 0
... def instance_method(self):
... self.i += 1
... print self.i
... c = 0
... @classmethod
... def class_method(cls):
... cls.c += 1
... print cls.c
... @staticmethod
... def static_method(s):
... s += 1
... print s
...
>>> a = Class()
>>> a.class_method()
1
>>> Class.class_method() # The class shares this value across instances
2
>>> a.instance_method()
1
>>> Class.instance_method() # The class cannot use an instance method
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method instance_method() must be called with Class instance as first argument (got nothing instead)
>>> Class.instance_method(a)
2
>>> b = 0
>>> a.static_method(b)
1
>>> a.static_method(a.c) # Static method does not have direct access to
>>> # class or instance properties.
3
>>> Class.c # a.c above was passed by value and not by reference.
2
>>> a.c
2
>>> a.c = 5 # The connection between the instance
>>> Class.c # and its class is weak as seen here.
2
>>> Class.class_method()
3
>>> a.c
5
</code></pre>
| 10 | 2010-04-23T03:25:12Z | [
"python"
] |
Class method differences in Python: bound, unbound and static | 114,214 | <p>What is the difference between the following class methods?</p>
<p>Is it that one is static and the other is not?</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
</code></pre>
| 190 | 2008-09-22T10:49:43Z | 21,213,848 | <p>Please read this docs from the Guido <a href="http://python-history.blogspot.in/2009/02/first-class-everything.html" rel="nofollow">First Class everything</a> Clearly explained how Unbound, Bound methods are born.</p>
| 1 | 2014-01-19T06:18:41Z | [
"python"
] |
Class method differences in Python: bound, unbound and static | 114,214 | <p>What is the difference between the following class methods?</p>
<p>Is it that one is static and the other is not?</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
</code></pre>
| 190 | 2008-09-22T10:49:43Z | 39,563,369 | <p>Accurate explanation from Armin Ronacher above, expanding on his answers so that beginners like me understand it well:</p>
<p>Difference in the methods defined in a class, whether static or instance method(there is yet another type - class method - not discussed here so skipping it), lay in the fact whether they are somehow bound to the class instance or not. For example, say whether the method receives a reference to the class instance during runtime</p>
<pre><code>class C:
a = []
def foo(self):
pass
C # this is the class object
C.a # is a list object (class property object)
C.foo # is a function object (class property object)
c = C()
c # this is the class instance
</code></pre>
<p>The <code>__dict__</code> dictionary property of the class object holds the reference to all the properties and methods of a class object and thus </p>
<pre><code>>>> C.__dict__['foo']
<function foo at 0x17d05b0>
</code></pre>
<p>the method foo is accessible as above. An important point to note here is that everything in python is an object and so references in the dictionary above are themselves pointing to other objects. Let me call them Class Property Objects - or as CPO within the scope of my answer for brevity.</p>
<p>If a CPO is a descriptor, then python interpretor calls the <code>__get__()</code> method of the CPO to access the value it contains.</p>
<p>In order to determine if a CPO is a descriptor, python interpretor checks if it implements the descriptor protocol. To implement descriptor protocol is to implement 3 methods</p>
<pre><code>def __get__(self, instance, owner)
def __set__(self, instance, value)
def __delete__(self, instance)
</code></pre>
<p>for e.g. </p>
<pre><code>>>> C.__dict__['foo'].__get__(c, C)
</code></pre>
<p>where </p>
<ul>
<li><code>self</code> is the CPO (it could be an instance of list, str, function etc) and is supplied by the runtime</li>
<li><code>instance</code> is the instance of the class where this CPO is defined (the object 'c' above) and needs to be explicity supplied by us</li>
<li><code>owner</code> is the class where this CPO is defined(the class object 'C' above) and needs to be supplied by us. However this is because we are calling it on the CPO. when we call it on the instance, we dont need to supply this since the runtime can supply the instance or its class(polymorphism)</li>
<li><code>value</code> is the intended value for the CPO and needs to be supplied by us</li>
</ul>
<p>Not all CPO are descriptors. For example </p>
<pre><code>>>> C.__dict__['foo'].__get__(None, C)
<function C.foo at 0x10a72f510>
>>> C.__dict__['a'].__get__(None, C)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__get__'
</code></pre>
<p>This is because the list class doesnt implement the descriptor protocol.</p>
<p>Thus the argument self in <code>c.foo(self)</code> is required because its method signature is actually this <code>C.__dict__['foo'].__get__(c, C)</code> (as explained above, C is not needed as it can be found out or polymorphed)
And this is also why you get a TypeError if you dont pass that required instance argument.</p>
<p>If you notice the method is still referenced via the class Object C and the binding with the class instance is achieved via passing a context in the form of the instance object into this function. </p>
<p>This is pretty awesome since if you chose to keep no context or no binding to the instance, all that was needed was to write a class to wrap the descriptor CPO and override its <code>__get__()</code> method to require no context.
This new class is what we call a decorator and is applied via the keyword <code>@staticmethod</code></p>
<pre><code>class C(object):
@staticmethod
def foo():
pass
</code></pre>
<p>The absence of context in the new wrapped CPO <code>foo</code> doesnt throw an error and can be verified as follows:</p>
<pre><code>>>> C.__dict__['foo'].__get__(None, C)
<function foo at 0x17d0c30>
</code></pre>
<p>Use case of a static method is more of a namespacing and code maintainability one(taking it out of a class and making it available throughout the module etc). </p>
<p>It maybe better to write static methods rather than instance methods whenever possible, unless ofcourse you need to contexualise the methods(like access instance variables, class variables etc). One reason is to ease garbage collection by not keeping unwanted reference to objects.</p>
| 0 | 2016-09-18T22:51:16Z | [
"python"
] |
Where can a save confirmation page be hooked into the Django admin? (similar to delete confirmation) | 114,283 | <p>I want to emulate the delete confirmation page behavior before saving
certain models in the admin. In my case if I change one object,
certain others should be deleted as they depend upon the object's now
out-of-date state. </p>
<p>I understand where to implement the actual cascaded updates (inside
the parent model's save method), but I don't see a quick way to ask
the user for confirmation (and then rollback if they decide not to
save). I suppose I could implement some weird confirmation logic
directly inside the save method (sort of a two phase save) but that
seems...ugly. </p>
<p>Any thoughts, even general pointers into the django codebase? </p>
<p>Thanks!</p>
| 7 | 2008-09-22T11:11:12Z | 114,348 | <p>I'm by no means a Django expert, so this answer might misguide you. </p>
<p>Start looking somewhere around <code>django.contrib.admin.options.ModelAdmin</code>, especially <code>render_change_form</code> and <code>response_change</code>. I guess you would need to subclass ModelAdmin for your model and provide required behavior around those methods.</p>
| 1 | 2008-09-22T11:36:43Z | [
"python",
"django"
] |
Where can a save confirmation page be hooked into the Django admin? (similar to delete confirmation) | 114,283 | <p>I want to emulate the delete confirmation page behavior before saving
certain models in the admin. In my case if I change one object,
certain others should be deleted as they depend upon the object's now
out-of-date state. </p>
<p>I understand where to implement the actual cascaded updates (inside
the parent model's save method), but I don't see a quick way to ask
the user for confirmation (and then rollback if they decide not to
save). I suppose I could implement some weird confirmation logic
directly inside the save method (sort of a two phase save) but that
seems...ugly. </p>
<p>Any thoughts, even general pointers into the django codebase? </p>
<p>Thanks!</p>
| 7 | 2008-09-22T11:11:12Z | 114,373 | <p>You could overload the <code>get_form</code> method of your model admin and add an extra checkbox to the generated form that has to be ticket. Alternatively you can override <code>change_view</code> and intercept the request.</p>
| 2 | 2008-09-22T11:42:42Z | [
"python",
"django"
] |
Where can a save confirmation page be hooked into the Django admin? (similar to delete confirmation) | 114,283 | <p>I want to emulate the delete confirmation page behavior before saving
certain models in the admin. In my case if I change one object,
certain others should be deleted as they depend upon the object's now
out-of-date state. </p>
<p>I understand where to implement the actual cascaded updates (inside
the parent model's save method), but I don't see a quick way to ask
the user for confirmation (and then rollback if they decide not to
save). I suppose I could implement some weird confirmation logic
directly inside the save method (sort of a two phase save) but that
seems...ugly. </p>
<p>Any thoughts, even general pointers into the django codebase? </p>
<p>Thanks!</p>
| 7 | 2008-09-22T11:11:12Z | 121,796 | <p>Have you considered overriding the administrative templates for the models in question? This <a href="http://www.unessa.net/en/hoyci/2006/12/custom-admin-templates/" rel="nofollow">link</a> provides an excellent overview of the process. In this particular situation, having a finer-grained level of control may be the best way to achieve the desired result.</p>
| 0 | 2008-09-23T15:37:06Z | [
"python",
"django"
] |
What is the fastest way to scale and display an image in Python? | 114,597 | <p>I am required to display a two dimensional numpy.array of int16 at 20fps or so. Using Matplotlib's imshow chokes on anything above 10fps. There obviously are some issues with scaling and interpolation. I should add that the dimensions of the array are not known, but will probably be around thirty by four hundred. </p>
<p>These are data from a sensor that are supposed to have a real-time display, so the data has to be re-sampled on the fly.</p>
| 5 | 2008-09-22T12:36:53Z | 114,626 | <p>The fastest way to display 30x400 data points is to:</p>
<h2>Use OpenGL color arrays</h2>
<p>If you can quickly transform your data to what OpenGL understands as color array, you could create a vertex array describing quads, one for each sensor, then update your color array and draw this orthographically on screen.</p>
<h2>Use OpenGL textures</h2>
<p>If you can quickly transform your datapoints to an opengl texture you can draw one quad with fixed UV coordinates that is bound to this texture.</p>
<h2>Use pygame</h2>
<p>Pygame has support for conversion of Numpy/Numarray to surfaces, Pygame can then transform such surfaces which involves resampling, after resampling you can blit it on screen.</p>
<h2>Misc</h2>
<p><a href="http://pyglet.org/">pyglet</a> makes dealing with opengl very easy</p>
| 6 | 2008-09-22T12:43:30Z | [
"python",
"animation",
"matplotlib",
"image-scaling"
] |
Is a Python dictionary an example of a hash table? | 114,830 | <p>One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?</p>
| 88 | 2008-09-22T13:22:28Z | 114,831 | <p>Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, <a href="http://mail.python.org/pipermail/python-list/2000-March/048085.html">here</a>.</p>
<p>That's why you can't use something 'not hashable' as a dict key, like a list:</p>
<pre><code>>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
</code></pre>
<p>You can <a href="http://en.wikipedia.org/wiki/Hash_table">read more about hash tables</a> or <a href="https://hg.python.org/cpython/file/10eea15880db/Objects/dictobject.c">check how it has been implemented in python</a> and <a href="https://hg.python.org/cpython/file/10eea15880db/Objects/dictnotes.txt">why it is implemented that way</a>.</p>
| 127 | 2008-09-22T13:23:00Z | [
"python",
"hash",
"dictionary",
"hashmap",
"hashtable"
] |
Is a Python dictionary an example of a hash table? | 114,830 | <p>One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?</p>
| 88 | 2008-09-22T13:22:28Z | 114,848 | <p>Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (<a href="http://mail.python.org/pipermail/python-list/2000-February/023645.html">source</a>).</p>
| 14 | 2008-09-22T13:25:27Z | [
"python",
"hash",
"dictionary",
"hashmap",
"hashtable"
] |
Is a Python dictionary an example of a hash table? | 114,830 | <p>One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?</p>
| 88 | 2008-09-22T13:22:28Z | 114,853 | <p>If you're interested in the technical details, one article in <a href="http://oreilly.com/catalog/9780596510046/">Beautiful Code</a> deals with the internals of Python's <code>dict</code> implementation.</p>
| 25 | 2008-09-22T13:26:19Z | [
"python",
"hash",
"dictionary",
"hashmap",
"hashtable"
] |
Is a Python dictionary an example of a hash table? | 114,830 | <p>One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?</p>
| 88 | 2008-09-22T13:22:28Z | 115,379 | <p>To expand upon nosklo's explanation:</p>
<pre><code>a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']
</code></pre>
| 5 | 2008-09-22T15:09:43Z | [
"python",
"hash",
"dictionary",
"hashmap",
"hashtable"
] |
Is a Python dictionary an example of a hash table? | 114,830 | <p>One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?</p>
| 88 | 2008-09-22T13:22:28Z | 33,459,086 | <p>There must be more to a Python dictionary than a table lookup on hash(). By brute experimentation I found this <strong>hash collision</strong>:</p>
<pre><code>>>> hash(1.1)
2040142438
>>> hash(4504.1)
2040142438
</code></pre>
<p>Yet it doesn't break the dictionary:</p>
<pre><code>>>> d = { 1.1: 'a', 4504.1: 'b' }
>>> d[1.1]
'a'
>>> d[4504.1]
'b'
</code></pre>
<p>Sanity check:</p>
<pre><code>>>> for k,v in d.items(): print(hash(k))
2040142438
2040142438
</code></pre>
<p>Possibly there's another lookup level beyond hash() that avoids collisions between dictionary keys. Or maybe dict() uses a different hash.</p>
<p>(By the way, this in Python 2.7.10. Same story in Python 3.4.3 and 3.5.0 with a collision at <code>hash(1.1) == hash(214748749.8)</code>.)</p>
| 5 | 2015-11-01T04:01:49Z | [
"python",
"hash",
"dictionary",
"hashmap",
"hashtable"
] |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | <p>I want to use a WSDL SOAP based web service in Python. I have looked at the <a href="http://diveintopython.net/soap_web_services/">Dive Into Python</a> code but the SOAPpy module does not work under Python 2.5.</p>
<p>I have tried using <a href="https://fedorahosted.org/suds">suds</a> which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item').</p>
<p>I have also looked at <a href="http://trac.optio.webfactional.com/wiki">Client</a> but this does not appear to support WSDL.</p>
<p>And I have looked at <a href="http://pywebsvcs.sourceforge.net/zsi.html">ZSI</a> but it looks very complex. Does anyone have any sample code for it?</p>
<p>The WSDL is <a href="https://ws.pingdom.com/soap/PingdomAPI.wsdl">https://ws.pingdom.com/soap/PingdomAPI.wsdl</a> and works fine with the PHP 5 SOAP client.</p>
| 102 | 2008-09-22T14:58:53Z | 115,700 | <p>Right now (as of 2008), all the SOAP libraries available for Python suck. I recommend avoiding SOAP if possible. The last time we where forced to use a SOAP web service from Python, we wrote a wrapper in C# that handled the SOAP on one side and spoke COM out the other. </p>
| 9 | 2008-09-22T15:55:07Z | [
"python",
"web-services",
"soap"
] |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | <p>I want to use a WSDL SOAP based web service in Python. I have looked at the <a href="http://diveintopython.net/soap_web_services/">Dive Into Python</a> code but the SOAPpy module does not work under Python 2.5.</p>
<p>I have tried using <a href="https://fedorahosted.org/suds">suds</a> which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item').</p>
<p>I have also looked at <a href="http://trac.optio.webfactional.com/wiki">Client</a> but this does not appear to support WSDL.</p>
<p>And I have looked at <a href="http://pywebsvcs.sourceforge.net/zsi.html">ZSI</a> but it looks very complex. Does anyone have any sample code for it?</p>
<p>The WSDL is <a href="https://ws.pingdom.com/soap/PingdomAPI.wsdl">https://ws.pingdom.com/soap/PingdomAPI.wsdl</a> and works fine with the PHP 5 SOAP client.</p>
| 102 | 2008-09-22T14:58:53Z | 117,025 | <p>It's not true SOAPpy does not work with Python 2.5 - it works, although it's very simple and really, really basic. If you want to talk to any more complicated webservice, ZSI is your only friend.</p>
<p>The really useful demo I found is at <a href="http://www.ebi.ac.uk/Tools/webservices/tutorials/python" rel="nofollow">http://www.ebi.ac.uk/Tools/webservices/tutorials/python</a> - this really helped me to understand how ZSI works.</p>
| 2 | 2008-09-22T19:38:22Z | [
"python",
"web-services",
"soap"
] |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | <p>I want to use a WSDL SOAP based web service in Python. I have looked at the <a href="http://diveintopython.net/soap_web_services/">Dive Into Python</a> code but the SOAPpy module does not work under Python 2.5.</p>
<p>I have tried using <a href="https://fedorahosted.org/suds">suds</a> which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item').</p>
<p>I have also looked at <a href="http://trac.optio.webfactional.com/wiki">Client</a> but this does not appear to support WSDL.</p>
<p>And I have looked at <a href="http://pywebsvcs.sourceforge.net/zsi.html">ZSI</a> but it looks very complex. Does anyone have any sample code for it?</p>
<p>The WSDL is <a href="https://ws.pingdom.com/soap/PingdomAPI.wsdl">https://ws.pingdom.com/soap/PingdomAPI.wsdl</a> and works fine with the PHP 5 SOAP client.</p>
| 102 | 2008-09-22T14:58:53Z | 1,793,052 | <p>I know this is an old thread but it was showing up at the top of Google's results so I wanted to share a more current discussion on Python and SOAP.</p>
<p>See: <a href="http://www.diveintopython.net/soap_web_services/index.html">http://www.diveintopython.net/soap_web_services/index.html</a></p>
| 30 | 2009-11-24T21:32:02Z | [
"python",
"web-services",
"soap"
] |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | <p>I want to use a WSDL SOAP based web service in Python. I have looked at the <a href="http://diveintopython.net/soap_web_services/">Dive Into Python</a> code but the SOAPpy module does not work under Python 2.5.</p>
<p>I have tried using <a href="https://fedorahosted.org/suds">suds</a> which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item').</p>
<p>I have also looked at <a href="http://trac.optio.webfactional.com/wiki">Client</a> but this does not appear to support WSDL.</p>
<p>And I have looked at <a href="http://pywebsvcs.sourceforge.net/zsi.html">ZSI</a> but it looks very complex. Does anyone have any sample code for it?</p>
<p>The WSDL is <a href="https://ws.pingdom.com/soap/PingdomAPI.wsdl">https://ws.pingdom.com/soap/PingdomAPI.wsdl</a> and works fine with the PHP 5 SOAP client.</p>
| 102 | 2008-09-22T14:58:53Z | 2,092,983 | <p>If you're rolling your own I'd highly recommend looking at <a href="http://effbot.org/zone/element-soap.htm" rel="nofollow">http://effbot.org/zone/element-soap.htm</a>.</p>
| 1 | 2010-01-19T11:13:16Z | [
"python",
"web-services",
"soap"
] |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | <p>I want to use a WSDL SOAP based web service in Python. I have looked at the <a href="http://diveintopython.net/soap_web_services/">Dive Into Python</a> code but the SOAPpy module does not work under Python 2.5.</p>
<p>I have tried using <a href="https://fedorahosted.org/suds">suds</a> which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item').</p>
<p>I have also looked at <a href="http://trac.optio.webfactional.com/wiki">Client</a> but this does not appear to support WSDL.</p>
<p>And I have looked at <a href="http://pywebsvcs.sourceforge.net/zsi.html">ZSI</a> but it looks very complex. Does anyone have any sample code for it?</p>
<p>The WSDL is <a href="https://ws.pingdom.com/soap/PingdomAPI.wsdl">https://ws.pingdom.com/soap/PingdomAPI.wsdl</a> and works fine with the PHP 5 SOAP client.</p>
| 102 | 2008-09-22T14:58:53Z | 2,567,815 | <p>SOAPpy is now obsolete, AFAIK, replaced by ZSL. It's a moot point, because I can't get either one to work, much less compile, on either Python 2.5 or Python 2.6</p>
| 1 | 2010-04-02T16:33:07Z | [
"python",
"web-services",
"soap"
] |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | <p>I want to use a WSDL SOAP based web service in Python. I have looked at the <a href="http://diveintopython.net/soap_web_services/">Dive Into Python</a> code but the SOAPpy module does not work under Python 2.5.</p>
<p>I have tried using <a href="https://fedorahosted.org/suds">suds</a> which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item').</p>
<p>I have also looked at <a href="http://trac.optio.webfactional.com/wiki">Client</a> but this does not appear to support WSDL.</p>
<p>And I have looked at <a href="http://pywebsvcs.sourceforge.net/zsi.html">ZSI</a> but it looks very complex. Does anyone have any sample code for it?</p>
<p>The WSDL is <a href="https://ws.pingdom.com/soap/PingdomAPI.wsdl">https://ws.pingdom.com/soap/PingdomAPI.wsdl</a> and works fine with the PHP 5 SOAP client.</p>
| 102 | 2008-09-22T14:58:53Z | 2,829,486 | <p>I would recommend that you have a look at <a href="https://fedorahosted.org/suds/">SUDS</a></p>
<p>"Suds is a lightweight SOAP python client for consuming Web Services."</p>
| 44 | 2010-05-13T19:02:39Z | [
"python",
"web-services",
"soap"
] |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | <p>I want to use a WSDL SOAP based web service in Python. I have looked at the <a href="http://diveintopython.net/soap_web_services/">Dive Into Python</a> code but the SOAPpy module does not work under Python 2.5.</p>
<p>I have tried using <a href="https://fedorahosted.org/suds">suds</a> which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item').</p>
<p>I have also looked at <a href="http://trac.optio.webfactional.com/wiki">Client</a> but this does not appear to support WSDL.</p>
<p>And I have looked at <a href="http://pywebsvcs.sourceforge.net/zsi.html">ZSI</a> but it looks very complex. Does anyone have any sample code for it?</p>
<p>The WSDL is <a href="https://ws.pingdom.com/soap/PingdomAPI.wsdl">https://ws.pingdom.com/soap/PingdomAPI.wsdl</a> and works fine with the PHP 5 SOAP client.</p>
| 102 | 2008-09-22T14:58:53Z | 19,835,265 | <p>I periodically search for a satisfactory answer to this, but no luck so far. I use soapUI + requests + manual labour.</p>
<p>I gave up and used Java the last time I <em>needed</em> to do this, and simply gave up a few times the last time I <em>wanted</em> to do this, but it wasn't essential.</p>
<p>Having successfully used the requests library last year with Project Place's RESTful API, it occurred to me that maybe I could just hand-roll the SOAP requests I want to send in a similar way.</p>
<p>Turns out that's not too difficult, but it <em>is</em> time consuming and prone to error, especially if fields are inconsistently named (the one I'm currently working on today has 'jobId', JobId' and 'JobID'. I use soapUI to load the WSDL to make it easier to extract endpoints etc and perform some manual testing. So far I've been lucky not to have been affected by changes to any WSDL that I'm using.</p>
| 5 | 2013-11-07T11:54:38Z | [
"python",
"web-services",
"soap"
] |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | <p>I want to use a WSDL SOAP based web service in Python. I have looked at the <a href="http://diveintopython.net/soap_web_services/">Dive Into Python</a> code but the SOAPpy module does not work under Python 2.5.</p>
<p>I have tried using <a href="https://fedorahosted.org/suds">suds</a> which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item').</p>
<p>I have also looked at <a href="http://trac.optio.webfactional.com/wiki">Client</a> but this does not appear to support WSDL.</p>
<p>And I have looked at <a href="http://pywebsvcs.sourceforge.net/zsi.html">ZSI</a> but it looks very complex. Does anyone have any sample code for it?</p>
<p>The WSDL is <a href="https://ws.pingdom.com/soap/PingdomAPI.wsdl">https://ws.pingdom.com/soap/PingdomAPI.wsdl</a> and works fine with the PHP 5 SOAP client.</p>
| 102 | 2008-09-22T14:58:53Z | 27,302,096 | <p>I recently stumbled up on the same problem. Here is the synopsis of my solution.
<em>(If you need to see the whole discussion, here is the link for complete discussion of the solution:
<a href="http://tedbelay.blogspot.com/2014/12/soap-web-service-client-in-python-27.html">http://tedbelay.blogspot.com/2014/12/soap-web-service-client-in-python-27.html</a>)</em></p>
<p><strong>Basic constituent code blocks needed</strong></p>
<p>The following are the required basic code blocks of your client application</p>
<ol>
<li>Session request section: request a session with the provider</li>
<li>Session authentication section: provide credentials to the provider </li>
<li>Client section: create the Client </li>
<li>Security Header section: add the WS-Security Header to the Client </li>
<li>Consumption section: consume available operations (or methods) as needed</li>
</ol>
<p><strong>What modules do you need?</strong></p>
<p>Many suggested to use Python modules such as urllib2 ; however, none of the modules work-at least for this particular project.</p>
<p>So, here is the list of the modules you need to get.
First of all, you need to download and install the latest version of suds from the following link:</p>
<blockquote>
<p>pypi.python.org/pypi/suds-jurko/0.4.1.jurko.2</p>
</blockquote>
<p>Additionally, you need to download and install requests and suds_requests modules from the following links respectively ( disclaimer: I am new to post in here, so I can't post more than one link for now).</p>
<blockquote>
<p>pypi.python.org/pypi/requests</p>
<p>pypi.python.org/pypi/suds_requests/0.1</p>
</blockquote>
<p>Once you successfully download and install these modules, you are good to go.</p>
<p><strong>The code</strong></p>
<p>Following the steps outlined earlier, the code looks like the following:
Imports:</p>
<pre><code>import logging
from suds.client import Client
from suds.wsse import *
from datetime import timedelta,date,datetime,tzinfo
import requests
from requests.auth import HTTPBasicAuth
import suds_requests
</code></pre>
<p>Session request and authentication:</p>
<pre><code>username=input('Username:')
password=input('password:')
session = requests.session()
session.auth=(username, password)
</code></pre>
<p>Create the Client:</p>
<pre><code>client = Client(WSDL_URL, faults=False, cachingpolicy=1, location=WSDL_URL, transport=suds_requests.RequestsTransport(session))
</code></pre>
<p>Add WS-Security Header:</p>
<pre><code>...
addSecurityHeader(client,username,password)
....
def addSecurityHeader(client,username,password):
security=Security()
userNameToken=UsernameToken(username,password)
timeStampToken=Timestamp(validity=600)
security.tokens.append(userNameToken)
security.tokens.append(timeStampToken)
client.set_options(wsse=security)
</code></pre>
<p>Please note that this method creates the security header depicted in Fig.1. So, your implementation may vary depending on the correct security header format provided by the owner of the service you are consuming.</p>
<p>Consume the relevant method (or operation) :</p>
<pre><code>result=client.service.methodName(Inputs)
</code></pre>
<p><strong>Logging</strong>:</p>
<p>One of the best practices in such implementations as this one is logging to see how the communication is executed. In case there is some issue, it makes debugging easy. The following code does basic logging. However, you can log many aspects of the communication in addition to the ones depicted in the code.</p>
<pre><code>logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
logging.getLogger('suds.transport').setLevel(logging.DEBUG)
</code></pre>
<p><strong>Result:</strong></p>
<p>Here is the result in my case. Note that the server returned HTTP 200. This is the standard success code for HTTP request-response.</p>
<pre><code>(200, (collectionNodeLmp){
timestamp = 2014-12-03 00:00:00-05:00
nodeLmp[] =
(nodeLmp){
pnodeId = 35010357
name = "YADKIN"
mccValue = -0.19
mlcValue = -0.13
price = 36.46
type = "500 KV"
timestamp = 2014-12-03 01:00:00-05:00
errorCodeId = 0
},
(nodeLmp){
pnodeId = 33138769
name = "ZION 1"
mccValue = -0.18
mlcValue = -1.86
price = 34.75
type = "Aggregate"
timestamp = 2014-12-03 01:00:00-05:00
errorCodeId = 0
},
})
</code></pre>
| 12 | 2014-12-04T19:13:20Z | [
"python",
"web-services",
"soap"
] |
How can I consume a WSDL (SOAP) web service in Python? | 115,316 | <p>I want to use a WSDL SOAP based web service in Python. I have looked at the <a href="http://diveintopython.net/soap_web_services/">Dive Into Python</a> code but the SOAPpy module does not work under Python 2.5.</p>
<p>I have tried using <a href="https://fedorahosted.org/suds">suds</a> which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item').</p>
<p>I have also looked at <a href="http://trac.optio.webfactional.com/wiki">Client</a> but this does not appear to support WSDL.</p>
<p>And I have looked at <a href="http://pywebsvcs.sourceforge.net/zsi.html">ZSI</a> but it looks very complex. Does anyone have any sample code for it?</p>
<p>The WSDL is <a href="https://ws.pingdom.com/soap/PingdomAPI.wsdl">https://ws.pingdom.com/soap/PingdomAPI.wsdl</a> and works fine with the PHP 5 SOAP client.</p>
| 102 | 2008-09-22T14:58:53Z | 36,910,649 | <p>There is a relatively new library which is very promising and albeit still poorly documented, seems very clean and pythonic: <a href="https://github.com/mvantellingen/python-zeep" rel="nofollow">python zeep</a>.</p>
<p>See also <a href="http://stackoverflow.com/a/36892846/204634">this answer</a> for an example.</p>
| 3 | 2016-04-28T09:33:04Z | [
"python",
"web-services",
"soap"
] |
What is the simplest way to offer/consume web services in jython? | 115,744 | <p>I have an application for Tomcat which needs to offer/consume web services. Since Java web services are a nightmare (xml, code generation, etc.) compared with what is possible in Python, I would like to learn from your experience using jython instead of java for offerring/consuming web services.</p>
<p>What I have done so far involves adapting <a href="http://pywebsvcs.sourceforge.net/">http://pywebsvcs.sourceforge.net/</a> to <a href="http://www.jython.org">Jython</a>. I still get errors (namespaces, types and so), although some of it is succesful for the simplest services.</p>
| 5 | 2008-09-22T16:01:52Z | 116,027 | <p><a href="http://www.jython.org/docs/api/org/python/util/PyServlet.html" rel="nofollow">PyServlet</a> helps you configure Tomcat to serve up Jython scripts from a URL. You could use this is a "REST-like" way to do some basic web services without much effort. (It is also described <a href="http://www.informit.com/articles/article.aspx?p=26865&seqNum=6" rel="nofollow">here</a>.) </p>
<p>We used a similar home grown framework to provide a variety of data services in a large multiple web application very successfully.</p>
| 0 | 2008-09-22T16:46:13Z | [
"python",
"web-services",
"soap",
"wsdl",
"jython"
] |
What is the simplest way to offer/consume web services in jython? | 115,744 | <p>I have an application for Tomcat which needs to offer/consume web services. Since Java web services are a nightmare (xml, code generation, etc.) compared with what is possible in Python, I would like to learn from your experience using jython instead of java for offerring/consuming web services.</p>
<p>What I have done so far involves adapting <a href="http://pywebsvcs.sourceforge.net/">http://pywebsvcs.sourceforge.net/</a> to <a href="http://www.jython.org">Jython</a>. I still get errors (namespaces, types and so), although some of it is succesful for the simplest services.</p>
| 5 | 2008-09-22T16:01:52Z | 148,455 | <p>I've put together more details on how to use webservices in jython using axis. Read about it here: <a href="http://www.fishandcross.com/blog/?p=503" rel="nofollow">How To Script Webservices with Jython and Axis</a>.</p>
| 2 | 2008-09-29T12:23:43Z | [
"python",
"web-services",
"soap",
"wsdl",
"jython"
] |
Which is more pythonic, factory as a function in a module, or as a method on the class it creates? | 115,764 | <p>I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file.</p>
<p>The calendar object just has a method that adds events as they get parsed.</p>
<p>Now I want to create a factory function that creates a calendar from a file object, path, or URL.</p>
<p>I've been using the <a href="http://codespeak.net/icalendar/" rel="nofollow">iCalendar python module</a>, which implements a factory function as a class method directly on the Class that it returns an instance of:</p>
<pre><code>cal = icalendar.Calendar.from_string(data)
</code></pre>
<p>From what little I know about Java, this is a common pattern in Java code, though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from.</p>
<p>The question is, is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ?</p>
| 3 | 2008-09-22T16:03:41Z | 115,777 | <p>It's pythonic not to think about esoteric difference in some pattern you read somewhere and now want to use everywhere, like the factory pattern.</p>
<p>Most of the time you would think of a @staticmethod as a solution it's probably better to use a module function, except when you stuff multiple classes in one module and each has a different implementation of the same interface, then it's better to use a @staticmethod</p>
<p>Ultimately weather you create your instances by a @staticmethod or by module function makes little difference.</p>
<p>I'd probably use the initializer ( __init__ ) of a class because one of the more accepted "patterns" in python is that the factory for a class is the class initialization.</p>
| 6 | 2008-09-22T16:05:25Z | [
"python",
"factory"
] |
Which is more pythonic, factory as a function in a module, or as a method on the class it creates? | 115,764 | <p>I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file.</p>
<p>The calendar object just has a method that adds events as they get parsed.</p>
<p>Now I want to create a factory function that creates a calendar from a file object, path, or URL.</p>
<p>I've been using the <a href="http://codespeak.net/icalendar/" rel="nofollow">iCalendar python module</a>, which implements a factory function as a class method directly on the Class that it returns an instance of:</p>
<pre><code>cal = icalendar.Calendar.from_string(data)
</code></pre>
<p>From what little I know about Java, this is a common pattern in Java code, though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from.</p>
<p>The question is, is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ?</p>
| 3 | 2008-09-22T16:03:41Z | 115,802 | <p>The factory pattern has its own <a href="http://en.wikipedia.org/wiki/Factory_method_pattern" rel="nofollow">strengths and weaknesses</a>. However, choosing one way to create instances usually has little pragmatic effect on your code.</p>
| 0 | 2008-09-22T16:09:45Z | [
"python",
"factory"
] |
Which is more pythonic, factory as a function in a module, or as a method on the class it creates? | 115,764 | <p>I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file.</p>
<p>The calendar object just has a method that adds events as they get parsed.</p>
<p>Now I want to create a factory function that creates a calendar from a file object, path, or URL.</p>
<p>I've been using the <a href="http://codespeak.net/icalendar/" rel="nofollow">iCalendar python module</a>, which implements a factory function as a class method directly on the Class that it returns an instance of:</p>
<pre><code>cal = icalendar.Calendar.from_string(data)
</code></pre>
<p>From what little I know about Java, this is a common pattern in Java code, though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from.</p>
<p>The question is, is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ?</p>
| 3 | 2008-09-22T16:03:41Z | 115,807 | <p>IMHO a module-level method is a cleaner solution. It hides behind the Python module system that gives it a unique namespace prefix, something the "factory pattern" is commonly used for. </p>
| 2 | 2008-09-22T16:11:52Z | [
"python",
"factory"
] |
Which is more pythonic, factory as a function in a module, or as a method on the class it creates? | 115,764 | <p>I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file.</p>
<p>The calendar object just has a method that adds events as they get parsed.</p>
<p>Now I want to create a factory function that creates a calendar from a file object, path, or URL.</p>
<p>I've been using the <a href="http://codespeak.net/icalendar/" rel="nofollow">iCalendar python module</a>, which implements a factory function as a class method directly on the Class that it returns an instance of:</p>
<pre><code>cal = icalendar.Calendar.from_string(data)
</code></pre>
<p>From what little I know about Java, this is a common pattern in Java code, though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from.</p>
<p>The question is, is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ?</p>
| 3 | 2008-09-22T16:03:41Z | 115,853 | <p>[<strong>Note</strong>. Be very cautious about separating "Calendar" a collection of events, and "Event" - a single event on a calendar. In your question, it seems like there could be some confusion.]</p>
<p>There are many variations on the Factory design pattern.</p>
<ol>
<li><p>A stand-alone convenience function (e.g., calendarMaker(data))</p></li>
<li><p>A separate class (e.g., CalendarParser) which builds your target class (Calendar).</p></li>
<li><p>A class-level method (e.g. Calendar.from_string) method.</p></li>
</ol>
<p>These have different purposes. All are Pythonic, the questions are "what do you <em>mean</em>?" and "what's likely to change?" Meaning is everything; change is important.</p>
<p>Convenience functions are Pythonic. Languages like Java can't have free-floating functions; you must wrap a lonely function in a class. Python allows you to have a lonely function without the overhead of a class. A function is relevant when your constructor has no state changes or alternate strategies or any memory of previous actions. </p>
<p>Sometimes folks will define a class and then provide a convenience function that makes an instance of the class, sets the usual parameters for state and strategy and any other configuration, and then calls the single relevant method of the class. This gives you both the statefulness of class plus the flexibility of a stand-alone function.</p>
<p>The class-level method pattern is used, but it has limitations. One, it's forced to rely on class-level variables. Since these can be confusing, a complex constructor as a static method runs into problems when you need to add features (like statefulness or alternative strategies.) Be sure you're never going to expand the static method.</p>
<p>Two, it's more-or-less irrelevant to the rest of the class methods and attributes. This kind of <code>from_string</code> is just one of many alternative encodings for your Calendar objects. You might have a <code>from_xml</code>, <code>from_JSON</code>, <code>from_YAML</code> and on and on. None of this has the least relevance to what a Calendar IS or what it DOES. These methods are all about how a Calendar is encoded for transmission.</p>
<p>What you'll see in the mature Python libraries is that factories are separate from the things they create. Encoding (as strings, XML, JSON, YAML) is subject to a great deal of more-or-less random change. The essential thing, however, rarely changes.</p>
<p>Separate the two concerns. Keep encoding and representation as far away from state and behavior as you can.</p>
| 11 | 2008-09-22T16:20:38Z | [
"python",
"factory"
] |
Which is more pythonic, factory as a function in a module, or as a method on the class it creates? | 115,764 | <p>I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file.</p>
<p>The calendar object just has a method that adds events as they get parsed.</p>
<p>Now I want to create a factory function that creates a calendar from a file object, path, or URL.</p>
<p>I've been using the <a href="http://codespeak.net/icalendar/" rel="nofollow">iCalendar python module</a>, which implements a factory function as a class method directly on the Class that it returns an instance of:</p>
<pre><code>cal = icalendar.Calendar.from_string(data)
</code></pre>
<p>From what little I know about Java, this is a common pattern in Java code, though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from.</p>
<p>The question is, is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ?</p>
| 3 | 2008-09-22T16:03:41Z | 115,933 | <p>A staticmethod rarely has value, but a classmethod may be useful. It depends on what you want the class and the factory function to actually do.</p>
<p>A factory function in a module would always make an instance of the 'right' type (where 'right' in your case is the 'Calendar' class always, but you might also make it dependant on the contents of what it is creating the instance out of.)</p>
<p>Use a classmethod if you wish to make it dependant not on the data, but on the class you call it on. A classmethod is like a staticmethod in that you can call it on the class, without an instance, but it receives the class it was called on as first argument. This allows you to actually create an instance of <em>that class</em>, which may be a subclass of the original class. An example of a classmethod is dict.fromkeys(), which creates a dict from a list of keys and a single value (defaulting to None.) Because it's a classmethod, when you subclass dict you get the 'fromkeys' method entirely for free. Here's an example of how one could write dict.fromkeys() oneself:</p>
<pre><code>class dict_with_fromkeys(dict):
@classmethod
def fromkeys(cls, keys, value=None):
self = cls()
for key in keys:
self[key] = value
return self
</code></pre>
| 0 | 2008-09-22T16:30:48Z | [
"python",
"factory"
] |
How do I configure the ip address with CherryPy? | 115,773 | <p>I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 but not through the IP or the windows machine name. It could be a machine configuration difference or a newer version of CherryPy or Python. Any ideas how I can bind to the correct IP address?</p>
<p>Edit: to make it clear, I currently don't have a config file at all.</p>
| 15 | 2008-09-22T16:04:54Z | 115,826 | <p>That depends on how you are running the cherrypy init.</p>
<p>If using cherrypy 3.1 syntax, that wold do it:</p>
<pre><code>cherrypy.server.socket_host = 'www.machinename.com'
cherrypy.engine.start()
cherrypy.engine.block()
</code></pre>
<p>Of course you can have something more fancy, like subclassing the server class, or using config files. Those uses are covered in <a href="http://www.cherrypy.org/wiki/ServerAPI">the documentation</a>.</p>
<p>But that should be enough. If not just tell us what you are doing and cherrypy version, and I will edit this answer.</p>
| 13 | 2008-09-22T16:16:12Z | [
"python",
"cherrypy"
] |
How do I configure the ip address with CherryPy? | 115,773 | <p>I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 but not through the IP or the windows machine name. It could be a machine configuration difference or a newer version of CherryPy or Python. Any ideas how I can bind to the correct IP address?</p>
<p>Edit: to make it clear, I currently don't have a config file at all.</p>
| 15 | 2008-09-22T16:04:54Z | 152,012 | <pre><code>server.socket_host: '0.0.0.0'
</code></pre>
<p>...would also work. That's IPv4 INADDR_ANY, which means, "listen on all interfaces".</p>
<p>In a config file, the syntax is:</p>
<pre><code>[global]
server.socket_host: '0.0.0.0'
</code></pre>
<p>In code:</p>
<pre><code>cherrypy.server.socket_host = '0.0.0.0'
</code></pre>
| 29 | 2008-09-30T06:55:25Z | [
"python",
"cherrypy"
] |
Convert mysql timestamp to epoch time in python | 115,866 | <p>Convert mysql timestamp to epoch time in python - is there an easy way to do this?</p>
| 6 | 2008-09-22T16:22:16Z | 115,903 | <p>Why not let MySQL do the hard work?</p>
<p>select unix_timestamp(fieldname) from tablename;</p>
| 24 | 2008-09-22T16:26:51Z | [
"python",
"mysql",
"time",
"timestamp"
] |
Convert mysql timestamp to epoch time in python | 115,866 | <p>Convert mysql timestamp to epoch time in python - is there an easy way to do this?</p>
| 6 | 2008-09-22T16:22:16Z | 118,236 | <p>If you don't want to have MySQL do the work for some reason, then you can do this in Python easily enough. When you get a datetime column back from MySQLdb, you get a Python datetime.datetime object. To convert one of these, you can use time.mktime. For example:</p>
<pre><code>import time
# Connecting to database skipped (also closing connection later)
c.execute("SELECT my_datetime_field FROM my_table")
d = c.fetchone()[0]
print time.mktime(d.timetuple())
</code></pre>
| 3 | 2008-09-22T23:34:51Z | [
"python",
"mysql",
"time",
"timestamp"
] |
Convert mysql timestamp to epoch time in python | 115,866 | <p>Convert mysql timestamp to epoch time in python - is there an easy way to do this?</p>
| 6 | 2008-09-22T16:22:16Z | 126,034 | <p>I use something like the following to get seconds since the epoch (UTC) from a MySQL date (local time):</p>
<pre><code>calendar.timegm(
time.gmtime(
time.mktime(
time.strptime(t,
"%Y-%m-%d %H:%M:%S"))))
</code></pre>
<p>More info in this question: <a href="http://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python">http://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python</a></p>
| 1 | 2008-09-24T08:30:00Z | [
"python",
"mysql",
"time",
"timestamp"
] |
Convert mysql timestamp to epoch time in python | 115,866 | <p>Convert mysql timestamp to epoch time in python - is there an easy way to do this?</p>
| 6 | 2008-09-22T16:22:16Z | 2,407,400 | <p>converting mysql time to epoch:</p>
<pre><code>>>> import time
>>> import calendar
>>> mysql_time = "2010-01-02 03:04:05"
>>> mysql_time_struct = time.strptime(mysql_time, '%Y-%m-%d %H:%M:%S')
>>> print mysql_time_struct
(2010, 1, 2, 3, 4, 5, 5, 2, -1)
>>> mysql_time_epoch = calendar.timegm(mysql_time_struct)
>>> print mysql_time_epoch
1262401445
</code></pre>
<p>converting epoch to something MySQL can use:</p>
<pre><code>>>> import time
>>> time_epoch = time.time()
>>> print time_epoch
1268121070.7
>>> time_struct = time.gmtime(time_epoch)
>>> print time_struct
(2010, 3, 9, 7, 51, 10, 1, 68, 0)
>>> time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time_struct)
>>> print time_formatted
2010-03-09 07:51:10
</code></pre>
| 7 | 2010-03-09T07:51:59Z | [
"python",
"mysql",
"time",
"timestamp"
] |
What would be the simplest way to daemonize a python script in Linux? | 115,974 | <p>What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. </p>
| 10 | 2008-09-22T16:39:09Z | 115,985 | <p><a href="http://en.wikipedia.org/wiki/Nohup" rel="nofollow">nohup</a> </p>
<p><a href="http://code.activestate.com/recipes/278731/" rel="nofollow">Creating a daemon the Python way</a></p>
| 4 | 2008-09-22T16:41:18Z | [
"python",
"scripting",
"daemon"
] |
What would be the simplest way to daemonize a python script in Linux? | 115,974 | <p>What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. </p>
| 10 | 2008-09-22T16:39:09Z | 116,035 | <p>See <a href="http://www.kohala.com/start/">Stevens</a> and also this <a href="http://code.activestate.com/recipes/278731/">lengthy thread on activestate</a> which I found personally to be both mostly incorrect and much to verbose, and I came up with this:</p>
<pre><code>from os import fork, setsid, umask, dup2
from sys import stdin, stdout, stderr
if fork(): exit(0)
umask(0)
setsid()
if fork(): exit(0)
stdout.flush()
stderr.flush()
si = file('/dev/null', 'r')
so = file('/dev/null', 'a+')
se = file('/dev/null', 'a+', 0)
dup2(si.fileno(), stdin.fileno())
dup2(so.fileno(), stdout.fileno())
dup2(se.fileno(), stderr.fileno())
</code></pre>
<p>If you need to stop that process again, it is required to know the pid, the usual solution to this is pidfiles. Do this if you need one</p>
<pre><code>from os import getpid
outfile = open(pid_file, 'w')
outfile.write('%i' % getpid())
outfile.close()
</code></pre>
<p>For security reasons you might consider any of these after demonizing</p>
<pre><code>from os import setuid, setgid, chdir
from pwd import getpwnam
from grp import getgrnam
setuid(getpwnam('someuser').pw_uid)
setgid(getgrnam('somegroup').gr_gid)
chdir('/')
</code></pre>
<p>You could also use <a href="http://en.wikipedia.org/wiki/Nohup">nohup</a> but that does not work well with <a href="http://docs.python.org/lib/module-subprocess.html">python's subprocess module</a></p>
| 20 | 2008-09-22T16:47:31Z | [
"python",
"scripting",
"daemon"
] |
What would be the simplest way to daemonize a python script in Linux? | 115,974 | <p>What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. </p>
| 10 | 2008-09-22T16:39:09Z | 116,081 | <p>Use <a href="http://www.clapper.org/software/python/grizzled/" rel="nofollow">grizzled.os.daemonize</a>:</p>
<pre><code>$ easy_install grizzled
>>> from grizzled.os import daemonize
>>> daemon.daemonize()
</code></pre>
<p>To understand how this works or to do it yourself, read <a href="http://code.activestate.com/recipes/278731/" rel="nofollow">the discussion on ActiveState</a>.</p>
| 0 | 2008-09-22T16:57:14Z | [
"python",
"scripting",
"daemon"
] |
What would be the simplest way to daemonize a python script in Linux? | 115,974 | <p>What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. </p>
| 10 | 2008-09-22T16:39:09Z | 117,176 | <p>If you do not care for actual discussions (which tend to go offtopic and do not offer authoritative response), you can choose some library that will make your tast easier. I'd recomment taking a look at <a href="http://www.livinglogic.de/Python/Download.html" rel="nofollow">ll-xist</a>, this library contains large amount of life-saving code, like cron jobs helper, daemon framework, and (what is not interesting to you, but is really great) <em>object-oriented XSL</em> (ll-xist itself).</p>
| 1 | 2008-09-22T19:58:20Z | [
"python",
"scripting",
"daemon"
] |
What would be the simplest way to daemonize a python script in Linux? | 115,974 | <p>What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. </p>
| 10 | 2008-09-22T16:39:09Z | 3,606,303 | <p>I have recently used <a href="http://pypi.python.org/pypi/Turkmenbashi/1.0.0.01" rel="nofollow">Turkmenbashi</a> :</p>
<pre><code>$ easy_install turkmenbashi
import Turkmenbashi
class DebugDaemon (Turkmenbashi.Daemon):
def config(self):
self.debugging = True
def go(self):
self.debug('a debug message')
self.info('an info message')
self.warn('a warning message')
self.error('an error message')
self.critical('a critical message')
if __name__=="__main__":
d = DebugDaemon()
d.config()
d.setenv(30, '/var/run/daemon.pid', '/tmp', None)
d.start(d.go)
</code></pre>
| 2 | 2010-08-31T05:43:08Z | [
"python",
"scripting",
"daemon"
] |
Using Pylint with Django | 115,977 | <p>I would very much like to integrate <a href="http://www.logilab.org/857">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
| 89 | 2008-09-22T16:39:34Z | 116,025 | <p>Because of how pylint works (it examines the source itself, without letting Python actually execute it) it's very hard for pylint to figure out how metaclasses and complex baseclasses actually affect a class and its instances. The 'pychecker' tool is a bit better in this regard, because it <em>does</em> actually let Python execute the code; it imports the modules and examines the resulting objects. However, that approach has other problems, because it does actually let Python execute the code :-)</p>
<p>You could extend pylint to teach it about the magic Django uses, or to make it understand metaclasses or complex baseclasses better, or to just ignore such cases after detecting one or more features it doesn't quite understand. I don't think it would be particularly easy. You can also just tell pylint to not warn about these things, through special comments in the source, command-line options or a .pylintrc file.</p>
| 15 | 2008-09-22T16:46:00Z | [
"python",
"django",
"static-analysis",
"pylint"
] |
Using Pylint with Django | 115,977 | <p>I would very much like to integrate <a href="http://www.logilab.org/857">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
| 89 | 2008-09-22T16:39:34Z | 116,047 | <p>Try running pylint with</p>
<pre><code>pylint --ignored-classes=Tags
</code></pre>
<p>If that works, add all the other Django classes - possibly using a script, in say, python :P </p>
<p>The documentation for <code>--ignore-classes</code> is:</p>
<blockquote>
<p><code>--ignored-classes=<members names></code><br />
List of classes names for which member
attributes should not be checked
(useful for classes with attributes
dynamicaly set). [current: %default]</p>
</blockquote>
<p>I should add this is not a particular elegant solution in my view, but it should work.</p>
| 5 | 2008-09-22T16:50:09Z | [
"python",
"django",
"static-analysis",
"pylint"
] |
Using Pylint with Django | 115,977 | <p>I would very much like to integrate <a href="http://www.logilab.org/857">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
| 89 | 2008-09-22T16:39:34Z | 117,299 | <p>I resigned from using pylint/pychecker in favor of using pyflakes with Django code - it just tries to import module and reports any problem it finds, like unused imports or uninitialized local names.</p>
| 6 | 2008-09-22T20:12:40Z | [
"python",
"django",
"static-analysis",
"pylint"
] |
Using Pylint with Django | 115,977 | <p>I would very much like to integrate <a href="http://www.logilab.org/857">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
| 89 | 2008-09-22T16:39:34Z | 118,375 | <p>This is not a solution, but you can add <code>objects = models.Manager()</code> to your Django models without changing any behavior.</p>
<p>I myself only use pyflakes, primarily due to some dumb defaults in pylint and laziness on my part (not wanting to look up how to change the defaults).</p>
| 7 | 2008-09-23T00:17:58Z | [
"python",
"django",
"static-analysis",
"pylint"
] |
Using Pylint with Django | 115,977 | <p>I would very much like to integrate <a href="http://www.logilab.org/857">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
| 89 | 2008-09-22T16:39:34Z | 410,860 | <p>So far I have found no real solution to that but work around:</p>
<ul>
<li>In our company we require a pylint
score > 8. This allows coding
practices pylint doesn't understand
while ensuring that the code isn't
too "unusual". So far we havn't seen
any instance where E1101 kept us
from reaching a score of 8 or
higher.</li>
<li>Our 'make check' targets
filter out "for has no 'objects'
member" messages to remove most of
the distraction caused by pylint not
understanding Django.</li>
</ul>
| 2 | 2009-01-04T11:37:48Z | [
"python",
"django",
"static-analysis",
"pylint"
] |
Using Pylint with Django | 115,977 | <p>I would very much like to integrate <a href="http://www.logilab.org/857">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
| 89 | 2008-09-22T16:39:34Z | 1,416,297 | <p>I use the following: <code>pylint --generated-members=objects</code></p>
| 59 | 2009-09-12T22:21:47Z | [
"python",
"django",
"static-analysis",
"pylint"
] |
Using Pylint with Django | 115,977 | <p>I would very much like to integrate <a href="http://www.logilab.org/857">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
| 89 | 2008-09-22T16:39:34Z | 2,456,436 | <p>django-lint is a nice tool which wraps pylint with django specific settings : <a href="http://chris-lamb.co.uk/projects/django-lint/" rel="nofollow">http://chris-lamb.co.uk/projects/django-lint/</a> </p>
<p>github project: <a href="https://github.com/lamby/django-lint" rel="nofollow">https://github.com/lamby/django-lint</a></p>
| 18 | 2010-03-16T17:00:16Z | [
"python",
"django",
"static-analysis",
"pylint"
] |
Using Pylint with Django | 115,977 | <p>I would very much like to integrate <a href="http://www.logilab.org/857">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
| 89 | 2008-09-22T16:39:34Z | 4,162,971 | <p>My ~/.pylintrc contains</p>
<pre><code>[TYPECHECK]
generated-members=REQUEST,acl_users,aq_parent,objects,_meta,id
</code></pre>
<p>the last two are specifically for Django.</p>
<p>Note that there is a <a href="http://www.logilab.org/ticket/28796">bug in PyLint 0.21.1</a> which needs patching to make this work.</p>
<p>Edit: After messing around with this a little more, I decided to hack PyLint just a tiny bit to allow me to expand the above into:</p>
<pre><code>[TYPECHECK]
generated-members=REQUEST,acl_users,aq_parent,objects,_meta,id,[a-zA-Z]+_set
</code></pre>
<p>I simply added:</p>
<pre><code> import re
for pattern in self.config.generated_members:
if re.match(pattern, node.attrname):
return
</code></pre>
<p>after the fix mentioned in the bug report (i.e., at line 129).</p>
<p>Happy days!</p>
| 27 | 2010-11-12T08:59:11Z | [
"python",
"django",
"static-analysis",
"pylint"
] |
Using Pylint with Django | 115,977 | <p>I would very much like to integrate <a href="http://www.logilab.org/857">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
| 89 | 2008-09-22T16:39:34Z | 5,104,874 | <p>The solution proposed in this <a href="http://stackoverflow.com/questions/3509599/can-an-api-tell-pylint-not-to-complain-in-the-client-code">other question</a> it to simply add <strong>get_attr</strong> to your Tag class. Ugly, but works.</p>
| 2 | 2011-02-24T12:48:37Z | [
"python",
"django",
"static-analysis",
"pylint"
] |
Using Pylint with Django | 115,977 | <p>I would very much like to integrate <a href="http://www.logilab.org/857">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
| 89 | 2008-09-22T16:39:34Z | 31,000,713 | <p>Do not disable or weaken Pylint functionality by adding <code>ignores</code> or <code>generated-members</code>.<br>
Use an actively developed Pylint plugin that <strong>understands</strong> Django.<br>
<a href="https://github.com/landscapeio/pylint-django">This Pylint plugin for Django</a> works quite well:</p>
<pre><code>pip install pylint-django
</code></pre>
<p>and when running pylint add the following flag to the command:</p>
<pre><code>--load-plugins pylint_django
</code></pre>
<p>Detailed blog post <a href="https://blog.landscape.io/using-pylint-on-django-projects-with-pylint-django.html">here</a>.</p>
| 31 | 2015-06-23T10:47:45Z | [
"python",
"django",
"static-analysis",
"pylint"
] |
How can I search a word in a Word 2007 .docx file? | 116,139 | <p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
| 40 | 2008-09-22T17:08:12Z | 116,194 | <p>A docx is just a zip archive with lots of files inside. Maybe you can look at some of the contents of those files? Other than that you probably have to find a lib that understands the word format so that you can filter out things you're not interested in.</p>
<p>A second choice would be to interop with word and do the search through it.</p>
| 4 | 2008-09-22T17:16:43Z | [
"python",
"ms-word",
"openxml",
"docx"
] |
How can I search a word in a Word 2007 .docx file? | 116,139 | <p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
| 40 | 2008-09-22T17:08:12Z | 116,197 | <p>a docx file is essentially a zip file with an xml inside it.<br />
the xml contains the formatting but it also contains the text.</p>
| 2 | 2008-09-22T17:17:15Z | [
"python",
"ms-word",
"openxml",
"docx"
] |
How can I search a word in a Word 2007 .docx file? | 116,139 | <p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
| 40 | 2008-09-22T17:08:12Z | 116,199 | <p>You should be able to use the MSWord ActiveX interface to extract the text to search (or, possibly, do the search). I have no idea how you access ActiveX from Python though.</p>
| 0 | 2008-09-22T17:17:26Z | [
"python",
"ms-word",
"openxml",
"docx"
] |
How can I search a word in a Word 2007 .docx file? | 116,139 | <p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
| 40 | 2008-09-22T17:08:12Z | 116,217 | <p>More exactly, a .docx document is a Zip archive in OpenXML format: you have first to uncompress it.<br />
I downloaded a sample (Google: <em>some search term filetype:docx</em>) and after unzipping I found some folders. The <em>word</em> folder contains the document itself, in file <em>document.xml</em>.</p>
| 30 | 2008-09-22T17:22:10Z | [
"python",
"ms-word",
"openxml",
"docx"
] |
How can I search a word in a Word 2007 .docx file? | 116,139 | <p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
| 40 | 2008-09-22T17:08:12Z | 118,136 | <p>OLE Automation would probably be the easiest. You have to consider formatting, because the text could look like this in the XML:</p>
<pre><code><b>Looking <i>for</i> this <u>phrase</u>
</code></pre>
<p>There's no easy way to find that using a simple text scan.</p>
| 1 | 2008-09-22T23:03:32Z | [
"python",
"ms-word",
"openxml",
"docx"
] |
How can I search a word in a Word 2007 .docx file? | 116,139 | <p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
| 40 | 2008-09-22T17:08:12Z | 118,175 | <p>In this example, "Course Outline.docx" is a Word 2007 document, which does contain the word "Windows", and does not contain the phrase "random other string".</p>
<pre><code>>>> import zipfile
>>> z = zipfile.ZipFile("Course Outline.docx")
>>> "Windows" in z.read("word/document.xml")
True
>>> "random other string" in z.read("word/document.xml")
False
>>> z.close()
</code></pre>
<p>Basically, you just open the docx file (which is a zip archive) using <a href="http://docs.python.org/lib/module-zipfile.html">zipfile</a>, and find the content in the 'document.xml' file in the 'word' folder. If you wanted to be more sophisticated, you could then <a href="http://docs.python.org/lib/module-xml.etree.ElementTree.html">parse the XML</a>, but if you're just looking for a phrase (which you know won't be a tag), then you can just look in the XML for the string.</p>
| 14 | 2008-09-22T23:12:59Z | [
"python",
"ms-word",
"openxml",
"docx"
] |
How can I search a word in a Word 2007 .docx file? | 116,139 | <p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
| 40 | 2008-09-22T17:08:12Z | 138,231 | <p><a href="http://www.codeproject.com/KB/WPF/OpenFlowDoc.aspx?msg=2740533#xx2740533xx" rel="nofollow">Here</a> is a example of using XLINQ to search throu a word document</p>
| 0 | 2008-09-26T08:03:35Z | [
"python",
"ms-word",
"openxml",
"docx"
] |
How can I search a word in a Word 2007 .docx file? | 116,139 | <p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
| 40 | 2008-09-22T17:08:12Z | 215,479 | <p>You may also consider using the library from <a href="http://openxmldeveloper.org/default.aspx" rel="nofollow">OpenXMLDeveloper.org</a></p>
| 0 | 2008-10-18T19:34:32Z | [
"python",
"ms-word",
"openxml",
"docx"
] |
How can I search a word in a Word 2007 .docx file? | 116,139 | <p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
| 40 | 2008-09-22T17:08:12Z | 1,737,242 | <p>A problem with searching inside a Word document XML file is that the text can be split into elements at any character. It will certainly be split if formatting is different, for example as in Hello <strong>World</strong>. But it <em>can</em> be split at any point and that is valid in OOXML. So you will end up dealing with XML like this even if formatting does not change in the middle of the phrase!</p>
<pre><code><w:p w:rsidR="00C07F31" w:rsidRDefault="003F6D7A">
<w:r w:rsidRPr="003F6D7A">
<w:rPr>
<w:b />
</w:rPr>
<w:t>Hello</w:t>
</w:r>
<w:r>
<w:t xml:space="preserve">World.</w:t>
</w:r>
</w:p>
</code></pre>
<p>You can of course load it into an XML DOM tree (not sure what this will be in Python) and ask to get text only as a string, but you could end up with many other "dead ends" just because the OOXML spec is around 6000 pages long and MS Word can write lots of "stuff" you don't expect. So you could end up writing your own document processing library.</p>
<p>Or you can try using <a href="http://www.aspose.com/categories/.net-components/aspose.words-for-.net/default.aspx">Aspose.Words</a>. </p>
<p>It is available as .NET and Java products. Both can be used from Python. One via COM Interop another via JPype. See Aspose.Words Programmers Guide, Utilize Aspose.Words in Other Programming Languages (sorry I can't post a second link, stackoverflow does not let me yet).</p>
| 13 | 2009-11-15T11:01:08Z | [
"python",
"ms-word",
"openxml",
"docx"
] |
How can I search a word in a Word 2007 .docx file? | 116,139 | <p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
| 40 | 2008-09-22T17:08:12Z | 1,979,864 | <p>After reading your post above, I made a 100% native Python docx module to solve this specific problem.</p>
<pre><code># Import the module
from docx import *
# Open the .docx file
document = opendocx('A document.docx')
# Search returns true if found
search(document,'your search string')
</code></pre>
<p>The docx module is at <a href="https://python-docx.readthedocs.org/en/latest/">https://python-docx.readthedocs.org/en/latest/</a></p>
| 127 | 2009-12-30T12:08:33Z | [
"python",
"ms-word",
"openxml",
"docx"
] |
How can I search a word in a Word 2007 .docx file? | 116,139 | <p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
| 40 | 2008-09-22T17:08:12Z | 27,377,115 | <p>You can use <code>docx2txt</code> to get the text inside the docx, than search in that txt</p>
<pre><code>npm install -g docx2txt
docx2txt input.docx # This will print the text to stdout
</code></pre>
| 3 | 2014-12-09T10:51:23Z | [
"python",
"ms-word",
"openxml",
"docx"
] |
Subsets and Splits