title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Python String Cleanup + Manipulation (Accented Characters) | 930,303 | <p>I have a database full of names like:</p>
<pre><code>John Smith
Scott J. Holmes
Dr. Kaplan
Ray's Dog
Levi's
Adrian O'Brien
Perry Sean Smyre
Carie Burchfield-Thompson
Björn Ãrnason
</code></pre>
<p>There are a few foreign names with accents in them that need to be converted to strings with non-accented characters.</p>
<p>I'd like to convert the full names (after stripping characters like " ' " , "-") to user logins like:</p>
<pre><code>john.smith
scott.j.holmes
dr.kaplan
rays.dog
levis
adrian.obrien
perry.sean.smyre
carie.burchfieldthompson
bjorn.arnason
</code></pre>
<p>So far I have:</p>
<pre><code>Fullname.strip() # get rid of leading/trailing white space
Fullname.lower() # make everything lower case
... # after bad chars converted/removed
Fullname.replace(' ', '.') # replace spaces with periods
</code></pre>
| 5 | 2009-05-30T18:36:16Z | 931,051 | <p>The following function is generic:</p>
<pre><code>import unicodedata
def not_combining(char):
return unicodedata.category(char) != 'Mn'
def strip_accents(text, encoding):
unicode_text= unicodedata.normalize('NFD', text.decode(encoding))
return filter(not_combining, unicode_text).encode(encoding)
# in a cp1252 environment
>>> print strip_accents("déjà ", "cp1252")
deja
# in a cp1253 environment
>>> print strip_accents("καλημÎÏα", "cp1253")
καλημεÏα
</code></pre>
<p>Obviously, you should know the encoding of your strings.</p>
| 3 | 2009-05-31T01:43:14Z | [
"python",
"regex",
"unicode",
"string"
] |
Python String Cleanup + Manipulation (Accented Characters) | 930,303 | <p>I have a database full of names like:</p>
<pre><code>John Smith
Scott J. Holmes
Dr. Kaplan
Ray's Dog
Levi's
Adrian O'Brien
Perry Sean Smyre
Carie Burchfield-Thompson
Björn Ãrnason
</code></pre>
<p>There are a few foreign names with accents in them that need to be converted to strings with non-accented characters.</p>
<p>I'd like to convert the full names (after stripping characters like " ' " , "-") to user logins like:</p>
<pre><code>john.smith
scott.j.holmes
dr.kaplan
rays.dog
levis
adrian.obrien
perry.sean.smyre
carie.burchfieldthompson
bjorn.arnason
</code></pre>
<p>So far I have:</p>
<pre><code>Fullname.strip() # get rid of leading/trailing white space
Fullname.lower() # make everything lower case
... # after bad chars converted/removed
Fullname.replace(' ', '.') # replace spaces with periods
</code></pre>
| 5 | 2009-05-30T18:36:16Z | 1,333,215 | <p>If you are not afraid to install third-party modules, then have a look at the <a href="http://www.tablix.org/~avian/blog/archives/2009/01/unicode_transliteration_in_python/" rel="nofollow">python port of the Perl module <code>Text::Unidecode</code></a> (it's also <a href="http://pypi.python.org/pypi/Unidecode" rel="nofollow">on pypi</a>).</p>
<p>The module does nothing more than use a lookup table to transliterate the characters. I glanced over the code and it looks very simple. So I suppose it's working on pretty much any OS and on any Python version (crossingfingers). It's also easy to bundle with your application.</p>
<p>With this module you don't have to create your lookup table manually ( = reduced risk it being incomplete).</p>
<p>The advantage of this module compared to the unicode normalization technique is this: Unicode normalization does not replace all characters. A good example is a character like "æ". Unicode normalisation will see it as "Letter, lowercase" (Ll). This means using the <code>normalize</code> method will give you neither a replacement character nor a useful hint. Unfortunately, that character is not representable in ASCII. So you'll get errors.</p>
<p>The mentioned <a href="http://www.tablix.org/~avian/blog/archives/2009/01/unicode_transliteration_in_python/" rel="nofollow">module</a> does a better job at this. This will actually replace the "æ" with "ae". Which is actually useful and makes sense.</p>
<p>The most impressive thing I've seen is that it goes much further. It even replaces Japanese Kana characters <em>mostly</em> properly. For example, it replaces "ã¯" with "ha". Wich is perfectly fine. <strike>It's not fool-proof though as the current version replaces "ã¡" with "ti" instead of "chi". So you'll have to handle it with care for the more exotic characters.</strike></p>
<p>Usage of the module is straightforward::</p>
<pre><code>from unidecode import unidecode
var_utf8 = "æã¯".decode("utf8")
unidecode( var_utf8 ).encode("ascii")
>>> "aeha"
</code></pre>
<p>Note that I have nothing to do with this module directly. It just happens that I find it very useful.</p>
<p><strong>Edit:</strong> The patch I submitted fixed the bug concerning the Japanese kana. I've only fixed the one's I could spot right away. I may have missed some.</p>
| 5 | 2009-08-26T08:36:53Z | [
"python",
"regex",
"unicode",
"string"
] |
Getting the last element of a list in Python | 930,397 | <p>In Python, how do you get the last element of a list?</p>
| 826 | 2009-05-30T19:28:53Z | 930,398 | <p><code>some_list[-1]</code> is the shortest and most Pythonic.</p>
<p>In fact, you can do much more with this syntax. The <code>some_list[-n]</code> syntax gets the nth-to-last element. So <code>some_list[-1]</code> gets the last element, <code>some_list[-2]</code> gets the second to last, etc, all the way down to <code>some_list[-len(some_list)]</code>, which gives you the first element.</p>
<p>You can also set list elements in this way. For instance:</p>
<pre><code>>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]
</code></pre>
| 1,347 | 2009-05-30T19:29:55Z | [
"python",
"list",
"indexing"
] |
Getting the last element of a list in Python | 930,397 | <p>In Python, how do you get the last element of a list?</p>
| 826 | 2009-05-30T19:28:53Z | 930,759 | <p>You can also do:</p>
<pre><code>alist.pop()
</code></pre>
<p>It depends on what you want to do with your list because the <code>pop()</code> method will delete the last element.</p>
| 49 | 2009-05-30T22:21:08Z | [
"python",
"list",
"indexing"
] |
Getting the last element of a list in Python | 930,397 | <p>In Python, how do you get the last element of a list?</p>
| 826 | 2009-05-30T19:28:53Z | 4,139,773 | <p>If your str() or list() objects might end up being empty as so: <code>astr = ''</code> or <code>alist = []</code>, then you might want to use <code>alist[-1:]</code> instead of <code>alist[-1]</code> for object "sameness".</p>
<p>The significance of this is:</p>
<pre><code>alist = []
alist[-1] # will generate an IndexError exception whereas
alist[-1:] # will return an empty list
astr = ''
astr[-1] # will generate an indexError excepttion whereas
astr[-1:] # will return an empty str
</code></pre>
<p>Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.</p>
| 116 | 2010-11-09T23:26:38Z | [
"python",
"list",
"indexing"
] |
Getting the last element of a list in Python | 930,397 | <p>In Python, how do you get the last element of a list?</p>
| 826 | 2009-05-30T19:28:53Z | 12,042,371 | <p>The simplest way to display last element in python is</p>
<pre><code>>>> list[-1:] # returns indexed value
[3]
>>> list[-1] # returns value
3
</code></pre>
<p>there are many other method to achieve such a goal but these are short and sweet to use.</p>
| 32 | 2012-08-20T17:41:54Z | [
"python",
"list",
"indexing"
] |
Getting the last element of a list in Python | 930,397 | <p>In Python, how do you get the last element of a list?</p>
| 826 | 2009-05-30T19:28:53Z | 31,620,887 | <pre><code>popes = ['john paul II', 'benedict XIV', 'francis I']
current_pope = []
for pope in popes:
current_pope = pope
</code></pre>
<p>after the for loop you'll get last item in current_pope variable.</p>
| -8 | 2015-07-24T22:45:23Z | [
"python",
"list",
"indexing"
] |
Getting the last element of a list in Python | 930,397 | <p>In Python, how do you get the last element of a list?</p>
| 826 | 2009-05-30T19:28:53Z | 32,998,601 | <p>Ok, but what about common in almost every language way <code>items[len(items) - 1]</code>? This is IMO the easiest way to get last element, because it does not require anything <em>pythonic</em> knowledge.</p>
| -1 | 2015-10-07T17:22:04Z | [
"python",
"list",
"indexing"
] |
Getting the last element of a list in Python | 930,397 | <p>In Python, how do you get the last element of a list?</p>
| 826 | 2009-05-30T19:28:53Z | 34,705,384 | <blockquote>
<p>some_list = [1, 2, 3]</p>
</blockquote>
<p>Method 1:</p>
<pre><code>some_list[-1]
</code></pre>
<p>Method 2:</p>
<pre><code>**some_list.reverse()**
**some_list[0]**
</code></pre>
<p>Method 3:</p>
<pre><code>some_list.pop()
</code></pre>
| 5 | 2016-01-10T12:32:06Z | [
"python",
"list",
"indexing"
] |
Getting the last element of a list in Python | 930,397 | <p>In Python, how do you get the last element of a list?</p>
| 826 | 2009-05-30T19:28:53Z | 39,908,383 | <p><code>list[-1]</code> will retrieve the last element of the list without changing the list.
<code>list.pop()</code> will retrieve the last element of the list, but it will mutate/change the original list. Usually, mutating the original list is not recommended.</p>
<p>Alternatively, if, for some reason, you're looking for something less pythonic, you could use <code>list[len(list)-1]</code>, assuming the list is not empty.</p>
| 0 | 2016-10-07T02:21:23Z | [
"python",
"list",
"indexing"
] |
How to run one last function before getting killed in Python? | 930,519 | <p>Is there any way to run one last command before a running Python script is stopped by being killed by some other script, keyboard interrupt etc.</p>
<p>Thanks for your help!</p>
| 16 | 2009-05-30T20:22:53Z | 930,521 | <pre><code>import signal
import sys
import time
def cleanup(*args):
print 'Exiting'
sys.exit(0)
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
while True:
time.sleep(60) # less busy loop
</code></pre>
| 6 | 2009-05-30T20:24:34Z | [
"python",
"function",
"interrupt",
"quit"
] |
How to run one last function before getting killed in Python? | 930,519 | <p>Is there any way to run one last command before a running Python script is stopped by being killed by some other script, keyboard interrupt etc.</p>
<p>Thanks for your help!</p>
| 16 | 2009-05-30T20:22:53Z | 930,537 | <pre><code>import time
try:
time.sleep(10)
finally:
print "clean up"
clean up
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
</code></pre>
<p>If you need to catch other OS level interrupts, look at the signal module:</p>
<p><a href="http://docs.python.org/library/signal.html">http://docs.python.org/library/signal.html</a></p>
<h3>Signal Example</h3>
<pre><code>from signal import *
import sys, time
def clean(*args):
print "clean me"
sys.exit(0)
for sig in (SIGABRT, SIGBREAK, SIGILL, SIGINT, SIGSEGV, SIGTERM):
signal(sig, clean)
time.sleep(10)
</code></pre>
| 28 | 2009-05-30T20:29:50Z | [
"python",
"function",
"interrupt",
"quit"
] |
How to run one last function before getting killed in Python? | 930,519 | <p>Is there any way to run one last command before a running Python script is stopped by being killed by some other script, keyboard interrupt etc.</p>
<p>Thanks for your help!</p>
| 16 | 2009-05-30T20:22:53Z | 930,542 | <p>I think that you could use the <code>atexit</code> module. With it, you can register a function which will be called at program termination. An example from here: <a href="http://docs.python.org/library/atexit.html">http://docs.python.org/library/atexit.html</a></p>
<pre><code>try:
_count = int(open("/tmp/counter").read())
except IOError:
_count = 0
def incrcounter(n):
global _count
_count = _count + n
def savecounter():
open("/tmp/counter", "w").write("%d" % _count)
import atexit
atexit.register(savecounter)
</code></pre>
<p>You can also pass positional and keyword parameters to the function you want to call at program termination.</p>
| 8 | 2009-05-30T20:32:14Z | [
"python",
"function",
"interrupt",
"quit"
] |
How to run one last function before getting killed in Python? | 930,519 | <p>Is there any way to run one last command before a running Python script is stopped by being killed by some other script, keyboard interrupt etc.</p>
<p>Thanks for your help!</p>
| 16 | 2009-05-30T20:22:53Z | 930,545 | <p>Use the atexit module to register a function that will be called at the end.</p>
<pre><code>import atexit
atexit.register(some_function)
</code></pre>
| 3 | 2009-05-30T20:32:20Z | [
"python",
"function",
"interrupt",
"quit"
] |
How to run one last function before getting killed in Python? | 930,519 | <p>Is there any way to run one last command before a running Python script is stopped by being killed by some other script, keyboard interrupt etc.</p>
<p>Thanks for your help!</p>
| 16 | 2009-05-30T20:22:53Z | 34,575,239 | <p>WIth apologies to 'Unknown' for taking their answer and correcting it as though it was my own answer, but my edits were rejected.</p>
<p>The approved answer contains an error that will cause a segfault.</p>
<p>You cannot use sys.exit() in a signal handler, but you can use os._exit so that it becomes:</p>
<pre><code>from signal import *
import os, time
def clean(*args):
print "clean me"
os._exit(0)
for sig in (SIGABRT, SIGINT, SIGTERM):
signal(sig, clean)
time.sleep(10)
</code></pre>
<p>SIGBREAK may be used if the target platform is Windows.</p>
<p>Depending on the use case and the need to cleanup in the event of fatal errors - you may add SIGSEGV and SIGILL but generally this is not advised since the program state may be such that you create an infinite loop.</p>
| 3 | 2016-01-03T09:55:32Z | [
"python",
"function",
"interrupt",
"quit"
] |
Python AppEngine; get user info and post parameters? | 930,578 | <p>Im checking the examples google gives on how to start using python; especifically the code posted here; <a href="http://code.google.com/appengine/docs/python/gettingstarted/usingdatastore.html" rel="nofollow">http://code.google.com/appengine/docs/python/gettingstarted/usingdatastore.html</a></p>
<p>The thing that i want to lean is that, here:</p>
<pre><code>class Guestbook(webapp.RequestHandler):
def post(self):
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get('content')
greeting.put()
self.redirect('/')
</code></pre>
<p>They are saving a comment, IF the user is logged in, we save the user; if not its empty and when we get it out of the db we actually check for that here:</p>
<pre><code> if greeting.author:
self.response.out.write('<b>%s</b> wrote:' % greeting.author.nickname())
else:
self.response.out.write('An anonymous person wrote:')
</code></pre>
<p>So what i would like is to use the User object to get the information, like this:</p>
<pre><code>class Guestbook(webapp.RequestHandler):
def post(self):
user = users.get_current_user()
if user:
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get('content')
greeting.put()
self.redirect('/')
else:
self.redirect(users.create_login_url(self.request.uri))
</code></pre>
<p>So, what i would like to do with that code is to send the user to the login url(if he is not logged in); and then to come back with whatever he had in post and actually post it. But what happens is that it doesnt even get to that action coz is nothing in the post.
I know i could put something in the session and check for it in the get action of the guestbook, but i wanted to check if someone could come up with a better solution!</p>
<p>Thanks</p>
| 2 | 2009-05-30T20:48:40Z | 931,034 | <p>The problem is, <code>self.redirect</code> cannot "carry along" the payload of a <code>POST</code> HTTP request, so (from a <code>post</code> method) the redirection to the login-url &c is going to misbehave (in fact I believe the login URL will use <code>get</code> to continue when it's done, and that there's no way to ask it to do a <code>post</code> instead).</p>
<p>If you don't want to stash that <code>POST</code> payload around somewhere (session or otherwise), you can make your code work by changing the <code>def post</code> in your snippet above to <code>def get</code>, and of course the <code>action="post"</code> in the HTML written in other parts of the example that you haven't snipped to <code>action="get"</code>. There are other minor workarounds (you could accept <code>post</code> for "normal" messages from logged-in users and redirect them to the <code>get</code> that perhaps does something simpler if they weren't logged in yet), but I think this info is sufficient to help you continue from here, right?</p>
| 3 | 2009-05-31T01:33:47Z | [
"python",
"google-app-engine"
] |
Django Shell shortcut in Windows | 930,641 | <p>I'm trying to write a bat file so I can quickly launch into the Interactive Shell for one of my Django projects.</p>
<p>Basically I need to write a python script that can launch "manage.py shell" and then be able to print from mysite.myapp.models import *</p>
<p>The problem is manage.py shell cannot take additional arguments and launching into "manage.py shell" exits the parent script, so I am unable to then execute additional commands.</p>
| 0 | 2009-05-30T21:12:42Z | 930,910 | <p>First download django-extensions from google code. search for "django command-extensions"</p>
<p>Download and install it by running setup.py install from within the folder (it has a file called "setup.py")
You will then be able to run manage.py shell_plus instead of manage.py shell, giving you an enhanced version of the python shell which will load all your models automatically</p>
<p>Now the batch file:
make a new file "run_django.bat" on your desktop (for instance), then enter to it</p>
<pre><code>@echo off
cd [path/to/project]
manage.py shell_plus
</code></pre>
<p>save the file. anytime you click it, it will start your shell with all your models loaded</p>
| 2 | 2009-05-31T00:09:29Z | [
"python",
"django",
"command-line",
"windows-xp",
"batch-file"
] |
Python & parsing IRC messages | 930,700 | <p>What's the best way to parse messages received from an IRC server with Python according to the RFC? I simply want some kind of list/whatever, for example:</p>
<pre><code>:test!~test@test.com PRIVMSG #channel :Hi!
</code></pre>
<p>becomes this:</p>
<pre><code>{ "sender" : "test!~test@test.com", "target" : "#channel", "message" : "Hi!" }
</code></pre>
<p>And so on?</p>
<p>(Edit: I want to parse IRC messages in <strong>general</strong>, not just PRIVMSG's)</p>
| 6 | 2009-05-30T21:51:58Z | 930,706 | <p>Look at Twisted's implementation <a href="http://twistedmatrix.com/">http://twistedmatrix.com/</a></p>
<p>Unfortunately I'm out of time, maybe someone else can paste it here for you.</p>
<h3>Edit</h3>
<p>Well I'm back, and strangely no one has pasted it yet so here it is:</p>
<p><a href="http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/irc.py#54">http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/irc.py#54</a></p>
<pre><code>def parsemsg(s):
"""Breaks a message from an IRC server into its prefix, command, and arguments.
"""
prefix = ''
trailing = []
if not s:
raise IRCBadMessage("Empty line.")
if s[0] == ':':
prefix, s = s[1:].split(' ', 1)
if s.find(' :') != -1:
s, trailing = s.split(' :', 1)
args = s.split()
args.append(trailing)
else:
args = s.split()
command = args.pop(0)
return prefix, command, args
parsemsg(":test!~test@test.com PRIVMSG #channel :Hi!")
# ('test!~test@test.com', 'PRIVMSG', ['#channel', 'Hi!'])
</code></pre>
<p>This function closely follows the EBNF described in the IRC RFC.</p>
| 16 | 2009-05-30T21:58:04Z | [
"python",
"parsing",
"irc"
] |
Python & parsing IRC messages | 930,700 | <p>What's the best way to parse messages received from an IRC server with Python according to the RFC? I simply want some kind of list/whatever, for example:</p>
<pre><code>:test!~test@test.com PRIVMSG #channel :Hi!
</code></pre>
<p>becomes this:</p>
<pre><code>{ "sender" : "test!~test@test.com", "target" : "#channel", "message" : "Hi!" }
</code></pre>
<p>And so on?</p>
<p>(Edit: I want to parse IRC messages in <strong>general</strong>, not just PRIVMSG's)</p>
| 6 | 2009-05-30T21:51:58Z | 930,767 | <p>You can do it with a simple list comprehension if the format is always like this.</p>
<pre><code>keys = ['sender', 'type', 'target', 'message']
s = ":test!~test@test.com PRIVMSG #channel :Hi!"
dict((key, value.lstrip(':')) for key, value in zip(keys, s.split()))
</code></pre>
<p>Result:</p>
<pre><code>{'message': 'Hi!', 'type': 'PRIVMSG', 'sender': 'test!~test@test.com', 'target': '#channel'}
</code></pre>
| 1 | 2009-05-30T22:26:11Z | [
"python",
"parsing",
"irc"
] |
Python & parsing IRC messages | 930,700 | <p>What's the best way to parse messages received from an IRC server with Python according to the RFC? I simply want some kind of list/whatever, for example:</p>
<pre><code>:test!~test@test.com PRIVMSG #channel :Hi!
</code></pre>
<p>becomes this:</p>
<pre><code>{ "sender" : "test!~test@test.com", "target" : "#channel", "message" : "Hi!" }
</code></pre>
<p>And so on?</p>
<p>(Edit: I want to parse IRC messages in <strong>general</strong>, not just PRIVMSG's)</p>
| 6 | 2009-05-30T21:51:58Z | 930,806 | <p>Do you just want to parse IRC Messages in general or do you want just parse PRIVMSGs? However I have a implementation for that.</p>
<pre><code>def parse_message(s):
prefix = ''
trailing = ''
if s.startswith(':'):
prefix, s = s[1:].split(' ', 1)
if ' :' in s:
s, trailing = s.split(' :', 1)
args = s.split()
return prefix, args.pop(0), args, trailing
</code></pre>
| 0 | 2009-05-30T22:44:01Z | [
"python",
"parsing",
"irc"
] |
Python & parsing IRC messages | 930,700 | <p>What's the best way to parse messages received from an IRC server with Python according to the RFC? I simply want some kind of list/whatever, for example:</p>
<pre><code>:test!~test@test.com PRIVMSG #channel :Hi!
</code></pre>
<p>becomes this:</p>
<pre><code>{ "sender" : "test!~test@test.com", "target" : "#channel", "message" : "Hi!" }
</code></pre>
<p>And so on?</p>
<p>(Edit: I want to parse IRC messages in <strong>general</strong>, not just PRIVMSG's)</p>
| 6 | 2009-05-30T21:51:58Z | 931,274 | <p>If you want to keep to a low-level hacking I second the Twisted answer by Unknown, but first I think you should take a look at the very recently announced <strong><a href="http://zork.net/motd/nick/django/introducing-yardbird.html" rel="nofollow">Yardbird</a></strong> which is a nice request parsing layer on top of Twisted. It lets you use something similar to Django URL dispatching for handling IRC messages with a side benefit of having the Django ORM available for generating responses, etc.</p>
| 0 | 2009-05-31T04:37:44Z | [
"python",
"parsing",
"irc"
] |
Python & parsing IRC messages | 930,700 | <p>What's the best way to parse messages received from an IRC server with Python according to the RFC? I simply want some kind of list/whatever, for example:</p>
<pre><code>:test!~test@test.com PRIVMSG #channel :Hi!
</code></pre>
<p>becomes this:</p>
<pre><code>{ "sender" : "test!~test@test.com", "target" : "#channel", "message" : "Hi!" }
</code></pre>
<p>And so on?</p>
<p>(Edit: I want to parse IRC messages in <strong>general</strong>, not just PRIVMSG's)</p>
| 6 | 2009-05-30T21:51:58Z | 2,288,155 | <p>I know it's not Python, but for a regular expression-based approach to this problem, you could take a look at <a href="http://github.com/bingos/poe-filter-ircd/blob/master/lib/POE/Filter/IRCD.pm" rel="nofollow">POE::Filter::IRCD</a>, which handles IRC server protocol (see <a href="http://github.com/bingos/poe-component-irc/blob/master/lib/POE/Filter/IRC/Compat.pm" rel="nofollow">POE::Filter::IRC::Compat</a> for the client protocol additions) parsing for Perl's <a href="http://github.com/bingos/poe-component-irc" rel="nofollow">POE::Component::IRC</a> framework.</p>
| 0 | 2010-02-18T11:21:55Z | [
"python",
"parsing",
"irc"
] |
Python regex - conditional matching? | 930,834 | <p>I don't know if that's the right word for it, but I am trying to come up with some regex's that can extract coefficients and exponents from a mathematical expression. The expression will come in the form 'axB+cxD+exF' where the lower case letters are the coefficients and the uppercase letters are the exponents. I have a regex that can match to both of them, but I'm wondering if I can use 2 regexs, one to match the coefficients and one for the exponents. Is there a way to match a number with a letter on one side of it without matching the letter? EG, in '3x3+6x2+2x1+8x0' I need to get
['3', '6', '2', '8']
and
['3', '2', '1', '0']</p>
| 0 | 2009-05-30T23:09:58Z | 930,841 | <pre><code>>>> import re
>>> equation = '3x3+6x2+2x1+8x0'
>>> re.findall(r'x([0-9]+)', equation)
['3', '2', '1', '0']
>>> re.findall(r'([0-9]+)x', equation)
['3', '6', '2', '8']
</code></pre>
| 1 | 2009-05-30T23:14:51Z | [
"python",
"regex"
] |
Python regex - conditional matching? | 930,834 | <p>I don't know if that's the right word for it, but I am trying to come up with some regex's that can extract coefficients and exponents from a mathematical expression. The expression will come in the form 'axB+cxD+exF' where the lower case letters are the coefficients and the uppercase letters are the exponents. I have a regex that can match to both of them, but I'm wondering if I can use 2 regexs, one to match the coefficients and one for the exponents. Is there a way to match a number with a letter on one side of it without matching the letter? EG, in '3x3+6x2+2x1+8x0' I need to get
['3', '6', '2', '8']
and
['3', '2', '1', '0']</p>
| 0 | 2009-05-30T23:09:58Z | 930,849 | <p>You can use <a href="http://www.regular-expressions.info/lookaround.html#lookahead" rel="nofollow">positive look-ahead</a> to match something that is followed by something else. To match the coefficients, you can use:</p>
<pre><code>>>> s = '3x3+6x2+2x1+8x0'
>>> re.findall(r'\d+(?=x)', s)
['3', '6', '2', '8']
</code></pre>
<p>From the documentation of the <a href="http://docs.python.org/library/re.html" rel="nofollow"><code>re</code></a> module:</p>
<blockquote>
<p>(?=...)
Matches if ... matches next, but doesnât consume any of the string.
This is called a lookahead assertion.
For example, Isaac (?=Asimov) will
match 'Isaac ' only if itâs followed
by 'Asimov'.</p>
</blockquote>
<p>For the exponents, you can use <a href="http://www.regular-expressions.info/lookaround.html#lookbehind" rel="nofollow">positive look-behind</a> instead:</p>
<pre><code>>>> s = '3x3+6x2+2x1+8x0'
>>> re.findall(r'(?<=x)\d+', s)
['3', '2', '1', '0']
</code></pre>
<p>Again, from the docs:</p>
<blockquote>
<p>(?<=...) Matches if the current position in the string is preceded by a match for
... that ends at the current position.
This is called a positive lookbehind
assertion. (?<=abc)def will find a
match in abcdef, since the lookbehind
will back up 3 characters and check if
the contained pattern matches.</p>
</blockquote>
| 5 | 2009-05-30T23:22:25Z | [
"python",
"regex"
] |
Python regex - conditional matching? | 930,834 | <p>I don't know if that's the right word for it, but I am trying to come up with some regex's that can extract coefficients and exponents from a mathematical expression. The expression will come in the form 'axB+cxD+exF' where the lower case letters are the coefficients and the uppercase letters are the exponents. I have a regex that can match to both of them, but I'm wondering if I can use 2 regexs, one to match the coefficients and one for the exponents. Is there a way to match a number with a letter on one side of it without matching the letter? EG, in '3x3+6x2+2x1+8x0' I need to get
['3', '6', '2', '8']
and
['3', '2', '1', '0']</p>
| 0 | 2009-05-30T23:09:58Z | 930,873 | <p>Yet another way to do it, without regex: </p>
<pre><code>>>> eq = '3x3+6x2+2x1+8x0'
>>> op = eq.split('+')
['3x3', '6x2', '2x1', '8x0']
>>> [o.split('x')[0] for o in op]
['3', '6', '2', '8']
>>> [o.split('x')[1] for o in op]
['3', '2', '1', '0']
</code></pre>
| 1 | 2009-05-30T23:39:36Z | [
"python",
"regex"
] |
Referencing another project | 930,857 | <p>In a simple program I made, I wanted to get a list from another project and access the elements from it. Since I'm new to python, I don't really have any idea what to do. In my project, I checked the box for the project name I wanted to reference and... I don't know what to do. A few google searched did me no good, so I'm hoping someone here can tell/link me how to set this up.</p>
| 2 | 2009-05-30T23:28:44Z | 930,879 | <p>Use import. Then you can access the "module" (project) and everything in it like an object./</p>
<pre><code># a.py
some_list = [1,2,3,4]
# b.py
import a
print a.some_list
</code></pre>
<p>If you run b.py, it will print [1,2,3,4]</p>
| 2 | 2009-05-30T23:44:31Z | [
"python"
] |
Referencing another project | 930,857 | <p>In a simple program I made, I wanted to get a list from another project and access the elements from it. Since I'm new to python, I don't really have any idea what to do. In my project, I checked the box for the project name I wanted to reference and... I don't know what to do. A few google searched did me no good, so I'm hoping someone here can tell/link me how to set this up.</p>
| 2 | 2009-05-30T23:28:44Z | 930,880 | <p>Generally if you have some code in <code>project1.py</code> and then want to use it from a different file in the same directory, you can import <code>project1</code> as a module:</p>
<pre><code>import project1
data = project1.my_data_function()
</code></pre>
<p>This works just the same way as you would import any module form the standard library.</p>
| 1 | 2009-05-30T23:44:36Z | [
"python"
] |
how to sort by a computed value in django | 930,865 | <p>Hey I want to sort objects based on a computed value in django... how do I do it?</p>
<p>Here is an example User profile model based on stack overflow that explains my predicament:</p>
<pre><code>class Profile(models.Model):
user = models.ForeignKey(User)
def get_reputation():
...
return reputation
reputation = property(get_reputation)
</code></pre>
<p>So, say I want to sort users by reputation. How do I do that? I know you can't just do this:</p>
<pre><code>Profile.objects.order_by("-reputation")
</code></pre>
<p>Thanks for your help everyone :)</p>
| 5 | 2009-05-30T23:34:20Z | 930,894 | <p>Since your calculation code exists only within Python, you have to perform the sorting in Python as well:</p>
<pre><code>sorted (Profile.objects.all (), key = lambda p: p.reputation)
</code></pre>
| 16 | 2009-05-30T23:54:29Z | [
"python",
"django",
"web-applications",
"sorting",
"django-models"
] |
how to sort by a computed value in django | 930,865 | <p>Hey I want to sort objects based on a computed value in django... how do I do it?</p>
<p>Here is an example User profile model based on stack overflow that explains my predicament:</p>
<pre><code>class Profile(models.Model):
user = models.ForeignKey(User)
def get_reputation():
...
return reputation
reputation = property(get_reputation)
</code></pre>
<p>So, say I want to sort users by reputation. How do I do that? I know you can't just do this:</p>
<pre><code>Profile.objects.order_by("-reputation")
</code></pre>
<p>Thanks for your help everyone :)</p>
| 5 | 2009-05-30T23:34:20Z | 931,048 | <p>If you need to do the sorting in the database (because you have lots of records, and need to e.g. paginate them), the only real option is to turn reputation into a denormalized field (e.g. updated in an overridden <code>save()</code> method on the model).</p>
| 3 | 2009-05-31T01:41:57Z | [
"python",
"django",
"web-applications",
"sorting",
"django-models"
] |
how to sort by a computed value in django | 930,865 | <p>Hey I want to sort objects based on a computed value in django... how do I do it?</p>
<p>Here is an example User profile model based on stack overflow that explains my predicament:</p>
<pre><code>class Profile(models.Model):
user = models.ForeignKey(User)
def get_reputation():
...
return reputation
reputation = property(get_reputation)
</code></pre>
<p>So, say I want to sort users by reputation. How do I do that? I know you can't just do this:</p>
<pre><code>Profile.objects.order_by("-reputation")
</code></pre>
<p>Thanks for your help everyone :)</p>
| 5 | 2009-05-30T23:34:20Z | 33,516,286 | <p>As of Django-1.8, it is possible to sort a QuerySet using <a href="https://docs.djangoproject.com/en/1.8/ref/models/expressions/" rel="nofollow">query expressions</a> as long as the computed value can be rendered in SQL. You can also use <a href="https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#order-by" rel="nofollow"><code>annotations</code></a> to the model as the <a href="https://docs.djangoproject.com/en/1.8/ref/models/querysets/#order-by" rel="nofollow"><code>order_by</code></a> term.</p>
<pre><code>from django.db.models import F
Profile.objects.annotate(reputation=(F('<field>') + ...)).order_by("-reputation")
</code></pre>
<p>Basic operations like <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> and <code>**</code> can be used with <code>F()</code>. In addition there are several other functions such as <code>Count</code>, <code>Avg</code>, <code>Max</code>, ...</p>
<p>Links:</p>
<ul>
<li><a href="https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#order-by" rel="nofollow">Aggregation - <code>order_by</code></a></li>
<li><a href="https://docs.djangoproject.com/en/1.8/topics/db/queries/#filters-can-reference-fields-on-the-model" rel="nofollow">Making Queries - filters can reference fields on a model</a></li>
<li><a href="https://docs.djangoproject.com/en/1.8/ref/models/expressions/#built-in-expressions" rel="nofollow">Query Expressions - Built in Expressions</a></li>
</ul>
<p>See also this SO Q&A: <a href="http://stackoverflow.com/a/476033/1020470">Order a QuerySet by aggregate field value</a></p>
| 2 | 2015-11-04T07:44:10Z | [
"python",
"django",
"web-applications",
"sorting",
"django-models"
] |
assertEquals vs. assertEqual in python | 930,995 | <p>Is there a difference between <code>assertEquals</code> and <code>assertEqual</code> in the python <code>unittest.TestCase</code>?</p>
<p>And if there is not, why are there two functions? Only for convenience? </p>
| 105 | 2009-05-31T01:07:03Z | 931,005 | <p>I don't find any mention of assertEquals in <a href="http://docs.python.org/library/unittest.html" rel="nofollow">http://docs.python.org/library/unittest.html</a>. However, when I import TestCase and then do a "help(TestCase)", it's listed. I think it's just a synonym for convenience.</p>
| 2 | 2009-05-31T01:14:37Z | [
"python",
"unit-testing"
] |
assertEquals vs. assertEqual in python | 930,995 | <p>Is there a difference between <code>assertEquals</code> and <code>assertEqual</code> in the python <code>unittest.TestCase</code>?</p>
<p>And if there is not, why are there two functions? Only for convenience? </p>
| 105 | 2009-05-31T01:07:03Z | 931,011 | <p>Good question!</p>
<p>Actually, in Python 2.6, both <code>assertEqual</code> and <code>assertEquals</code> are convenience aliases to <code>failUnlessEqual</code>. The source declares them thus: </p>
<pre><code> # Synonyms for assertion methods
assertEqual = assertEquals = failUnlessEqual
</code></pre>
<p>In <a href="http://docs.python.org/3/library/unittest.html#deprecated-aliases">Python 3</a>, to your point, <code>failUnlessEqual</code> is explicitly deprecated. <code>assertEquals</code> carries this comment :-)</p>
<blockquote>
<p># Synonyms for assertion methods</p>
<p># The plurals are undocumented. Keep them that way to discourage use.</p>
<p># Do not add more. Do not remove.</p>
<p># Going through a deprecation cycle on these would annoy many people.</p>
</blockquote>
<p>So, the upshot appears to be that you should use whatever you like for Python 2.x, but tend toward <code>assertEqual</code> for Python 3.</p>
| 121 | 2009-05-31T01:17:47Z | [
"python",
"unit-testing"
] |
assertEquals vs. assertEqual in python | 930,995 | <p>Is there a difference between <code>assertEquals</code> and <code>assertEqual</code> in the python <code>unittest.TestCase</code>?</p>
<p>And if there is not, why are there two functions? Only for convenience? </p>
| 105 | 2009-05-31T01:07:03Z | 937,144 | <p>I think this was tension between the "only one obvious way to do it" vs. "alias to make the overall code flow semantically". Personally I found I like to read</p>
<pre><code>failIf(some_condition)
</code></pre>
<p>over </p>
<pre><code>assertFalse(some_condition)
</code></pre>
<p>but liked</p>
<pre><code>assertEqual(a, b)
</code></pre>
<p>over the other two (<code>assertEquals(a, b)</code> bothers my sense of grammar).</p>
<p>The "only one obvious way to do it" has taken precedence going forward.</p>
| 4 | 2009-06-01T22:35:26Z | [
"python",
"unit-testing"
] |
assertEquals vs. assertEqual in python | 930,995 | <p>Is there a difference between <code>assertEquals</code> and <code>assertEqual</code> in the python <code>unittest.TestCase</code>?</p>
<p>And if there is not, why are there two functions? Only for convenience? </p>
| 105 | 2009-05-31T01:07:03Z | 21,993,198 | <p>A 3.3 update: From <a href="http://docs.python.org/3.3/library/unittest.html#deprecated-aliases">26.3.7.1.1. Deprecated aliases</a> :</p>
<blockquote>
<p>For historical reasons, some of the TestCase methods had one or more aliases that are now deprecated. The following table lists the correct names along with their deprecated aliases:</p>
</blockquote>
<pre><code>Method Name | Deprecated alias | Deprecated alias
--------------+------------------+-----------------
assertEqual() | failUnlessEqual | assertEquals
...
</code></pre>
| 21 | 2014-02-24T16:21:40Z | [
"python",
"unit-testing"
] |
assertEquals vs. assertEqual in python | 930,995 | <p>Is there a difference between <code>assertEquals</code> and <code>assertEqual</code> in the python <code>unittest.TestCase</code>?</p>
<p>And if there is not, why are there two functions? Only for convenience? </p>
| 105 | 2009-05-31T01:07:03Z | 27,852,282 | <p>Not just for Python 3.x, since Python 2.7 <code>assertEquals</code> has been deprecated as well:</p>
<pre><code>Method Name | Deprecated alias(es)
_________________________________________________________
assertEqual() | failUnlessEqual, assertEquals
</code></pre>
<p>From <a href="https://docs.python.org/2/library/unittest.html#deprecated-aliases">25.3.7.1.1. Deprecated aliases</a></p>
| 5 | 2015-01-09T00:58:59Z | [
"python",
"unit-testing"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 931,095 | <p>How about:</p>
<pre><code>>>> 'hello world'[::-1]
'dlrow olleh'
</code></pre>
<p>This is <a href="http://docs.python.org/2/whatsnew/2.3.html#extended-slices">extended slice</a> syntax. It works by doing <code>[begin:end:step]</code> - by leaving begin and end off and specifying a step of -1, it reverses a string.</p>
| 1,576 | 2009-05-31T02:11:46Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 931,099 | <p>@Paolo's <code>s[::-1]</code> is fastest; a slower approach (maybe more readable, but that's debatable) is <code>''.join(reversed(s))</code>.</p>
| 155 | 2009-05-31T02:13:54Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 26,828,946 | <pre><code>def reverse(st):
rev = ""
for i in range(0 ,len(st)):
rev += st[(len(st) -1) - i]
return rev
</code></pre>
| -2 | 2014-11-09T13:56:00Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 27,401,625 | <p>Reverse a string in python without using reversed() or [::-1]</p>
<pre><code>def reverse(test):
n = len(test)
x=""
for i in range(n-1,-1,-1):
x += test[i]
return x
</code></pre>
| 3 | 2014-12-10T12:57:22Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 27,843,760 | <blockquote>
<h1>What is the best way of implementing a reverse function for strings?</h1>
<p>There is no built-in reverse function in Python's str object. </p>
</blockquote>
<p>In my long illustrious career of being a programmer, I have never seen a practical need to reverse a string. So congratulations, you must be learning Python. </p>
<p>There's a couple of things about Python's strings you should know:</p>
<ol>
<li><p>In Python, <strong>strings are immutable</strong>. Changing a string does not modify the string. It creates a new one.</p></li>
<li><p>Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:</p>
<pre><code>string[subscript]
</code></pre></li>
</ol>
<p>The subscript creates a slice by including a colon within the braces:</p>
<pre><code> string[start:stop:step]
</code></pre>
<p>To create a slice outside of the braces, you'll need to create a slice object:</p>
<pre><code> slice_obj = slice(start, stop, step)
string[slice_obj]
</code></pre>
<h2>A readable approach:</h2>
<p>While <code>''.join(reversed('foo'))</code> is readable, it requires calling a string method, <code>str.join</code>, on another called function, which can be rather slow. Let's put this in a function - we'll come back to it:</p>
<pre><code>def reverse_string_readable_answer(string):
return ''.join(reversed(string))
</code></pre>
<h2>Most performant approach:</h2>
<p>Much faster is using a reverse slice:</p>
<pre><code>'foo'[::-1]
</code></pre>
<p>But how can we make this more readable and understandable to someone less familiar with the intent of the original author? Let's create a named slice object, and pass it to the subscript notation.</p>
<pre><code>start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]
</code></pre>
<h2>Implement as Function</h2>
<p>To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:</p>
<pre><code>def reversed_string(a_string):
return a_string[::-1]
</code></pre>
<p>And usage is simply:</p>
<pre><code>reversed_string('foo')
</code></pre>
<h2>What your teacher probably wants:</h2>
<p>If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:</p>
<pre><code>def reverse_a_string_slowly(a_string):
new_string = ''
index = len(a_string)
while index:
index -= 1 # index = index - 1
new_string += a_string[index] # new_string = new_string + character
return new_string
</code></pre>
<p>This is theoretically bad because, remember, <strong>strings are immutable</strong> - so every time where it looks like you're appending a character onto your <code>new_string</code>, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.</p>
<h2>Best Practice</h2>
<p>Theoretically better is to collect your substrings in a list, and join them later:</p>
<pre><code>def reverse_a_string_more_slowly(a_string):
new_strings = []
index = len(a_string)
while index:
index -= 1
new_strings.append(a_string[index])
return ''.join(new_strings)
</code></pre>
<p>However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.</p>
<h2>Timings</h2>
<p>Here are the timings:</p>
<pre><code>>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265
</code></pre>
<p>CPython optimizes string concatenation, whereas other implementations <a href="https://www.python.org/dev/peps/pep-0008/#programming-recommendations">may not</a>:</p>
<blockquote>
<p>... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations. </p>
</blockquote>
| 51 | 2015-01-08T15:32:55Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 30,035,731 | <p>Here is a no fancy one:</p>
<pre><code>def reverse(text):
r_text = ''
index = len(text) - 1
while index >= 0:
r_text += text[index] #string canbe concatenated
index -= 1
return r_text
print reverse("hello, world!")
</code></pre>
| 3 | 2015-05-04T17:02:51Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 31,064,900 | <pre><code>def reverse(input):
return reduce(lambda x,y : y+x, input)
</code></pre>
| 1 | 2015-06-26T04:25:59Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 33,457,266 | <h2>Quick Answer (TL;DR)</h2>
<h3>Example</h3>
<pre><code>### example01 -------------------
mystring = 'coup_ate_grouping'
backwards = mystring[::-1]
print backwards
### ... or even ...
mystring = 'coup_ate_grouping'[::-1]
print mystring
### result01 -------------------
'''
gnipuorg_eta_puoc
'''
</code></pre>
<h2>Detailed Answer</h2>
<h3>Background</h3>
<p>This answer is provided to address the following concern from a user odigity:</p>
<blockquote>
<p>Wow. I was horrified at first by the solution Paolo proposed, but that
took a back seat to the horror I felt upon reading the first
comment: "That's very pythonic. Good job!" I'm so disturbed that such
a bright community thinks using such cryptic methods for something so
basic is a good idea. Why isn't it just s.reverse()?</p>
</blockquote>
<h3>Problem</h3>
<ul>
<li><strong>Context</strong>
<ul>
<li>Python 2.x</li>
<li>Python 3.x</li>
</ul></li>
<li><strong>Scenario:</strong>
<ul>
<li>Developer wants to transform a string</li>
<li>Transformation is to reverse order of all the characters</li>
</ul></li>
</ul>
<h3>Solution</h3>
<ul>
<li>example01 produces the desired result, using <a href="https://docs.python.org/2/whatsnew/2.3.html?highlight=extended%20slice#extended-slices" rel="nofollow">extended slice notation</a>. </li>
</ul>
<h3>Pitfalls</h3>
<ul>
<li>Developer might expect something like <code>string.reverse()</code></li>
<li>The native idiomatic (aka "<a href="http://stackoverflow.com/a/25011492/42223">pythonic</a>") solution may not be readable to newer developers</li>
<li>Developer may be tempted to implement his or her own version of <code>string.reverse()</code> to avoid slice notation.</li>
<li>The output of slice notation may be counter-intuitive in some cases:
<ul>
<li>see e.g., example02
<ul>
<li><code>print 'coup_ate_grouping'[-4:] ## => 'ping'</code></li>
<li>compared to</li>
<li><code>print 'coup_ate_grouping'[-4:-1] ## => 'pin'</code></li>
<li>compared to</li>
<li><code>print 'coup_ate_grouping'[-1] ## => 'g'</code></li>
</ul></li>
<li>the different outcomes of indexing on <code>[-1]</code> may throw some developers off</li>
</ul></li>
</ul>
<h3>Rationale</h3>
<p>Python has a special circumstance to be aware of: a string is an <a href="https://docs.python.org/2/glossary.html#term-iterable" rel="nofollow">iterable</a> type.</p>
<p>One rationale for excluding a <code>string.reverse()</code> method is to give python developers incentive to leverage the power of this special circumstance.</p>
<p>In simplified terms, this simply means each individual character in a string can be easily operated on as a part of a sequential array of elements, just like arrays in other programming languages.</p>
<p>To understand how this works, reviewing example02 can provide a good overview.</p>
<h3>Example02</h3>
<pre><code>### example02 -------------------
## start (with positive integers)
print 'coup_ate_grouping'[0] ## => 'c'
print 'coup_ate_grouping'[1] ## => 'o'
print 'coup_ate_grouping'[2] ## => 'u'
## start (with negative integers)
print 'coup_ate_grouping'[-1] ## => 'g'
print 'coup_ate_grouping'[-2] ## => 'n'
print 'coup_ate_grouping'[-3] ## => 'i'
## start:end
print 'coup_ate_grouping'[0:4] ## => 'coup'
print 'coup_ate_grouping'[4:8] ## => '_ate'
print 'coup_ate_grouping'[8:12] ## => '_gro'
## start:end
print 'coup_ate_grouping'[-4:] ## => 'ping' (counter-intuitive)
print 'coup_ate_grouping'[-4:-1] ## => 'pin'
print 'coup_ate_grouping'[-4:-2] ## => 'pi'
print 'coup_ate_grouping'[-4:-3] ## => 'p'
print 'coup_ate_grouping'[-4:-4] ## => ''
print 'coup_ate_grouping'[0:-1] ## => 'coup_ate_groupin'
print 'coup_ate_grouping'[0:] ## => 'coup_ate_grouping' (counter-intuitive)
## start:end:step (or stop:end:stride)
print 'coup_ate_grouping'[-1::1] ## => 'g'
print 'coup_ate_grouping'[-1::-1] ## => 'gnipuorg_eta_puoc'
## combinations
print 'coup_ate_grouping'[-1::-1][-4:] ## => 'puoc'
</code></pre>
<h3>Conclusion</h3>
<p>The <a href="https://en.wikipedia.org/wiki/Cognitive_load" rel="nofollow">cognitive load</a> associated with understanding how slice notation works in python may indeed be too much for some adopters and developers who do not wish to invest much time in learning the language.</p>
<p>Nevertheless, once the basic principles are understood, the power of this approach over fixed string manipulation methods can be quite favorable.</p>
<p>For those who think otherwise, there are alternate approaches, such as lambda functions, iterators, or simple one-off function declarations.</p>
<p>If desired, a developer can implement her own string.reverse() method, however it is good to understand the rationale behind this "quirk" of python.</p>
<h3>See also</h3>
<ul>
<li><a href="http://stackoverflow.com/a/6238928/42223">alternate simple approach</a></li>
<li><a href="http://stackoverflow.com/a/766291/42223">alternate simple approach</a></li>
<li><a href="http://stackoverflow.com/questions/509211/explain-pythons-slice-notation">alternate explanation of slice notation</a> </li>
</ul>
| 12 | 2015-10-31T22:24:14Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 34,512,034 | <p>Here is one without <code>[::-1]</code> or <code>reversed</code> (for learning purposes):</p>
<pre><code>def reverse(text):
new_string = []
n = len(text)
while (n > 0):
new_string.append(text[n-1])
n -= 1
return ''.join(new_string)
print reverse("abcd")
</code></pre>
<p>you can use <code>+=</code> to concatenate strings but <code>join()</code> is faster. </p>
| 1 | 2015-12-29T13:23:57Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 35,174,761 | <p>Sure, in Python you can do very fancy 1-line stuff. :) <br>
Here's a simple, all rounder solution that could work in any programming language.</p>
<pre><code>def reverse_string(phrase):
reversed = ""
length = len(phrase)
for i in range(length):
reversed += phrase[length-1-i]
return reversed
phrase = raw_input("Provide a string: ")
print reverse_string(phrase)
</code></pre>
| 0 | 2016-02-03T10:40:43Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 35,247,129 | <pre><code>for i in list:
rev = (i[::-1])
reverse_list.append(rev)
</code></pre>
| -3 | 2016-02-06T22:14:15Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 36,207,493 | <pre><code>s = 'hello'
ln = len(s)
i = 1
while True:
rev = s[ln-i]
print rev,
i = i + 1
if i == ln + 1 :
break
</code></pre>
<p><strong>OUTPUT :</strong> </p>
<pre><code>o l l e h
</code></pre>
| 0 | 2016-03-24T18:28:53Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 36,350,837 | <p>A lesser perplexing way to look at it would be:</p>
<pre><code>string = 'happy'
print(string)
</code></pre>
<blockquote>
<p>'happy'</p>
</blockquote>
<pre><code>string_reversed = string[-1::-1]
print(string_reversed)
</code></pre>
<blockquote>
<p>'yppah'</p>
</blockquote>
<p>In English [-1::-1] reads as:</p>
<blockquote>
<p>"Starting at -1, go all the way, taking steps of -1"</p>
</blockquote>
| 1 | 2016-04-01T07:49:28Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 38,465,000 | <p>You can use the reversed function with a list comprehesive. But I don't understand why this method was eliminated in python 3, was unnecessarily. </p>
<pre><code>string = [ char for char in reversed(string)]
</code></pre>
| 0 | 2016-07-19T17:32:45Z | [
"python",
"string"
] |
Reverse a string in Python | 931,092 | <p>There is no built in <code>reverse</code> function in Python's <code>str</code> object. What is the best way of implementing this?</p>
<p>If supplying a very concise answer, please elaborate on it's efficiency. Is the <code>str</code> converted to a different object, etc. </p>
| 751 | 2009-05-31T02:10:10Z | 39,564,634 | <p>We can also implement a stack approach to this problem by using the built-in lists in python.</p>
<pre><code>def revstring(mystr):
revstr = ''
strList = []
for ch in mystr:
strList.append(ch)
while not strList == []:
revstr = revstr + strList .pop()
return revstr
print revstring('apple')
print revstring('apple') == 'apple'[::-1]
</code></pre>
| 0 | 2016-09-19T02:39:43Z | [
"python",
"string"
] |
Debug some Python code | 931,211 | <p>Edit: You can get the full source here: <a href="http://pastebin.com/m26693" rel="nofollow">http://pastebin.com/m26693</a></p>
<p>Edit again: I added some highlights to the pastebin page. <a href="http://pastebin.com/m10f8d239" rel="nofollow">http://pastebin.com/m10f8d239</a></p>
<p>I'm probably going to regret asking such a long question, but I'm stumped with this bug and I could use some guidance. You're going to have to run this code (edit: not anymore. I couldn't include all of the code -- it was truncated) to help in order to really see what's going on, unless you're God or something, then by all means figure it out without running it. Actually I kind of hope that I can explain it well enough so that's not necessary, and I do apologize if I don't accomplish that.</p>
<p>First I'll give you some output. (Edit: There's new output below)</p>
<pre><code>argc 1 [<__main__.RESULT instance at 0x94f91ec>]
(<__main__.RESULT instance at 0x9371f8c>, <__main__.RESULT instance at 0x94f91ec>)
None
bar
internal error: unknown result type 0
argc 1 [<__main__.RESULT instance at 0x94f92ac>]
(<__main__.RESULT instance at 0x94f91ac>, <__main__.RESULT instance at 0x94f92ac>)
None
bar
internal error: unknown result type 0
argc 1 [<__main__.RESULT instance at 0x94f91ec>]
(<__main__.RESULT instance at 0x94f91ec>,)
String: 'bar'
</code></pre>
<p>We have 3 divisions in the output. Notice that argc is always 1. At the point where that is printed, an argument list has been built to be passed to a plugin (Plugins are simply commands in the expression interpreter. Most of this code is the expression interpreter.) The list of a single RESULT instance representation that follows argc is the argument list. The next line is the argument list once it reaches the Python method being called. Notice it has two arguments at this point. The first of these two is trash. The second one is what I wanted. However, as you can see on the lines starting "argc 1" that argument list is always 1 RESULT wide. Where's the stray argument coming from?</p>
<p>Like I said, there are 3 divisions in the output. The first division is a class by itself. The second division is a subclassed class. And the third division is no class/instance at all. The only division that outputs what I expected is the 3rd. Notice it has 1 argument member both before the call and within the call, and the last line is the intended output. It simply echoes/returns the argument "bar". </p>
<p>Are there any peculiarities with variable argument lists that I should be aware of? What I mean is the following:</p>
<pre><code>def foo(result, *argv):
print argv[0]
</code></pre>
<p>I really think the bug has something to do with this, because that is where the trash seems to come from -- in between the call and the execution arrival in the method.</p>
<p>Edit: Ok, so they limit the size of these questions. :) I'll try my best to show what's going on. Here's the relevant part of EvalTree. Note that there's only 2 divisions in this code. I messed up that other file and deleted it.</p>
<pre><code>def EvalTree(self, Root):
type = -1
number = 0.0
freeme = 0
if Root.Token == T_NUMBER or Root.Token == T_STRING:
return 0
elif Root.Token == T_VARIABLE:
self.CopyResult(Root.Result, Root.Variable.value)
return 0
elif Root.Token == T_FUNCTION:
argc = Root.Children
param = resizeList([], argc, RESULT)
print "argc", argc
for i in range(argc):
self.EvalTree(Root.Child[i])
param[i] = Root.Child[i].Result
self.DelResult(Root.Result)
Root.Function.func(Root.Result, *param) # I should have never ever programmed Lua ever.
return 0
</code></pre>
<p>Here's the Plugin's class.</p>
<pre><code>class Foo:
def __init__(self, visitor):
visitor.AddFunction("foo", -1, self.foo)
def foo(self, result, *argv):
print argv
</code></pre>
<p>Here's where it's all executed.</p>
<pre><code>if __name__ == "__main__":
evaluator = Evaluator()
expression = "foo2('bar')"
#expression = "uptime('test')"
evaluator.SetVariableString("test", "Foo")
def func(self, result, *arg1):
print arg1
evaluator.SetResult(result, R_STRING, evaluator.R2S(arg1[0]))
evaluator.AddFunction('foo2', -1, func)
result = RESULT(0, 0, 0, None)
tree = evaluator.Compile(expression)
if tree != -1:
evaluator.Eval(tree, result)
if result.type == R_NUMBER:
print "Number: %g" % (evaluator.R2N(result))
elif result.type == R_STRING:
print "String: '%s'" % (result.string) #(evaluator.R2S(result))
elif result.type == (R_NUMBER | R_STRING):
print "String: '%s' Number: (%g)" % (evaluator.R2S(result), evaluator.R2N(result))
else:
print "internal error: unknown result type %d" % (result.type)
expression = "foo('test')"
result = RESULT(0, 0, 0, None)
tree = evaluator.Compile(expression)
if tree != -1:
evaluator.Eval(tree, result)
if result.type == R_NUMBER:
print "Number: %g" % (evaluator.R2N(result))
elif result.type == R_STRING:
print "String: '%s'" % (result.string) #(evaluator.R2S(result))
elif result.type == (R_NUMBER | R_STRING):
print "String: '%s' Number: (%g)" % (evaluator.R2S(result), evaluator.R2N(result))
else:
print "internal error: unknown result type %d" % (result.type)
</code></pre>
<p>This is the new output:</p>
<pre><code>argc 1
(<__main__.RESULT instance at 0x9ffcf4c>,)
String: 'bar'
argc 1
(<__main__.RESULT instance at 0xa0030cc>, <__main__.RESULT instance at 0xa0030ec>)
internal error: unknown result type 0
</code></pre>
| 0 | 2009-05-31T03:47:57Z | 931,229 | <p>It appears that your code was truncated, so I can't look through it.</p>
<p>Given that you only get the extra argument on methods defined in a class, though, might it be the <code>self</code> variable? Every method on a Python class receives <code>self</code> as the first parameter, and if you don't account for it, you'll get things wrong.</p>
<p>In other words, should this:</p>
<pre><code>def foo(result, *argv):
print argv[0]
</code></pre>
<p>actually be this:</p>
<pre><code>def foo(self, result, *argv):
print argv[0]
</code></pre>
<p>If so, then the value traditionally held by <code>self</code> will be assigned to <code>result</code>, and your result value will be in the first position of argv.</p>
<p>If that's not it, you'll need to give more code. At the very least, the code that actually runs the tests.</p>
| 2 | 2009-05-31T04:03:28Z | [
"python",
"debugging"
] |
Debug some Python code | 931,211 | <p>Edit: You can get the full source here: <a href="http://pastebin.com/m26693" rel="nofollow">http://pastebin.com/m26693</a></p>
<p>Edit again: I added some highlights to the pastebin page. <a href="http://pastebin.com/m10f8d239" rel="nofollow">http://pastebin.com/m10f8d239</a></p>
<p>I'm probably going to regret asking such a long question, but I'm stumped with this bug and I could use some guidance. You're going to have to run this code (edit: not anymore. I couldn't include all of the code -- it was truncated) to help in order to really see what's going on, unless you're God or something, then by all means figure it out without running it. Actually I kind of hope that I can explain it well enough so that's not necessary, and I do apologize if I don't accomplish that.</p>
<p>First I'll give you some output. (Edit: There's new output below)</p>
<pre><code>argc 1 [<__main__.RESULT instance at 0x94f91ec>]
(<__main__.RESULT instance at 0x9371f8c>, <__main__.RESULT instance at 0x94f91ec>)
None
bar
internal error: unknown result type 0
argc 1 [<__main__.RESULT instance at 0x94f92ac>]
(<__main__.RESULT instance at 0x94f91ac>, <__main__.RESULT instance at 0x94f92ac>)
None
bar
internal error: unknown result type 0
argc 1 [<__main__.RESULT instance at 0x94f91ec>]
(<__main__.RESULT instance at 0x94f91ec>,)
String: 'bar'
</code></pre>
<p>We have 3 divisions in the output. Notice that argc is always 1. At the point where that is printed, an argument list has been built to be passed to a plugin (Plugins are simply commands in the expression interpreter. Most of this code is the expression interpreter.) The list of a single RESULT instance representation that follows argc is the argument list. The next line is the argument list once it reaches the Python method being called. Notice it has two arguments at this point. The first of these two is trash. The second one is what I wanted. However, as you can see on the lines starting "argc 1" that argument list is always 1 RESULT wide. Where's the stray argument coming from?</p>
<p>Like I said, there are 3 divisions in the output. The first division is a class by itself. The second division is a subclassed class. And the third division is no class/instance at all. The only division that outputs what I expected is the 3rd. Notice it has 1 argument member both before the call and within the call, and the last line is the intended output. It simply echoes/returns the argument "bar". </p>
<p>Are there any peculiarities with variable argument lists that I should be aware of? What I mean is the following:</p>
<pre><code>def foo(result, *argv):
print argv[0]
</code></pre>
<p>I really think the bug has something to do with this, because that is where the trash seems to come from -- in between the call and the execution arrival in the method.</p>
<p>Edit: Ok, so they limit the size of these questions. :) I'll try my best to show what's going on. Here's the relevant part of EvalTree. Note that there's only 2 divisions in this code. I messed up that other file and deleted it.</p>
<pre><code>def EvalTree(self, Root):
type = -1
number = 0.0
freeme = 0
if Root.Token == T_NUMBER or Root.Token == T_STRING:
return 0
elif Root.Token == T_VARIABLE:
self.CopyResult(Root.Result, Root.Variable.value)
return 0
elif Root.Token == T_FUNCTION:
argc = Root.Children
param = resizeList([], argc, RESULT)
print "argc", argc
for i in range(argc):
self.EvalTree(Root.Child[i])
param[i] = Root.Child[i].Result
self.DelResult(Root.Result)
Root.Function.func(Root.Result, *param) # I should have never ever programmed Lua ever.
return 0
</code></pre>
<p>Here's the Plugin's class.</p>
<pre><code>class Foo:
def __init__(self, visitor):
visitor.AddFunction("foo", -1, self.foo)
def foo(self, result, *argv):
print argv
</code></pre>
<p>Here's where it's all executed.</p>
<pre><code>if __name__ == "__main__":
evaluator = Evaluator()
expression = "foo2('bar')"
#expression = "uptime('test')"
evaluator.SetVariableString("test", "Foo")
def func(self, result, *arg1):
print arg1
evaluator.SetResult(result, R_STRING, evaluator.R2S(arg1[0]))
evaluator.AddFunction('foo2', -1, func)
result = RESULT(0, 0, 0, None)
tree = evaluator.Compile(expression)
if tree != -1:
evaluator.Eval(tree, result)
if result.type == R_NUMBER:
print "Number: %g" % (evaluator.R2N(result))
elif result.type == R_STRING:
print "String: '%s'" % (result.string) #(evaluator.R2S(result))
elif result.type == (R_NUMBER | R_STRING):
print "String: '%s' Number: (%g)" % (evaluator.R2S(result), evaluator.R2N(result))
else:
print "internal error: unknown result type %d" % (result.type)
expression = "foo('test')"
result = RESULT(0, 0, 0, None)
tree = evaluator.Compile(expression)
if tree != -1:
evaluator.Eval(tree, result)
if result.type == R_NUMBER:
print "Number: %g" % (evaluator.R2N(result))
elif result.type == R_STRING:
print "String: '%s'" % (result.string) #(evaluator.R2S(result))
elif result.type == (R_NUMBER | R_STRING):
print "String: '%s' Number: (%g)" % (evaluator.R2S(result), evaluator.R2N(result))
else:
print "internal error: unknown result type %d" % (result.type)
</code></pre>
<p>This is the new output:</p>
<pre><code>argc 1
(<__main__.RESULT instance at 0x9ffcf4c>,)
String: 'bar'
argc 1
(<__main__.RESULT instance at 0xa0030cc>, <__main__.RESULT instance at 0xa0030ec>)
internal error: unknown result type 0
</code></pre>
| 0 | 2009-05-31T03:47:57Z | 931,388 | <p>In class Foo, when you call </p>
<pre><code>
def __init__(self, visitor):
visitor.AddFunction("foo", -1, self.foo)
</code></pre>
<p>...you are adding what's called a "bound" method argument (that is, <code>self.foo</code>). It is like a function that already has the self argument specified. The reason is, when you call self.foo(bar, baz), you don't specify "self" again in the argument list. If you call </p>
<pre><code>
def __init__(self, visitor):
visitor.AddFunction("foo", -1, Foo.foo)
</code></pre>
<p>...you'd get the same result as with your free function. However, I don't think this is quite what you want. Besides, EvalTree passes its own <code>self</code> as the first arg to the function. I think what you might want is to declare foo like this:</p>
<pre><code>
class Foo:
def __init__(self, visitor):
visitor.AddFunction("foo", -1, self.foo)
def foo(self, tree, result, *argv):
print argv
</code></pre>
| 1 | 2009-05-31T05:34:33Z | [
"python",
"debugging"
] |
Coverage not showing executed lines in virtualenv | 931,248 | <p>I have a project and I am trying to run nosetests with coverage. I am running in a virtualenv.
When I run</p>
<pre><code>$ python setup.py nosetests
</code></pre>
<p>The tests run fine but coverage is not showing that any code is executed (coverage
is all 0%).</p>
<pre>
Name Stmts Exec Cover Missing
------------------------------------------------------------------
package.module1 60 0 0% 3-106
package.module2 32 0 0% 3-93
package.module3 55 0 0% 8-74
package.module4 38 0 0% 3-125
package.module5 107 0 0% 8-123
package.module6 1 0 0% 1
package.module7 41 0 0% 3-143
package.module8 150 0 0% 7-281
package.module9 158 0 0% 3-338
------------------------------------------------------------------
TOTAL 642 0 0%
----------------------------------------------------------------------
Ran 15 tests in 0.099s
</pre>
<p>Coverage version 3.0b3, Darwin Kernel Version 9.7.0, Mac OS X 10.5.7, setuptools 0.6c9,
nose 0.11.1, Python 2.5.4</p>
| 2 | 2009-05-31T04:20:41Z | 932,210 | <p>This is going to require some back and forth. How can I see your code?</p>
<p>And why did you come to stackoverflow for an answer rather than to the developer (that is, me)? :)</p>
| 2 | 2009-05-31T15:19:34Z | [
"python",
"osx",
"code-coverage",
"virtualenv",
"nosetests"
] |
Coverage not showing executed lines in virtualenv | 931,248 | <p>I have a project and I am trying to run nosetests with coverage. I am running in a virtualenv.
When I run</p>
<pre><code>$ python setup.py nosetests
</code></pre>
<p>The tests run fine but coverage is not showing that any code is executed (coverage
is all 0%).</p>
<pre>
Name Stmts Exec Cover Missing
------------------------------------------------------------------
package.module1 60 0 0% 3-106
package.module2 32 0 0% 3-93
package.module3 55 0 0% 8-74
package.module4 38 0 0% 3-125
package.module5 107 0 0% 8-123
package.module6 1 0 0% 1
package.module7 41 0 0% 3-143
package.module8 150 0 0% 7-281
package.module9 158 0 0% 3-338
------------------------------------------------------------------
TOTAL 642 0 0%
----------------------------------------------------------------------
Ran 15 tests in 0.099s
</pre>
<p>Coverage version 3.0b3, Darwin Kernel Version 9.7.0, Mac OS X 10.5.7, setuptools 0.6c9,
nose 0.11.1, Python 2.5.4</p>
| 2 | 2009-05-31T04:20:41Z | 947,889 | <p>try... </p>
<pre><code>easy_install "coverage==2.85"
</code></pre>
<p>I was having the same issue and this solved my problem and gave me glorious coverage reports as expected. </p>
| 2 | 2009-06-03T23:51:31Z | [
"python",
"osx",
"code-coverage",
"virtualenv",
"nosetests"
] |
Getting friends within a specified degree of separation | 931,323 | <p>all. I'm a very, very new programmer. My language of choice at the moment is Python, and I feel like I have a decent feel for it. I'm just now starting to learn about recursion. (By the way, if anyone could recommend a good guide on this, please let me know!) Just so you all know, this question is very elementary, and the code I'm posting is horribly, horribly wrong.</p>
<p>Anyway, I'm trying to write a function that will get all the friends within a specified degree. If I pass it 0 as the degree, I just want myself. If I pass it 1, I want me and all my friends. 2, I want me, my friends, and all their friends, and so on.</p>
<p>I've tried quite a few different ways of doing this, but none work. I try to visualize how it should work in theory, and I can't quite get that either because I'm so inexperienced in this area. Maybe a kind soul here can show me all the ways in which this code fails and then explain how to do it properly and/or recommend a good guide on the subject. Here goes:</p>
<pre><code> def getFriends(self,degree,friendList):
if degree == 0:
friendList.append(self)
return friendList
else:
friendList = friendList.append(self)
for each in self.friends:
each.getFriends(degree-1,friendList)
</code></pre>
<p>It doesn't work, and I know I've done stupid, stupid things. Someone please slap me and point me in the correct direction!</p>
<p>Thanks.</p>
| 8 | 2009-05-31T05:00:20Z | 931,350 | <p>You can move friendList.append(self) to the line before the if - you need it in both cases. You also don't need to assign the result to friendlist - it's a bug.</p>
<p>In your algorithm, you will likely to add the same people twice - if A is a friend of B and B is a friend of A. So, you need to keep a set of friends that you've processed already. Before processing, check this set and don't do anything if the person has been processed already.</p>
| 1 | 2009-05-31T05:10:55Z | [
"python",
"recursion"
] |
Getting friends within a specified degree of separation | 931,323 | <p>all. I'm a very, very new programmer. My language of choice at the moment is Python, and I feel like I have a decent feel for it. I'm just now starting to learn about recursion. (By the way, if anyone could recommend a good guide on this, please let me know!) Just so you all know, this question is very elementary, and the code I'm posting is horribly, horribly wrong.</p>
<p>Anyway, I'm trying to write a function that will get all the friends within a specified degree. If I pass it 0 as the degree, I just want myself. If I pass it 1, I want me and all my friends. 2, I want me, my friends, and all their friends, and so on.</p>
<p>I've tried quite a few different ways of doing this, but none work. I try to visualize how it should work in theory, and I can't quite get that either because I'm so inexperienced in this area. Maybe a kind soul here can show me all the ways in which this code fails and then explain how to do it properly and/or recommend a good guide on the subject. Here goes:</p>
<pre><code> def getFriends(self,degree,friendList):
if degree == 0:
friendList.append(self)
return friendList
else:
friendList = friendList.append(self)
for each in self.friends:
each.getFriends(degree-1,friendList)
</code></pre>
<p>It doesn't work, and I know I've done stupid, stupid things. Someone please slap me and point me in the correct direction!</p>
<p>Thanks.</p>
| 8 | 2009-05-31T05:00:20Z | 931,354 | <pre><code>friendList = friendList.append(self)
</code></pre>
<p>This sets <code>friendList</code> to <code>None</code>, unconditionally, as that's the invariable return value of any list's <code>append</code> method -- so, fix <em>that</em> weirdness first...!-)</p>
<p>Once you've fixed that, you still need to fix the function so that it always ends with <code>return</code> of something -- "falling off the end" returns <code>None</code>. E.g.:</p>
<pre><code>def getFriends(self,degree, friendList):
if degree == 0:
friendList.append(self)
return friendList
else:
friendList.append(self)
for each in self.friends:
each.getFriends(degree-1, friendList)
return friendList
</code></pre>
<p>which can and clearly should be refactored to eliminate the duplication (DRY, Don't Repeat Yourself, is THE heart of programming...):</p>
<pre><code>def getFriends(self,degree, friendList):
friendList.append(self)
if degree > 0:
for each in self.friends:
each.getFriends(degree-1, friendList)
return friendList
</code></pre>
<p>PS: that (the <code>alist=alist.append(...)</code> issue) <strong>precisely</strong> how I got back in touch with my wife Anna in 2002 (we'd been not-quite-sweetheart friends many years before but had lost track of each other) -- she started studying Python, used exactly this erroneous construct, couldn't understand why it failed -- looked around the Python community, saw and recognized my name, mailed me asking about it... less than two years later we were married, and soon after she was the first woman member of the Python Software Foundation and my co-author in "Python Cookbook" 2nd ed. So, of course, I've got an incredible sweet spot for this specific Python error...;-).</p>
| 12 | 2009-05-31T05:13:07Z | [
"python",
"recursion"
] |
Getting friends within a specified degree of separation | 931,323 | <p>all. I'm a very, very new programmer. My language of choice at the moment is Python, and I feel like I have a decent feel for it. I'm just now starting to learn about recursion. (By the way, if anyone could recommend a good guide on this, please let me know!) Just so you all know, this question is very elementary, and the code I'm posting is horribly, horribly wrong.</p>
<p>Anyway, I'm trying to write a function that will get all the friends within a specified degree. If I pass it 0 as the degree, I just want myself. If I pass it 1, I want me and all my friends. 2, I want me, my friends, and all their friends, and so on.</p>
<p>I've tried quite a few different ways of doing this, but none work. I try to visualize how it should work in theory, and I can't quite get that either because I'm so inexperienced in this area. Maybe a kind soul here can show me all the ways in which this code fails and then explain how to do it properly and/or recommend a good guide on the subject. Here goes:</p>
<pre><code> def getFriends(self,degree,friendList):
if degree == 0:
friendList.append(self)
return friendList
else:
friendList = friendList.append(self)
for each in self.friends:
each.getFriends(degree-1,friendList)
</code></pre>
<p>It doesn't work, and I know I've done stupid, stupid things. Someone please slap me and point me in the correct direction!</p>
<p>Thanks.</p>
| 8 | 2009-05-31T05:00:20Z | 931,358 | <p>Is your identation correct? The body of the method should be indented relative to it's definition</p>
| 1 | 2009-05-31T05:13:54Z | [
"python",
"recursion"
] |
Getting friends within a specified degree of separation | 931,323 | <p>all. I'm a very, very new programmer. My language of choice at the moment is Python, and I feel like I have a decent feel for it. I'm just now starting to learn about recursion. (By the way, if anyone could recommend a good guide on this, please let me know!) Just so you all know, this question is very elementary, and the code I'm posting is horribly, horribly wrong.</p>
<p>Anyway, I'm trying to write a function that will get all the friends within a specified degree. If I pass it 0 as the degree, I just want myself. If I pass it 1, I want me and all my friends. 2, I want me, my friends, and all their friends, and so on.</p>
<p>I've tried quite a few different ways of doing this, but none work. I try to visualize how it should work in theory, and I can't quite get that either because I'm so inexperienced in this area. Maybe a kind soul here can show me all the ways in which this code fails and then explain how to do it properly and/or recommend a good guide on the subject. Here goes:</p>
<pre><code> def getFriends(self,degree,friendList):
if degree == 0:
friendList.append(self)
return friendList
else:
friendList = friendList.append(self)
for each in self.friends:
each.getFriends(degree-1,friendList)
</code></pre>
<p>It doesn't work, and I know I've done stupid, stupid things. Someone please slap me and point me in the correct direction!</p>
<p>Thanks.</p>
| 8 | 2009-05-31T05:00:20Z | 931,392 | <p>There's no <code>return</code> statement in the <code>else</code> clause. So if <code>degree != 0</code>, this method will always return <code>None</code>. You want to append the result of each recursive <code>getFriends</code> call to your <code>friendList</code>, and then return <code>friendList</code>.</p>
<p>By the way, if you want to make this algorithm faster, there are well established methods for doing this with either graph algorithms or matrix manipulation. For example, if you represent friendship relationships with an adjacency matrix <code>A</code>, and you want to find all people who are within <code>n</code> degrees of separation of each other, you can compute <code>B=A^n</code>. If <code>B[i][j] > 0</code>, then <code>i</code> and <code>j</code> are within <code>n</code> degrees of separation of each other. Matrix multiplication is easy with a package like <a href="http://numpy.scipy.org/" rel="nofollow">NumPy</a>.</p>
| 1 | 2009-05-31T05:38:54Z | [
"python",
"recursion"
] |
Getting friends within a specified degree of separation | 931,323 | <p>all. I'm a very, very new programmer. My language of choice at the moment is Python, and I feel like I have a decent feel for it. I'm just now starting to learn about recursion. (By the way, if anyone could recommend a good guide on this, please let me know!) Just so you all know, this question is very elementary, and the code I'm posting is horribly, horribly wrong.</p>
<p>Anyway, I'm trying to write a function that will get all the friends within a specified degree. If I pass it 0 as the degree, I just want myself. If I pass it 1, I want me and all my friends. 2, I want me, my friends, and all their friends, and so on.</p>
<p>I've tried quite a few different ways of doing this, but none work. I try to visualize how it should work in theory, and I can't quite get that either because I'm so inexperienced in this area. Maybe a kind soul here can show me all the ways in which this code fails and then explain how to do it properly and/or recommend a good guide on the subject. Here goes:</p>
<pre><code> def getFriends(self,degree,friendList):
if degree == 0:
friendList.append(self)
return friendList
else:
friendList = friendList.append(self)
for each in self.friends:
each.getFriends(degree-1,friendList)
</code></pre>
<p>It doesn't work, and I know I've done stupid, stupid things. Someone please slap me and point me in the correct direction!</p>
<p>Thanks.</p>
| 8 | 2009-05-31T05:00:20Z | 931,560 | <p>(Sorry, I can't comment on Alex's answer... <em>yet</em>)</p>
<p>I don't really like the idea that getFriends returns a value that is never used. It works, for sure, but it looks a bit intriguing ;)
Also, the first call to getFriends would be self.getFriends(degree, []) which is confusing: when getting a list of friends, why would you pass as an argument an empty list, right?</p>
<p>For clarity, I think that I would prefer this slightly different version, using the _getFriends helper function:</p>
<pre><code>def getFriends(self, degree):
friendList = []
self._getFriends(degree, friendList)
return friendList
def _getFriends(self, degree, friendList):
friendList.append(self)
if degree:
for friend in self.friends:
friend._getFriends(degree-1, friendList)
</code></pre>
| 1 | 2009-05-31T07:30:32Z | [
"python",
"recursion"
] |
Is there a Python equivalent to the PHP function htmlspecialchars()? | 931,423 | <p>Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().</p>
| 13 | 2009-05-31T05:58:44Z | 931,442 | <p>If you are using django 1.0 then your template variables will already be encoded and ready for display. You also use the <code>safe</code> operator <code>{{ var|safe }}</code> if you don't want it globally turned on.</p>
| 0 | 2009-05-31T06:11:00Z | [
"php",
"python",
"html-entities",
"htmlspecialchars"
] |
Is there a Python equivalent to the PHP function htmlspecialchars()? | 931,423 | <p>Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().</p>
| 13 | 2009-05-31T05:58:44Z | 931,445 | <p>Closest thing I know about is <a href="http://docs.python.org/library/cgi.html#cgi.escape">cgi.escape</a>.</p>
| 12 | 2009-05-31T06:12:45Z | [
"php",
"python",
"html-entities",
"htmlspecialchars"
] |
Is there a Python equivalent to the PHP function htmlspecialchars()? | 931,423 | <p>Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().</p>
| 13 | 2009-05-31T05:58:44Z | 931,474 | <p>You probably want <a href="http://docs.python.org/library/xml.sax.utils.html#xml.sax.saxutils.escape" rel="nofollow">xml.sax.saxutils.escape</a>:</p>
<pre><code>from xml.sax.saxutils import escape
escape(unsafe, {'"':'&quot;'}) # ENT_COMPAT
escape(unsafe, {'"':'&quot;', '\'':'&#039;'}) # ENT_QUOTES
escape(unsafe) # ENT_NOQUOTES
</code></pre>
<p>Have a look at <a href="http://docs.python.org/library/xml.sax.utils.html#xml.sax.saxutils.quoteattr" rel="nofollow">xml.sax.saxutils.quoteattr</a>, it might be more useful for you</p>
| 2 | 2009-05-31T06:31:53Z | [
"php",
"python",
"html-entities",
"htmlspecialchars"
] |
Is there a Python equivalent to the PHP function htmlspecialchars()? | 931,423 | <p>Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().</p>
| 13 | 2009-05-31T05:58:44Z | 931,641 | <p>The <code>html.entities</code> module (<code>htmlentitydefs</code> for python 2.x) contains a dictionary <code>codepoint2name</code> which should do what you need.</p>
<pre><code>>>> import html.entities
>>> html.entities.codepoint2name[ord("&")]
'amp'
>>> html.entities.codepoint2name[ord('"')]
'quot'
</code></pre>
| 1 | 2009-05-31T08:27:17Z | [
"php",
"python",
"html-entities",
"htmlspecialchars"
] |
Is there a Python equivalent to the PHP function htmlspecialchars()? | 931,423 | <p>Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().</p>
| 13 | 2009-05-31T05:58:44Z | 2,513,072 | <pre><code>from django.utils.html import escape
print escape('<div class="q">Q & A</div>')
</code></pre>
| 6 | 2010-03-25T04:32:22Z | [
"php",
"python",
"html-entities",
"htmlspecialchars"
] |
Is there a Python equivalent to the PHP function htmlspecialchars()? | 931,423 | <p>Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().</p>
| 13 | 2009-05-31T05:58:44Z | 5,488,846 | <p>I think the simplest way is just to use replace:</p>
<pre><code>text.replace("&", "&amp;").replace('"', "&quot;").replace("<", "&lt;").replace(">", "&gt;")
</code></pre>
<p>PHP only escapes those four entities with htmlspecialchars. Note that if you have ENT_QUOTES set in PHP, you need to replace quotes with &#039; rather than &quot;.</p>
| 1 | 2011-03-30T15:59:40Z | [
"php",
"python",
"html-entities",
"htmlspecialchars"
] |
Is there a Python equivalent to the PHP function htmlspecialchars()? | 931,423 | <p>Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().</p>
| 13 | 2009-05-31T05:58:44Z | 35,729,832 | <p>Building on @garlon4 answer, you can define your own <code>htmlspecialchars(s)</code>:</p>
<pre><code>def htmlspecialchars(text):
return (
text.replace("&", "&amp;").
replace('"', "&quot;").
replace("<", "&lt;").
replace(">", "&gt;")
)
</code></pre>
| 0 | 2016-03-01T17:48:11Z | [
"php",
"python",
"html-entities",
"htmlspecialchars"
] |
Replace __str__ method on list object in Python | 931,699 | <p>This seems like it should be simple:</p>
<p>I want a <code>list</code> like any other <code>list</code>, except it has a different <code>.__str__</code> method.</p>
<ol>
<li>Trying to set <code>object.__str__ = foo</code> results in a read-only error</li>
<li>Trying to subclass <code>list</code> means you need some way to convert an existing <code>list</code> to an instance of the subclass. This requires either copying all attributes manually (a huge pain), or somehow copying them all automatically, which I don't know how to do.</li>
<li>Trying to write a wrapper around the <code>list</code> object means I have to figure out some way to send all messages to the wrapped object except <code>.__str__</code> which I handle with my own method. Don't know how to do this.</li>
</ol>
<p>Any alternatives, or solutions #2 or #3 greatly appreciated. Thanks!</p>
| 8 | 2009-05-31T09:06:52Z | 931,706 | <p>You could extend the list class and override it:</p>
<pre><code>class myList(list):
def __str__(self):
# do something
return "something"
</code></pre>
<p>Edit: removed an incorrect part of the answer which suggested dynamically replacing <code>__str__</code> on the list object, which is not allowed in the implementation of Python lists.</p>
| 4 | 2009-05-31T09:11:36Z | [
"python"
] |
Replace __str__ method on list object in Python | 931,699 | <p>This seems like it should be simple:</p>
<p>I want a <code>list</code> like any other <code>list</code>, except it has a different <code>.__str__</code> method.</p>
<ol>
<li>Trying to set <code>object.__str__ = foo</code> results in a read-only error</li>
<li>Trying to subclass <code>list</code> means you need some way to convert an existing <code>list</code> to an instance of the subclass. This requires either copying all attributes manually (a huge pain), or somehow copying them all automatically, which I don't know how to do.</li>
<li>Trying to write a wrapper around the <code>list</code> object means I have to figure out some way to send all messages to the wrapped object except <code>.__str__</code> which I handle with my own method. Don't know how to do this.</li>
</ol>
<p>Any alternatives, or solutions #2 or #3 greatly appreciated. Thanks!</p>
| 8 | 2009-05-31T09:06:52Z | 931,747 | <p>I'm a Java programmer but I think that is what you want (tested with python 2.6): </p>
<pre><code>>>> class myList(list):
... def __str__(self):
... return "aaa"
...
>>> def myListWrapper(list):
... return myList(list)
...
>>> a = [1, 2, 3]
>>> type(a)
<type 'list'>
>>> b = myListWrapper(a)
>>> type(b)
<class '__main__.myList'>
>>> print(a)
[1, 2, 3]
>>> print(b)
aaa
</code></pre>
| 2 | 2009-05-31T09:34:16Z | [
"python"
] |
Replace __str__ method on list object in Python | 931,699 | <p>This seems like it should be simple:</p>
<p>I want a <code>list</code> like any other <code>list</code>, except it has a different <code>.__str__</code> method.</p>
<ol>
<li>Trying to set <code>object.__str__ = foo</code> results in a read-only error</li>
<li>Trying to subclass <code>list</code> means you need some way to convert an existing <code>list</code> to an instance of the subclass. This requires either copying all attributes manually (a huge pain), or somehow copying them all automatically, which I don't know how to do.</li>
<li>Trying to write a wrapper around the <code>list</code> object means I have to figure out some way to send all messages to the wrapped object except <code>.__str__</code> which I handle with my own method. Don't know how to do this.</li>
</ol>
<p>Any alternatives, or solutions #2 or #3 greatly appreciated. Thanks!</p>
| 8 | 2009-05-31T09:06:52Z | 931,757 | <p>How about wrapping the list?</p>
<pre><code>>>> class StrList(object):
def __init__(self, data=None):
self._data = data or []
def __str__(self):
return "StrList!"
def __getattr__(self, attr):
if attr == "_data":
return self.__dict__[attr]
return getattr(self._data, attr)
def __setattr__(self, key, val):
if key == "_data":
self.__dict__[key] = val
else:
setattr(self._data, key, val)
def __getitem__(self, index):
return self._data[index]
def __setitem__(self, index, value):
self._data[index] = value
>>> l = StrList(range(3))
>>> print l
StrList!
>>> l[0]
0
>>> for x in l:
print x
0
1
2
>>> l[0] = "spam"
>>> l.append("egg")
>>> print list(l)
['spam', 1, 2, 'egg']
>>>
</code></pre>
| 0 | 2009-05-31T09:41:34Z | [
"python"
] |
Replace __str__ method on list object in Python | 931,699 | <p>This seems like it should be simple:</p>
<p>I want a <code>list</code> like any other <code>list</code>, except it has a different <code>.__str__</code> method.</p>
<ol>
<li>Trying to set <code>object.__str__ = foo</code> results in a read-only error</li>
<li>Trying to subclass <code>list</code> means you need some way to convert an existing <code>list</code> to an instance of the subclass. This requires either copying all attributes manually (a huge pain), or somehow copying them all automatically, which I don't know how to do.</li>
<li>Trying to write a wrapper around the <code>list</code> object means I have to figure out some way to send all messages to the wrapped object except <code>.__str__</code> which I handle with my own method. Don't know how to do this.</li>
</ol>
<p>Any alternatives, or solutions #2 or #3 greatly appreciated. Thanks!</p>
| 8 | 2009-05-31T09:06:52Z | 931,765 | <p>Which raises the question: why do you want to override the __str__ method?</p>
<p>Wouldnt it be better to create a class to encapsulate your object?</p>
<pre><code>class MyContainer(object):
def __init__(self, list):
self.containedList = list
def __str__(self):
print('All hail Python')
</code></pre>
<p>This way you don't have to worry about converting your object, or copying the attributes, or whatsoever. (by the way, how expensive is MyList(longlist)? Is it an intelligent copy, or a dumb "let's recreate a list object from an iterable?")</p>
<p>If, at some point, it looks complicated to do what you're trying to do, it might mean that you're doing it wrong :p</p>
| 1 | 2009-05-31T09:50:52Z | [
"python"
] |
Replace __str__ method on list object in Python | 931,699 | <p>This seems like it should be simple:</p>
<p>I want a <code>list</code> like any other <code>list</code>, except it has a different <code>.__str__</code> method.</p>
<ol>
<li>Trying to set <code>object.__str__ = foo</code> results in a read-only error</li>
<li>Trying to subclass <code>list</code> means you need some way to convert an existing <code>list</code> to an instance of the subclass. This requires either copying all attributes manually (a huge pain), or somehow copying them all automatically, which I don't know how to do.</li>
<li>Trying to write a wrapper around the <code>list</code> object means I have to figure out some way to send all messages to the wrapped object except <code>.__str__</code> which I handle with my own method. Don't know how to do this.</li>
</ol>
<p>Any alternatives, or solutions #2 or #3 greatly appreciated. Thanks!</p>
| 8 | 2009-05-31T09:06:52Z | 931,822 | <p>This solution works without a wrapper. And works if you join two lists by add. Any operation that modify the list itself will work as expected. Only functions that return a copy of the list like: sorted, reveresed will return the native python list which is fine. sort and reverse on the other hand operate on the list itself and will keep the type.</p>
<pre><code>class myList(list):
def __new__(cls, data=None):
obj = super(myList, cls).__new__(cls, data)
return obj
def __str__(self):
return 'myList(%s)' % list(self)
def __add__(self, other):
return myList(list(self) + list(other))
>>> l = myList(range(5))
>>> print l
myList([0, 1, 2, 3, 4])
>>> print l + [1, 2]
myList([0, 1, 2, 3, 4, 1, 2])
>>> l.sort()
>>> print l
myList([0, 1, 2, 3, 4])
</code></pre>
| 7 | 2009-05-31T10:37:55Z | [
"python"
] |
Replace __str__ method on list object in Python | 931,699 | <p>This seems like it should be simple:</p>
<p>I want a <code>list</code> like any other <code>list</code>, except it has a different <code>.__str__</code> method.</p>
<ol>
<li>Trying to set <code>object.__str__ = foo</code> results in a read-only error</li>
<li>Trying to subclass <code>list</code> means you need some way to convert an existing <code>list</code> to an instance of the subclass. This requires either copying all attributes manually (a huge pain), or somehow copying them all automatically, which I don't know how to do.</li>
<li>Trying to write a wrapper around the <code>list</code> object means I have to figure out some way to send all messages to the wrapped object except <code>.__str__</code> which I handle with my own method. Don't know how to do this.</li>
</ol>
<p>Any alternatives, or solutions #2 or #3 greatly appreciated. Thanks!</p>
| 8 | 2009-05-31T09:06:52Z | 931,860 | <p>If you would like to override <code>__str__</code> for other containers (e.g., <code>tuple</code>), you can take advantage of multiple inheritance:</p>
<pre><code>class PrettyStr(object):
def __str__(self):
ret = ''
if isinstance(self, (list, tuple)):
ret = ''.join(str(elem) for elem in self)
else:
pass # handle other types here
return ret
class MyList(PrettyStr, list):
pass
class MyTuple(PrettyStr, tuple):
pass
if __name__ == "__main__":
print MyList([1, 2, 3, 4])
print MyTuple((1, 2, 3, 4))
</code></pre>
| 4 | 2009-05-31T11:12:55Z | [
"python"
] |
Replace __str__ method on list object in Python | 931,699 | <p>This seems like it should be simple:</p>
<p>I want a <code>list</code> like any other <code>list</code>, except it has a different <code>.__str__</code> method.</p>
<ol>
<li>Trying to set <code>object.__str__ = foo</code> results in a read-only error</li>
<li>Trying to subclass <code>list</code> means you need some way to convert an existing <code>list</code> to an instance of the subclass. This requires either copying all attributes manually (a huge pain), or somehow copying them all automatically, which I don't know how to do.</li>
<li>Trying to write a wrapper around the <code>list</code> object means I have to figure out some way to send all messages to the wrapped object except <code>.__str__</code> which I handle with my own method. Don't know how to do this.</li>
</ol>
<p>Any alternatives, or solutions #2 or #3 greatly appreciated. Thanks!</p>
| 8 | 2009-05-31T09:06:52Z | 932,063 | <pre><code>class MyList(list):
def __str__(self):
return "foo"
str(MyList([1, 2, 3]))
</code></pre>
<p>'foo'</p>
<pre><code>str(MyList(list([1, 2, 3])))
</code></pre>
<p>'foo'</p>
<p>My earlier comments as an answer. As you can see MyList accepts any sequence in its constructor.</p>
| 2 | 2009-05-31T13:38:16Z | [
"python"
] |
py2exe - generated executable freezes when connecting to socket | 931,851 | <p>Pardon my ignorance as I'm still a beginner in coding.</p>
<p>I'm trying to convert a python script I wrote to a Windows executable program using py2exe. However, though I am able to successfully convert the script, the executable doesn't seem to be fully functional.</p>
<p>After much debugging, I have isolated the cause and the following code seems to be the problem</p>
<pre><code>host = str(raw_input('Enter Host IP Address: '))
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, 5000))
</code></pre>
<p>The problem does not occur when the script is executed from Pydev itself and the script is able to run without problems. The windows executable which is a console application just <em>hangs</em> when trying to connect to another host. </p>
<p>Is this a known issue or am I doing something wrong? Any help is much appreciated.</p>
| 1 | 2009-05-31T11:08:16Z | 931,929 | <p>Are you able to input the IP address? Reading <a href="http://www.mail-archive.com/pygame-users@seul.org/msg04830.html" rel="nofollow">that thread</a> it seems that py2exe requires a special <em>windows</em> argument to launch a console. Otherwise, raw_input tries to read from the standard input, and hangs/crashes because it does not find anything.</p>
<p>Given the age of the thread, I checked <a href="http://www.py2exe.org/index.cgi/ListOfOptions" rel="nofollow">py2exe doc</a>: you might want to try to put your script in the <em>console</em> attribute.</p>
<p>I really think that the behavior is related to raw_input, and that it is <strong>not</strong> caused by the socket operation.</p>
| 1 | 2009-05-31T12:00:44Z | [
"python",
"py2exe"
] |
Inaccurate Logarithm in Python | 931,995 | <p>I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2**31, 2) it returned 31.000000000000004, which struck me as a bit odd.</p>
<p>I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2**31) / log10(2)' and I got a round 31.0</p>
<p>I tried running the same original function in Python 3.0.1, assuming that it was fixed in a more advanced version.</p>
<p>Why does this happen? Is it possible that there are some inaccuracies in mathematical functions in Python?</p>
| 7 | 2009-05-31T12:48:26Z | 932,003 | <p>This is to be expected with computer arithmetic. It is following particular rules, such as <a href="http://en.wikipedia.org/wiki/IEEE%5F754">IEEE 754</a>, that probably don't match the math you learned in school.</p>
<p>If this <em>actually</em> matters, use Python's <a href="http://docs.python.org/library/decimal.html">decimal type</a>.</p>
<p>Example:</p>
<pre><code>from decimal import Decimal, Context
ctx = Context(prec=20)
two = Decimal(2)
ctx.divide(ctx.power(two, Decimal(31)).ln(ctx), two.ln(ctx))
</code></pre>
| 43 | 2009-05-31T12:55:01Z | [
"python",
"math",
"floating-point"
] |
Inaccurate Logarithm in Python | 931,995 | <p>I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2**31, 2) it returned 31.000000000000004, which struck me as a bit odd.</p>
<p>I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2**31) / log10(2)' and I got a round 31.0</p>
<p>I tried running the same original function in Python 3.0.1, assuming that it was fixed in a more advanced version.</p>
<p>Why does this happen? Is it possible that there are some inaccuracies in mathematical functions in Python?</p>
| 7 | 2009-05-31T12:48:26Z | 932,007 | <p><em>Always</em> assume that floating point operations will have some error in them and check for equality taking that error into account (either a percentage value like 0.00001% or a fixed value like 0.00000000001). This inaccuracy is a given since not all decimal numbers can be represented in binary with a fixed number of bits precision.</p>
<p>Your particular case is not one of them if Python uses IEEE754 since 31 should be easily representable with even single precision. It's possible however that it loses precision in one of the many steps it takes to calculate log<sub>2</sub>2<sup>31</sup>, simply because it doesn't have code to detect special cases like a direct power of two.</p>
| 17 | 2009-05-31T12:58:09Z | [
"python",
"math",
"floating-point"
] |
Inaccurate Logarithm in Python | 931,995 | <p>I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2**31, 2) it returned 31.000000000000004, which struck me as a bit odd.</p>
<p>I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2**31) / log10(2)' and I got a round 31.0</p>
<p>I tried running the same original function in Python 3.0.1, assuming that it was fixed in a more advanced version.</p>
<p>Why does this happen? Is it possible that there are some inaccuracies in mathematical functions in Python?</p>
| 7 | 2009-05-31T12:48:26Z | 932,018 | <p>floating-point operations are never exact. They return a result which has an acceptable relative error, for the language/hardware infrastructure.</p>
<p>In general, it's quite wrong to assume that floating-point operations are precise, especially with single-precision. <a href="http://en.wikipedia.org/wiki/Floating%5Fpoint#Accuracy%5Fproblems" rel="nofollow">"Accuracy problems" section</a> from Wikipedia Floating point article :)</p>
| 5 | 2009-05-31T13:01:06Z | [
"python",
"math",
"floating-point"
] |
Inaccurate Logarithm in Python | 931,995 | <p>I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2**31, 2) it returned 31.000000000000004, which struck me as a bit odd.</p>
<p>I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2**31) / log10(2)' and I got a round 31.0</p>
<p>I tried running the same original function in Python 3.0.1, assuming that it was fixed in a more advanced version.</p>
<p>Why does this happen? Is it possible that there are some inaccuracies in mathematical functions in Python?</p>
| 7 | 2009-05-31T12:48:26Z | 932,021 | <p>This is normal. I would expect log10 to be more accurate then log(x, y), since it knows exactly what the base of the logarithm is, also there may be some hardware support for calculating base-10 logarithms.</p>
| 2 | 2009-05-31T13:04:49Z | [
"python",
"math",
"floating-point"
] |
Inaccurate Logarithm in Python | 931,995 | <p>I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2**31, 2) it returned 31.000000000000004, which struck me as a bit odd.</p>
<p>I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2**31) / log10(2)' and I got a round 31.0</p>
<p>I tried running the same original function in Python 3.0.1, assuming that it was fixed in a more advanced version.</p>
<p>Why does this happen? Is it possible that there are some inaccuracies in mathematical functions in Python?</p>
| 7 | 2009-05-31T12:48:26Z | 932,095 | <p>You should read "What Every Computer Scientist Should Know About Floating-Point Arithmetic". </p>
<p><a href="http://docs.sun.com/source/806-3568/ncg_goldberg.html" rel="nofollow">http://docs.sun.com/source/806-3568/ncg_goldberg.html</a></p>
| 19 | 2009-05-31T14:08:16Z | [
"python",
"math",
"floating-point"
] |
Inaccurate Logarithm in Python | 931,995 | <p>I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2**31, 2) it returned 31.000000000000004, which struck me as a bit odd.</p>
<p>I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2**31) / log10(2)' and I got a round 31.0</p>
<p>I tried running the same original function in Python 3.0.1, assuming that it was fixed in a more advanced version.</p>
<p>Why does this happen? Is it possible that there are some inaccuracies in mathematical functions in Python?</p>
| 7 | 2009-05-31T12:48:26Z | 932,641 | <p>IEEE double floating point numbers have <a href="http://www.johndcook.com/blog/2009/04/06/anatomy-of-a-floating-point-number/" rel="nofollow">52 bits of precision</a>. Since 10^15 < 2^52 < 10^16, a double has between 15 and 16 significant figures. The result 31.000000000000004 is correct to 16 figures, so it is as good as you can expect.</p>
| 3 | 2009-05-31T19:09:17Z | [
"python",
"math",
"floating-point"
] |
Inaccurate Logarithm in Python | 931,995 | <p>I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2**31, 2) it returned 31.000000000000004, which struck me as a bit odd.</p>
<p>I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2**31) / log10(2)' and I got a round 31.0</p>
<p>I tried running the same original function in Python 3.0.1, assuming that it was fixed in a more advanced version.</p>
<p>Why does this happen? Is it possible that there are some inaccuracies in mathematical functions in Python?</p>
| 7 | 2009-05-31T12:48:26Z | 932,726 | <p>The <code>repr</code>esentation (<code>float.__repr__</code>) of a number in python tries to return a string of digits as close to the real value as possible when converted back, given that IEEE-754 arithmetic is precise up to a limit. In any case, if you <code>print</code>ed the result, you wouldn't notice:</p>
<pre><code>>>> from math import log
>>> log(2**31,2)
31.000000000000004
>>> print log(2**31,2)
31.0
</code></pre>
<p><code>print</code> converts its arguments to strings (in this case, through the <code>float.__str__</code> method), which caters for the inaccuracy by displaying less digits:</p>
<pre><code>>>> log(1000000,2)
19.931568569324174
>>> print log(1000000,2)
19.9315685693
>>> 1.0/10
0.10000000000000001
>>> print 1.0/10
0.1
</code></pre>
<p>usuallyuseless' answer is very useful, actually :)</p>
| 1 | 2009-05-31T19:53:56Z | [
"python",
"math",
"floating-point"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 932,072 | <p>Mine is, basically, a directory called "plugins" which the main app can poll and then use <a href="https://docs.python.org/library/imp.html#imp.load_module">imp.load_module</a> to pick up files, look for a well-known entry point possibly with module-level config params, and go from there. I use file-monitoring stuff for a certain amount of dynamism in which plugins are active, but that's a nice-to-have.</p>
<p>Of course, any requirement that comes along saying "I don't need [big, complicated thing] X; I just want something lightweight" runs the risk of re-implementing X one discovered requirement at a time. But that's not to say you can't have some fun doing it anyway :)</p>
| 114 | 2009-05-31T13:51:05Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 932,078 | <p>Have a look at <a href="http://wehart.blogspot.com/2009/01/python-plugin-frameworks.html">at this overview over existing plugin frameworks / libraries</a>, it is a good starting point. I quite like <a href="http://yapsy.sourceforge.net/">yapsy</a>, but it depends on your use-case.</p>
| 29 | 2009-05-31T13:54:12Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 932,306 | <p>While that question is really interesting, I think it's fairly hard to answer, without more details. What sort of application is this? Does it have a GUI? Is it a command-line tool? A set of scripts? A program with an unique entry point, etc...</p>
<p>Given the little information I have, I will answer in a very generic manner.</p>
<p>What means do you have to add plugins? </p>
<ul>
<li>You will probably have to add a configuration file, which will list the paths/directories to load. </li>
<li>Another way would be to say "any files in that plugin/ directory will be loaded", but it has the inconvenient to require your users to move around files.</li>
<li>A last, intermediate option would be to require all plugins to be in the same plugin/ folder, and then to active/deactivate them using relative paths in a config file.</li>
</ul>
<p>On a pure code/design practice, you'll have to determine clearly what behavior/specific actions you want your users to extend. Identify the common entry point/a set of functionalities that will always be overridden, and determine groups within these actions. Once this is done, it should be easy to extend your application,</p>
<p>Example using <em>hooks</em>, inspired from MediaWiki (PHP, but does language really matters?):</p>
<pre><code>import hooks
# In your core code, on key points, you allow user to run actions:
def compute(...):
try:
hooks.runHook(hooks.registered.beforeCompute)
except hooks.hookException:
print('Error while executing plugin')
# [compute main code] ...
try:
hooks.runHook(hooks.registered.afterCompute)
except hooks.hookException:
print('Error while executing plugin')
# The idea is to insert possibilities for users to extend the behavior
# where it matters.
# If you need to, pass context parameters to runHook. Remember that
# runHook can be defined as a runHook(*args, **kwargs) function, not
# requiring you to define a common interface for *all* hooks. Quite flexible :)
# --------------------
# And in the plugin code:
# [...] plugin magic
def doStuff():
# ....
# and register the functionalities in hooks
# doStuff will be called at the end of each core.compute() call
hooks.registered.afterCompute.append(doStuff)
</code></pre>
<p>Another example, inspired from mercurial. Here, extensions only add commands to the <em>hg</em> commandline executable, extending the behavior.</p>
<pre><code>def doStuff(ui, repo, *args, **kwargs):
# when called, a extension function always receives:
# * an ui object (user interface, prints, warnings, etc)
# * a repository object (main object from which most operations are doable)
# * command-line arguments that were not used by the core program
doMoreMagicStuff()
obj = maybeCreateSomeObjects()
# each extension defines a commands dictionary in the main extension file
commands = { 'newcommand': doStuff }
</code></pre>
<p>For both approaches, you might need common <em>initialize</em> and <em>finalize</em> for your extension.
You can either use a common interface that all your extension will have to implement (fits better with second approach; mercurial uses a reposetup(ui, repo) that is called for all extension), or use a hook-kind of approach, with a hooks.setup hook.</p>
<p>But again, if you want more useful answers, you'll have to narrow down your question ;)</p>
| 21 | 2009-05-31T15:54:28Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 932,564 | <p>I am a retired biologist who dealt with digital micrograqphs and found himself having to write an image processing and analysis package (not technically a library) to run on an SGi machine. I wrote the code in C and used Tcl for the scripting language. The GUI, such as it was, was done using Tk. The commands that appeared in Tcl were of the form "extensionName commandName arg0 arg1 ... param0 param1 ...", that is, simple space-separated words and numbers. When Tcl saw the "extensionName" substring, control was passed to the C package. That in turn ran the command through a lexer/parser (done in lex/yacc) and then called C routines as necessary. </p>
<p>The commands to operate the package could be run one by one via a window in the GUI, but batch jobs were done by editing text files which were valid Tcl scripts; you'd pick the template that did the kind of file-level operation you wanted to do and then edit a copy to contain the actual directory and file names plus the package commands. It worked like a charm. Until ...</p>
<p>1) The world turned to PCs and 2) the scripts got longer than about 500 lines, when Tcl's iffy organizational capabilities started to become a real inconvenience. Time passed ...</p>
<p>I retired, Python got invented, and it looked like the perfect successor to Tcl. Now, I have never done the port, because I have never faced up to the challenges of compiling (pretty big) C programs on a PC, extending Python with a C package, and doing GUIs in Python/Gt?/Tk?/??. However, the old idea of having editable template scripts seems still workable. Also, it should not be too great a burden to enter package commands in a native Python form, e.g.:</p>
<p>packageName.command( arg0, arg1, ..., param0, param1, ...)</p>
<p>A few extra dots, parens, and commas, but those aren't showstoppers.</p>
<p>I remember seeing that someone has done versions of lex and yacc in Python (try: <a href="http://www.dabeaz.com/ply/" rel="nofollow">http://www.dabeaz.com/ply/</a>), so if those are still needed, they're around.</p>
<p>The point of this rambling is that it has seemed to me that Python itself IS the desired "lightweight" front end usable by scientists. I'm curious to know why you think that it is not, and I mean that seriously.</p>
<hr>
<p>added later: The application <em>gedit</em> anticipates plugins being added and their site has about the clearest explanation of a simple plugin procedure I've found in a few minutes of looking around. Try: </p>
<p><a href="https://wiki.gnome.org/Apps/Gedit/PythonPluginHowToOld" rel="nofollow">https://wiki.gnome.org/Apps/Gedit/PythonPluginHowToOld</a></p>
<p>I'd still like to understand your question better. I am unclear whether you 1) want scientists to be able to use your (Python) application quite simply in various ways or 2) want to allow the scientists to add new capabilities to your application. Choice #1 is the situation we faced with the images and that led us to use generic scripts which we modified to suit the need of the moment. Is it Choice #2 which leads you to the idea of plugins, or is it some aspect of your application that makes issuing commands to it impracticable?</p>
| 10 | 2009-05-31T18:05:31Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 932,771 | <p>I enjoyed the nice discussion on different plugin architectures given by Dr Andre Roberge at Pycon 2009. He gives a good overview of different ways of implementing plugins, starting from something really simple.</p>
<p>Its available as a <a href="http://blip.tv/pycon-us-videos-2009-2010-2011/plugins-and-monkeypatching-increasing-flexibility-dealing-with-inflexibility-1958972" rel="nofollow" title="Plugins and Monkeypatching: Increasing Flexibility, Dealing with Inflexibility">podcast</a> (second part following an explanation of monkey-patching) accompanied by a series of <a href="http://aroberge.blogspot.ch/2008/12/plugins-part-1-application.html" rel="nofollow">six blog entries</a>.</p>
<p>I recommend giving it a quick listen before you make a decision.</p>
| 6 | 2009-05-31T20:16:38Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 933,245 | <p><code>module_example.py</code>:</p>
<pre><code>def plugin_main(*args, **kwargs):
print args, kwargs
</code></pre>
<p><code>loader.py</code>:</p>
<pre><code>def load_plugin(name):
mod = __import__("module_%s" % name)
return mod
def call_plugin(name, *args, **kwargs):
plugin = load_plugin(name)
plugin.plugin_main(*args, **kwargs)
call_plugin("example", 1234)
</code></pre>
<p>It's certainly "minimal", it has absolutely no error checking, probably countless security problems, it's not very flexible - but it should how simple a plugin system in Python can be..</p>
<p>You probably want to look into the <a href="http://docs.python.org/library/imp.html">imp</a> module too, although you can do a lot with just <code>__import__</code>, <code>os.listdir</code> and some string manipulation.</p>
| 38 | 2009-06-01T01:11:18Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 2,442,096 | <p><a href="http://martyalchin.com/2008/jan/10/simple-plugin-framework/">Marty Allchin's simple plugin framework</a> is the base I use for my own needs. I really recommand to take a look at it, I think it is really a good start if you want something simple and easily hackable. You can find it also <a href="http://www.djangosnippets.org/snippets/542/">as a Django Snippets</a>.</p>
| 10 | 2010-03-14T12:14:17Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 14,579,111 | <p><a href="http://setuptools.readthedocs.io/en/latest/pkg_resources.html#entry-points" rel="nofollow">setuptools has an EntryPoint</a>:</p>
<blockquote>
<p>Entry points are a simple way for distributions to âadvertiseâ Python
objects (such as functions or classes) for use by other distributions.
Extensible applications and frameworks can search for entry points
with a particular name or group, either from a specific distribution
or from all active distributions on sys.path, and then inspect or load
the advertised objects at will.</p>
</blockquote>
<p>AFAIK this package is always available if you use pip or virtualenv.</p>
| 2 | 2013-01-29T09:03:27Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 19,555,786 | <p>I arrived here looking for a minimal plugin architecture, and found a lot of things that all seemed like overkill to me. So, I've implemented <a href="https://github.com/samwyse/sspp" rel="nofollow">Super Simple Python Plugins</a>. To use it, you create one or more directories and drop a special <code>__init__.py</code> file in each one. Importing those directories will cause all other Python files to be loaded as submodules, and their name(s) will be placed in the <code>__all__</code> list. Then it's up to you to validate/initialize/register those modules. There's an example in the README file.</p>
| 2 | 2013-10-24T02:23:28Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 19,636,157 | <p>When i searching for Python Decorators, found a simple but useful code snippet. It may not fit in your needs but very inspiring.</p>
<p><a href="http://scipy-lectures.github.io/advanced/advanced_python/#a-plugin-registration-system" rel="nofollow">Scipy Advanced Python#Plugin Registration System</a></p>
<pre><code>class WordProcessor(object):
PLUGINS = []
def process(self, text):
for plugin in self.PLUGINS:
text = plugin().cleanup(text)
return text
@classmethod
def plugin(cls, plugin):
cls.PLUGINS.append(plugin)
@WordProcessor.plugin
class CleanMdashesExtension(object):
def cleanup(self, text):
return text.replace('&mdash;', u'\N{em dash}')
</code></pre>
| 4 | 2013-10-28T13:31:23Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 26,282,173 | <p>As one another approach to plugin system, You may check <a href="https://pypi.python.org/pypi/extend_me" rel="nofollow">Extend Me project</a>.</p>
<p>For example, let's define simple class and its extension</p>
<pre><code># Define base class for extensions (mount point)
class MyCoolClass(Extensible):
my_attr_1 = 25
def my_method1(self, arg1):
print('Hello, %s' % arg1)
# Define extension, which implements some aditional logic
# or modifies existing logic of base class (MyCoolClass)
# Also any extension class maby be placed in any module You like,
# It just needs to be imported at start of app
class MyCoolClassExtension1(MyCoolClass):
def my_method1(self, arg1):
super(MyCoolClassExtension1, self).my_method1(arg1.upper())
def my_method2(self, arg1):
print("Good by, %s" % arg1)
</code></pre>
<p>And try to use it:</p>
<pre><code>>>> my_cool_obj = MyCoolClass()
>>> print(my_cool_obj.my_attr_1)
25
>>> my_cool_obj.my_method1('World')
Hello, WORLD
>>> my_cool_obj.my_method2('World')
Good by, World
</code></pre>
<p>And show what is hidden behind the scene:</p>
<pre><code>>>> my_cool_obj.__class__.__bases__
[MyCoolClassExtension1, MyCoolClass]
</code></pre>
<p><em>extend_me</em> library manipulates class creation process via metaclasses, thus in example above, when creating new instance of <code>MyCoolClass</code> we got instance of new class that is subclass of both <code>MyCoolClassExtension</code> and <code>MyCoolClass</code> having functionality of both of them, thanks to Python's <a href="https://docs.python.org/2/tutorial/classes.html#multiple-inheritance" rel="nofollow">multiple inheritance</a></p>
<p>For better control over class creation there are few metaclasses defined in this lib:</p>
<ul>
<li><p><code>ExtensibleType</code> - allows simple extensibility by subclassing</p></li>
<li><p><code>ExtensibleByHashType</code> - similar to ExtensibleType, but haveing ability
to build specialized versions of class, allowing global extension
of base class and extension of specialized versions of class</p></li>
</ul>
<p>This lib is used in <a href="https://github.com/katyukha/openerp-proxy" rel="nofollow">OpenERP Proxy Project</a>, and seems to be working good enough!</p>
<p>For real example of usage, look in <a href="https://github.com/katyukha/openerp-proxy/blob/master/openerp_proxy/ext/field_datetime.py" rel="nofollow">OpenERP Proxy 'field_datetime' extension</a>:</p>
<pre><code>from ..orm.record import Record
import datetime
class RecordDateTime(Record):
""" Provides auto conversion of datetime fields from
string got from server to comparable datetime objects
"""
def _get_field(self, ftype, name):
res = super(RecordDateTime, self)._get_field(ftype, name)
if res and ftype == 'date':
return datetime.datetime.strptime(res, '%Y-%m-%d').date()
elif res and ftype == 'datetime':
return datetime.datetime.strptime(res, '%Y-%m-%d %H:%M:%S')
return res
</code></pre>
<p><code>Record</code> here is extesible object. <code>RecordDateTime</code> is extension.</p>
<p>To enable extension, just import module that contains extension class, and (in case above) all <code>Record</code> objects created after it will have extension class in base classes, thus having all its functionality.</p>
<p>The main advantage of this library is that, code that operates extensible objects, does not need to know about extension and extensions could change everything in extensible objects.</p>
| 2 | 2014-10-09T15:21:33Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 32,225,807 | <p>Actually <em>setuptools</em> works with a "plugins directory", as the following example taken from the project's documentation:
<a href="http://peak.telecommunity.com/DevCenter/PkgResources#locating-plugins" rel="nofollow">http://peak.telecommunity.com/DevCenter/PkgResources#locating-plugins</a></p>
<p>Example usage:</p>
<pre><code>plugin_dirs = ['foo/plugins'] + sys.path
env = Environment(plugin_dirs)
distributions, errors = working_set.find_plugins(env)
map(working_set.add, distributions) # add plugins+libs to sys.path
print("Couldn't load plugins due to: %s" % errors)
</code></pre>
<p>In the long run, setuptools is a much safer choice since it can load plugins without conflicts or missing requirements. Another benefit is that plugins themselves to be extended using the same mechanism, without the original applications having to care about..</p>
| 2 | 2015-08-26T11:46:54Z | [
"python",
"architecture",
"plugins"
] |
Building a minimal plugin architecture in Python | 932,069 | <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p>
<p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p>
<p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p>
<p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
| 129 | 2009-05-31T13:46:41Z | 36,554,110 | <p>Expanding on the @edomaur's answer may I suggest taking a look at <a href="https://bitbucket.org/petar/simple_plugins" rel="nofollow">simple_plugins</a> (shameless plug), which is a simple plugin framework inspired by the <a href="http://martyalchin.com/2008/jan/10/simple-plugin-framework/" rel="nofollow">work of Marty Alchin</a>.</p>
<p>A short usage example based on the project's README:</p>
<pre><code># All plugin info
>>> BaseHttpResponse.plugins.keys()
['valid_ids', 'instances_sorted_by_id', 'id_to_class', 'instances',
'classes', 'class_to_id', 'id_to_instance']
# Plugin info can be accessed using either dict...
>>> BaseHttpResponse.plugins['valid_ids']
set([304, 400, 404, 200, 301])
# ... or object notation
>>> BaseHttpResponse.plugins.valid_ids
set([304, 400, 404, 200, 301])
>>> BaseHttpResponse.plugins.classes
set([<class '__main__.NotFound'>, <class '__main__.OK'>,
<class '__main__.NotModified'>, <class '__main__.BadRequest'>,
<class '__main__.MovedPermanently'>])
>>> BaseHttpResponse.plugins.id_to_class[200]
<class '__main__.OK'>
>>> BaseHttpResponse.plugins.id_to_instance[200]
<OK: 200>
>>> BaseHttpResponse.plugins.instances_sorted_by_id
[<OK: 200>, <MovedPermanently: 301>, <NotModified: 304>, <BadRequest: 400>, <NotFound: 404>]
# Coerce the passed value into the right instance
>>> BaseHttpResponse.coerce(200)
<OK: 200>
</code></pre>
| 1 | 2016-04-11T16:19:47Z | [
"python",
"architecture",
"plugins"
] |
Implementing the Koch Curve? | 932,222 | <p>I was looking at the wikipedia page for the Koch Snowflake (<a href="http://en.wikipedia.org/wiki/Koch%5Fsnowflake" rel="nofollow">here</a>) and was bothered by the all the examples all being in the logo/turtle style. So i set out to make my own that returned a list or coordinates. </p>
<p>My implementation is in python and i basically ripped off the python turtle implementation but replaced the turtle specific stuff with basic trig. It resulted in some ugly code. My challenge for you is to either improve my code or come up with a more elligant solution of your own. It can be in python, or your favorite language.</p>
<p>My Code:</p>
<pre><code>from math import sin, cos, radians
def grow(steps, length = 200, startPos = (0,0)):
angle = 0
try:
jump = float(length) / (3 ** steps)
except:
jump = length
set="F"
for i in xrange(steps): set=set.replace("F", "FLFRFLF")
coords = [startPos]
for move in set:
if move is "F":
coords.append(
(coords[-1][0] + jump * cos(angle),
coords[-1][1] + jump * sin(angle)))
if move is "L":
angle += radians(60)
if move is "R":
angle -= radians(120)
return coords
</code></pre>
<p>EDIT: due to lazy copying, i forgot the import</p>
| 3 | 2009-05-31T15:24:10Z | 932,498 | <p>I don't see it as particularly ugly and I'd only refactor it incrementally, e.g. as a first step (I've removed the <code>try/except</code> because I don't know what you're trying to ward against... if it needs to get back in it should be a bit more explicit, IMHO):</p>
<pre><code>import math
angles = [math.radians(60*x) for x in range(6)]
sines = [math.sin(x) for x in angles]
cosin = [math.cos(x) for x in angles]
def L(angle, coords, jump):
return (angle + 1) % 6
def R(angle, coords, jump):
return (angle + 4) % 6
def F(angle, coords, jump):
coords.append(
(coords[-1][0] + jump * cosin[angle],
coords[-1][1] + jump * sines[angle]))
return angle
decode = dict(L=L, R=R, F=F)
def grow(steps, length=200, startPos=(0,0)):
pathcodes="F"
for i in xrange(steps):
pathcodes = pathcodes.replace("F", "FLFRFLF")
jump = float(length) / (3 ** steps)
coords = [startPos]
angle = 0
for move in pathcodes:
angle = decode[move](angle, coords, jump)
return coords
</code></pre>
<p>If a second step was warranted I'd probably roll this functionality up into a class, but I'm not sure that would make things substantially better (or, better at all, in fact;-).</p>
| 5 | 2009-05-31T17:25:20Z | [
"python",
"fractals"
] |
Implementing the Koch Curve? | 932,222 | <p>I was looking at the wikipedia page for the Koch Snowflake (<a href="http://en.wikipedia.org/wiki/Koch%5Fsnowflake" rel="nofollow">here</a>) and was bothered by the all the examples all being in the logo/turtle style. So i set out to make my own that returned a list or coordinates. </p>
<p>My implementation is in python and i basically ripped off the python turtle implementation but replaced the turtle specific stuff with basic trig. It resulted in some ugly code. My challenge for you is to either improve my code or come up with a more elligant solution of your own. It can be in python, or your favorite language.</p>
<p>My Code:</p>
<pre><code>from math import sin, cos, radians
def grow(steps, length = 200, startPos = (0,0)):
angle = 0
try:
jump = float(length) / (3 ** steps)
except:
jump = length
set="F"
for i in xrange(steps): set=set.replace("F", "FLFRFLF")
coords = [startPos]
for move in set:
if move is "F":
coords.append(
(coords[-1][0] + jump * cos(angle),
coords[-1][1] + jump * sin(angle)))
if move is "L":
angle += radians(60)
if move is "R":
angle -= radians(120)
return coords
</code></pre>
<p>EDIT: due to lazy copying, i forgot the import</p>
| 3 | 2009-05-31T15:24:10Z | 1,542,485 | <p>Mathematica is superior when it comes to math stuff:</p>
<pre><code>points = {{0.0, 1.0}};
koch[pts_] := Join[
pts/3,
(RotationMatrix[60 Degree].#/3 + {1/3, 0}) & /@ pts,
(RotationMatrix[-60 Degree].#/3 + {1/2, 1/Sqrt[12]}) & /@ pts,
(#/3 + {2/3, 0}) & /@ pts
];
Graphics[Line[Nest[koch, points, 5]], PlotRange -> {{0, 1}, {0, 0.3}}] //Print
</code></pre>
| 0 | 2009-10-09T08:07:10Z | [
"python",
"fractals"
] |
Implementing the Koch Curve? | 932,222 | <p>I was looking at the wikipedia page for the Koch Snowflake (<a href="http://en.wikipedia.org/wiki/Koch%5Fsnowflake" rel="nofollow">here</a>) and was bothered by the all the examples all being in the logo/turtle style. So i set out to make my own that returned a list or coordinates. </p>
<p>My implementation is in python and i basically ripped off the python turtle implementation but replaced the turtle specific stuff with basic trig. It resulted in some ugly code. My challenge for you is to either improve my code or come up with a more elligant solution of your own. It can be in python, or your favorite language.</p>
<p>My Code:</p>
<pre><code>from math import sin, cos, radians
def grow(steps, length = 200, startPos = (0,0)):
angle = 0
try:
jump = float(length) / (3 ** steps)
except:
jump = length
set="F"
for i in xrange(steps): set=set.replace("F", "FLFRFLF")
coords = [startPos]
for move in set:
if move is "F":
coords.append(
(coords[-1][0] + jump * cos(angle),
coords[-1][1] + jump * sin(angle)))
if move is "L":
angle += radians(60)
if move is "R":
angle -= radians(120)
return coords
</code></pre>
<p>EDIT: due to lazy copying, i forgot the import</p>
| 3 | 2009-05-31T15:24:10Z | 7,420,270 | <p>I liked your question so much that I posted an answer to it as a new question, so that other people could improve it:</p>
<p><a href="http://stackoverflow.com/questions/7420248">Koch Curve algorithm in Python without using Turtle/Logo logic - suggestion to improve this code?</a></p>
<p>I used no Logo/Turtle stuff, neither trigonometry.</p>
<p>Congrats for being the first one bringing this problem to StackOverflow!</p>
| 1 | 2011-09-14T17:13:00Z | [
"python",
"fractals"
] |
Search functionality for Django | 932,255 | <p>I'm developing a web app using Django, and I'll need to add search functionality soon. Search will be implemented for two models, one being an extension of the auth user class and another one with the fields <code>name</code>, <code>tags</code>, and <code>description</code>. So I guess nothing too scary here in context of searching text.</p>
<p>For development I am using <a href="http://en.wikipedia.org/wiki/SQLite" rel="nofollow">SQLite</a> and as no database specific work has been done, I am at liberty to use any database in production. I'm thinking of choosing between <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="nofollow">PostgreSQL</a> or <a href="http://en.wikipedia.org/wiki/MySQL" rel="nofollow">MySQL</a>.</p>
<p>I have gone through several posts on Internet about search solutions, nevertheless I'd like to get opinions for my simple case. Here are my questions: </p>
<ol>
<li><p>is full-text search an overkill in my case?</p></li>
<li><p>is it better to rely on the database's full-text search support? If so, which database should I use?</p></li>
<li><p>should I use an external search library, such as <a href="http://whoosh.ca/" rel="nofollow">Whoosh</a>, <a href="http://en.wikipedia.org/wiki/Sphinx%5F%28search%5Fengine%29" rel="nofollow">Sphinx</a>, or <a href="http://en.wikipedia.org/wiki/Xapian" rel="nofollow">Xapian</a>? If so, which one?</p></li>
</ol>
<p><strong>EDIT:</strong>
<code>tags</code> is a Tagfield (from the django-tagging app) that sits on a m2m relationship. <code>description</code> is a field that holds HTML and has a max_length of 1024 bytes.</p>
| 2 | 2009-05-31T15:33:44Z | 932,360 | <p>If that field <code>tags</code> means what I think it means, i.e. you plan to store a string which concatenates multiple tags for an item, then you might need full-text search on it... but it's a bad design; rather, you should have a many-many relationship between items and a tags table (in another table, ItemTag or something, with 2 foreign keys that are the primary keys of the items table and tags table).</p>
<p>I can't tell whether you need full-text search on <code>description</code> as I have no indication of what it is -- nor whether you need the reasonable but somewhat rudimentary full-text search that MySQL 5.1 and PostgreSQL 8.3 provide, or the more powerful one in e.g. sphinx... maybe talk a bit more about the context of your app and why you're considering full-text search?</p>
<p>Edit: so it seems the only possible need for full-text search might be on <code>description</code>, and that looks like it's probably limited enough that either MySQL 5.1 or PostgreSQL 8.3 will serve it well. Me, I have a sweet spot for PostgreSQL (even though I'm reasonably expert at MySQL too), but that's a general preference, not specifically connected to full-text search issues. <a href="http://www.espace.com.eg/blog/2009/02/15/full-text-search-postgresql-beats-mysql/">This blog</a> does provide one reason to prefer PostgreSQL: you can have full-text search and still be transactional, while in MySQL full-text indexing only work on MyISAM tables, not InnoDB [[except if you add sphinx, of course]] (also see <a href="http://www.espace.com.eg/blog/2009/03/15/postgresql-an-ultimate-strategy-for-full-text-search/">this follow-on</a> for a bit more on full-text search in PostgreSQL and Lucene). Still, there are of course other considerations involved in picking a DB, and I don't think you'll be doing terribly with either (unless having to add sphinx for full-text plus transaction is a big problem).</p>
| 5 | 2009-05-31T16:15:01Z | [
"python",
"database",
"django",
"search",
"full-text-search"
] |
Search functionality for Django | 932,255 | <p>I'm developing a web app using Django, and I'll need to add search functionality soon. Search will be implemented for two models, one being an extension of the auth user class and another one with the fields <code>name</code>, <code>tags</code>, and <code>description</code>. So I guess nothing too scary here in context of searching text.</p>
<p>For development I am using <a href="http://en.wikipedia.org/wiki/SQLite" rel="nofollow">SQLite</a> and as no database specific work has been done, I am at liberty to use any database in production. I'm thinking of choosing between <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="nofollow">PostgreSQL</a> or <a href="http://en.wikipedia.org/wiki/MySQL" rel="nofollow">MySQL</a>.</p>
<p>I have gone through several posts on Internet about search solutions, nevertheless I'd like to get opinions for my simple case. Here are my questions: </p>
<ol>
<li><p>is full-text search an overkill in my case?</p></li>
<li><p>is it better to rely on the database's full-text search support? If so, which database should I use?</p></li>
<li><p>should I use an external search library, such as <a href="http://whoosh.ca/" rel="nofollow">Whoosh</a>, <a href="http://en.wikipedia.org/wiki/Sphinx%5F%28search%5Fengine%29" rel="nofollow">Sphinx</a>, or <a href="http://en.wikipedia.org/wiki/Xapian" rel="nofollow">Xapian</a>? If so, which one?</p></li>
</ol>
<p><strong>EDIT:</strong>
<code>tags</code> is a Tagfield (from the django-tagging app) that sits on a m2m relationship. <code>description</code> is a field that holds HTML and has a max_length of 1024 bytes.</p>
| 2 | 2009-05-31T15:33:44Z | 932,402 | <p>Whether you need an external library depends on your needs. How much traffic are we talking about? The external libraries are generally better when it comes to performance, but as always there are advantages and disadvantages. I am using Sphinx with django-sphinx plugin, and I would recommend it if you will be doing a lot of searching.</p>
| 0 | 2009-05-31T16:35:01Z | [
"python",
"database",
"django",
"search",
"full-text-search"
] |
Search functionality for Django | 932,255 | <p>I'm developing a web app using Django, and I'll need to add search functionality soon. Search will be implemented for two models, one being an extension of the auth user class and another one with the fields <code>name</code>, <code>tags</code>, and <code>description</code>. So I guess nothing too scary here in context of searching text.</p>
<p>For development I am using <a href="http://en.wikipedia.org/wiki/SQLite" rel="nofollow">SQLite</a> and as no database specific work has been done, I am at liberty to use any database in production. I'm thinking of choosing between <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="nofollow">PostgreSQL</a> or <a href="http://en.wikipedia.org/wiki/MySQL" rel="nofollow">MySQL</a>.</p>
<p>I have gone through several posts on Internet about search solutions, nevertheless I'd like to get opinions for my simple case. Here are my questions: </p>
<ol>
<li><p>is full-text search an overkill in my case?</p></li>
<li><p>is it better to rely on the database's full-text search support? If so, which database should I use?</p></li>
<li><p>should I use an external search library, such as <a href="http://whoosh.ca/" rel="nofollow">Whoosh</a>, <a href="http://en.wikipedia.org/wiki/Sphinx%5F%28search%5Fengine%29" rel="nofollow">Sphinx</a>, or <a href="http://en.wikipedia.org/wiki/Xapian" rel="nofollow">Xapian</a>? If so, which one?</p></li>
</ol>
<p><strong>EDIT:</strong>
<code>tags</code> is a Tagfield (from the django-tagging app) that sits on a m2m relationship. <code>description</code> is a field that holds HTML and has a max_length of 1024 bytes.</p>
| 2 | 2009-05-31T15:33:44Z | 932,427 | <p><a href="http://haystacksearch.org/" rel="nofollow">Haystack</a> looks promising. And it supports <a href="http://whoosh.ca/" rel="nofollow">Whoosh</a> on the back end.</p>
| 0 | 2009-05-31T16:45:25Z | [
"python",
"database",
"django",
"search",
"full-text-search"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.