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 conditional lock
| 625,491
|
<p>How can I implement conditional lock in threaded application, for instance I haw
30 threads that are calling function and for most off the time all threads can access is simultaneous, but depending on function input there can be condition when only one thread can do that one thing. (If value for input is repeated and some thread is still working then I need lock.)</p>
<p>I now that there is module threading with Rlock() but I don't now how to use it in a way that i described it in first part.</p>
<p><strong>Edit</strong>: The question is actually about how to prevent any two threads from running the same function with the same argument at the same time. (Thanks to David for helping me formulate my question :) )</p>
| 0
|
2009-03-09T09:03:54Z
| 625,499
|
<p>Try this: have a lock in the module where your function is, and if the input to the function is such that locking is required, acquire the lock inside the function. Otherwise don't.</p>
<pre><code>l = threading.RLock()
def fn(arg):
if arg == arg_that_needs_lock:
l.acquire()
try:
# do stuff
finally:
l.release()
else:
# do other stuff
</code></pre>
<p><hr /></p>
<p><em>EDIT</em>:</p>
<p>As far as I can tell now, the question is actually about how to prevent any two threads from running the same function with the same argument at the same time. There's no problem with two threads running the same function with different arguments at the same time, though. The simple method to do this, if all valid arguments to the function can be dictionary keys, is to create a dictionary of arguments to locks:</p>
<pre><code>import threading
dict_lock = threading.RLock()
locks = {}
def fn_dict(arg):
dict_lock.acquire()
try:
if arg not in dict:
locks[arg] = threading.RLock()
l = locks[arg]
finally:
dict_lock.release()
l.acquire()
try:
# do stuff
finally:
l.release()
</code></pre>
<p>If your function can be called with many different arguments, though, that amounts to a lot of locks. Probably a better way is to have a set of all arguments with which the function is currently executing, and have the contents of that set protected by a lock. I think this should work:</p>
<pre><code>set_condition = threading.Condition()
current_args = set()
def fn_set(arg):
set_condition.acquire()
try:
while arg in current_args:
set_condition.wait()
current_args.add(arg)
finally:
set_condition.release()
# do stuff
set_condition.acquire()
try:
current_args.remove(arg)
set_condition.notifyAll()
finally:
set_condition.release()
</code></pre>
| 5
|
2009-03-09T09:07:58Z
|
[
"python",
"multithreading"
] |
python conditional lock
| 625,491
|
<p>How can I implement conditional lock in threaded application, for instance I haw
30 threads that are calling function and for most off the time all threads can access is simultaneous, but depending on function input there can be condition when only one thread can do that one thing. (If value for input is repeated and some thread is still working then I need lock.)</p>
<p>I now that there is module threading with Rlock() but I don't now how to use it in a way that i described it in first part.</p>
<p><strong>Edit</strong>: The question is actually about how to prevent any two threads from running the same function with the same argument at the same time. (Thanks to David for helping me formulate my question :) )</p>
| 0
|
2009-03-09T09:03:54Z
| 625,554
|
<p>It sounds like you want something similar to a <a href="http://en.wikipedia.org/wiki/Readers-writer%5Flock" rel="nofollow">Readers-Writer lock</a>.</p>
<p>This is probably not what you want, but might be a clue:</p>
<pre><code>from __future__ import with_statement
import threading
def RWLock(readers = 1, writers = 1):
m = _Monitor(readers, writers)
return (_RWLock(m.r_increment, m.r_decrement), _RWLock(m.w_increment, m.w_decrement))
class _RWLock(object):
def __init__(self, inc, dec):
self.inc = inc
self.dec = dec
def acquire(self):
self.inc()
def release(self):
self.dec()
def __enter__(self):
self.inc()
def __exit__(self):
self.dec()
class _Monitor(object):
def __init__(self, max_readers, max_writers):
self.max_readers = max_readers
self.max_writers = max_writers
self.readers = 0
self.writers = 0
self.monitor = threading.Condition()
def r_increment(self):
with self.monitor:
while self.writers > 0 and self.readers < self.max_readers:
self.monitor.wait()
self.readers += 1
self.monitor.notify()
def r_decrement(self):
with self.monitor:
while self.writers > 0:
self.monitor.wait()
assert(self.readers > 0)
self.readers -= 1
self.monitor.notify()
def w_increment(self):
with self.monitor:
while self.readers > 0 and self.writers < self.max_writers:
self.monitor.wait()
self.writers += 1
self.monitor.notify()
def w_decrement(self):
with self.monitor:
assert(self.writers > 0)
self.writers -= 1
self.monitor.notify()
if __name__ == '__main__':
rl, wl = RWLock()
wl.acquire()
wl.release()
rl.acquire()
rl.release()
</code></pre>
<p>(Unfortunately not tested)</p>
| 1
|
2009-03-09T09:31:39Z
|
[
"python",
"multithreading"
] |
wxpython auinotebook close tab event
| 625,714
|
<p>What event is used when I close a tab in an auinotebook? I tested with
EVT_AUINOTEBOOK_PAGE_CLOSE(D). It didn't work.</p>
<p>I would also like to fire a right click on the tab itself event.</p>
<p>Where can I find all the events that can be used with the aui manager/notebook? Might just be my poor searching skills, but I can't find any lists over the different events that exist, not for mouse/window events either. It would be really handy to have a complete list.</p>
<pre><code>#!/usr/bin/python
#12_aui_notebook1.py
import wx
import wx.lib.inspection
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.nb = wx.aui.AuiNotebook(self)
self.new_panel('Page 1')
self.new_panel('Page 2')
self.new_panel('Page 3')
self.nb.Bind(wx.EVT_AUINOTEBOOK_PAGE_CLOSED, self.close)
def new_panel(self, nm):
pnl = wx.Panel(self)
pnl.identifierTag = nm
self.nb.AddPage(pnl, nm)
self.sizer = wx.BoxSizer()
self.sizer.Add(self.nb, 1, wx.EXPAND)
self.SetSizer(self.sizer)
def close(self, event):
print 'closed'
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, '12_aui_notebook1.py')
frame.Show()
self.SetTopWindow(frame)
return 1
if __name__ == "__main__":
app = MyApp(0)
# wx.lib.inspection.InspectionTool().Show()
app.MainLoop()
</code></pre>
<p>Oerjan Pettersen</p>
| 7
|
2009-03-09T10:26:40Z
| 625,851
|
<p>This is the bind command you want:</p>
<pre><code>self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSED, self.close, self.nb)
</code></pre>
<p>To detect a right click on the tab (e.g. to show a custom context menu):</p>
<pre><code>self.Bind(wx.aui.EVT_AUINOTEBOOK_TAB_RIGHT_DOWN, self.right, self.nb)
</code></pre>
<p>Here's a list of the aui notebook events:</p>
<pre><code>EVT_AUINOTEBOOK_PAGE_CLOSE
EVT_AUINOTEBOOK_PAGE_CLOSED
EVT_AUINOTEBOOK_PAGE_CHANGED
EVT_AUINOTEBOOK_PAGE_CHANGING
EVT_AUINOTEBOOK_BUTTON
EVT_AUINOTEBOOK_BEGIN_DRAG
EVT_AUINOTEBOOK_END_DRAG
EVT_AUINOTEBOOK_DRAG_MOTION
EVT_AUINOTEBOOK_ALLOW_DND
EVT_AUINOTEBOOK_DRAG_DONE
EVT_AUINOTEBOOK_BG_DCLICK
EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN
EVT_AUINOTEBOOK_TAB_MIDDLE_UP
EVT_AUINOTEBOOK_TAB_RIGHT_DOWN
EVT_AUINOTEBOOK_TAB_RIGHT_UP
</code></pre>
<p>From: {python folder}/Lib/site-packages/{wxpython folder}/wx/aui.py</p>
| 8
|
2009-03-09T11:17:31Z
|
[
"python",
"wxpython",
"wxwidgets"
] |
How can I pass all the parameters to a decorator?
| 625,786
|
<p>I tried to trace the execution of some methods using a decorator. Here is the decorator code:</p>
<pre class="lang-py prettyprint-override"><code>def trace(func):
def ofunc(*args):
func_name = func.__name__
xargs = args
print "entering %s with args %s" % (func_name,xargs)
ret_val = func(args)
print "return value %s" % ret_val
print "exiting %s" % (func_name)
return ofunc
</code></pre>
<p>The thing is, if I try to apply this decorator to methods, the self parameter doesn't get sent. Can you tell me why, and how can I fix that?</p>
| 2
|
2009-03-09T10:51:18Z
| 625,806
|
<p>This line is incorrect:</p>
<pre><code>ret_val = func(args)
</code></pre>
<p>You're forgetting to expand the argument list when you're passing it on. It should be:</p>
<pre><code>ret_val = func(*args)
</code></pre>
<p>Sample output with this modification in place:</p>
<pre><code>>>> class Test2:
... @trace
... def test3(self, a, b):
... pass
...
>>> t = Test2()
>>> t.test3(1,2)
entering test3 with args (<__main__.Test2 instance at 0x7ff2b42c>, 1, 2)
return value None
exiting test3
>>>
</code></pre>
<p>If you ever expand your decorator to also take keyword arguments, you'd also need to expand those appropriately when passing them on, using <code>**</code>.</p>
| 6
|
2009-03-09T10:58:51Z
|
[
"python",
"decorator"
] |
Store Django form.cleaned_data in null model field?
| 625,977
|
<p>I have a django model, which has a int field (with null=True, blank=True).
Now when I get a form submit from the user, I assign it like so:</p>
<pre><code>my_model.width= form.cleaned_data['width']
</code></pre>
<p>However sometimes I get an error:</p>
<pre><code>ValueError: invalid literal for int() with base 10: ''
</code></pre>
<p>I was wandering if it's the blank ('') string value that gets assigned to the field?
Because my understanding was the model will treat blank string as null/blank?</p>
<p>Any help would be appreciated in this matter. Thanks.</p>
| 2
|
2009-03-09T12:08:52Z
| 626,130
|
<p>No, it doesn't. If you want to assign NULL, use Python's <code>None</code>. Otherwise Django will try to parse a number from the string and that fails for the empty string. </p>
<p>You can use the <code>or</code> construct to achieve this:</p>
<pre><code>my_model.width = form.cleaned_data['width'] or None
</code></pre>
| 5
|
2009-03-09T13:03:09Z
|
[
"python",
"django"
] |
Loading bundled python framework dependencies using only python
| 626,157
|
<p>I've come across <a href="http://stackoverflow.com/questions/331377/">this question</a> but I don't like the solution that is presented. Shell scripting is operating system dependent. </p>
<p>Is there a python solution to this problem?</p>
<p>I'm not looking for python to machine code compilers, just a way to modify the include paths with python.</p>
| 1
|
2009-03-09T13:09:37Z
| 626,180
|
<p>Generally speaking, python follows the paths in sys.path when trying to resolve library dependencies. <code>sys.path</code> is a list, and it is searched in order. If your application modified <code>sys.path</code> on load to put its own library paths at the front, this should do the trick.</p>
<p>This section from the python docs has a good explanation of how python finds its dependencies: <a href="https://docs.python.org/reference/simple_stmts.html#the-import-statement" rel="nofollow">https://docs.python.org/reference/simple_stmts.html#the-import-statement</a>.</p>
| 3
|
2009-03-09T13:17:18Z
|
[
"python"
] |
Loading bundled python framework dependencies using only python
| 626,157
|
<p>I've come across <a href="http://stackoverflow.com/questions/331377/">this question</a> but I don't like the solution that is presented. Shell scripting is operating system dependent. </p>
<p>Is there a python solution to this problem?</p>
<p>I'm not looking for python to machine code compilers, just a way to modify the include paths with python.</p>
| 1
|
2009-03-09T13:09:37Z
| 626,204
|
<p>Well, as far as I know there are many different pieces of advice on how to do it. </p>
<p>Here are 2 approaches that may help you distribute your app</p>
<p>I/</p>
<p>. include all dependencies in my project directory structure</p>
<p>. manipulate the sys.path to make sure that the app is always looking in my dir structure before looking into the system available modules</p>
<p>(Disclaimer: this solution might not work if C libs are involved)</p>
<p>II/</p>
<p>Another approach is using a tool like <a href="http://peak.telecommunity.com/DevCenter/PythonEggs" rel="nofollow">EasyInstall and eggs</a>. This solution might be a bit more complex, but it will offer you a lot of freedom on how to configure your app and its dependencies (plus it will work with C dependencies).</p>
<p>./alex</p>
| 2
|
2009-03-09T13:22:42Z
|
[
"python"
] |
File editing in python
| 626,617
|
<p>I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories.</p>
<p>The problem is I'm not replacing in place. I'm opening files, passing the contents into memory, and then overwriting the file, like so:</p>
<pre><code>file = open('path/to/file','r')
in_string = file.read()
file.close()
# ...
#Processing logic
# ...
file = open('path/to/file','w')
file.write(out_string)
file.close()
</code></pre>
<p>Besides the obvious performance/memory concerns, which are legitimate, but not so much a problem for my use, there's another drawback to this method. SVN freaks out. I can do some copy and paste workarounds after the fact to fix the checksum error that svn throws on a commit, but it makes the utility pointless.</p>
<p>Is there a better way to do this? I'm guessing that if I were editing the file in place there wouldn't be any sort of problem. How do I go about that?</p>
| 3
|
2009-03-09T15:12:30Z
| 626,638
|
<p>Freaks out how? What you're describing, if it's working, <em>is</em> editing the file "in place", at least as much as <em>vi(1)</em> does.</p>
| 0
|
2009-03-09T15:16:23Z
|
[
"python",
"svn"
] |
File editing in python
| 626,617
|
<p>I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories.</p>
<p>The problem is I'm not replacing in place. I'm opening files, passing the contents into memory, and then overwriting the file, like so:</p>
<pre><code>file = open('path/to/file','r')
in_string = file.read()
file.close()
# ...
#Processing logic
# ...
file = open('path/to/file','w')
file.write(out_string)
file.close()
</code></pre>
<p>Besides the obvious performance/memory concerns, which are legitimate, but not so much a problem for my use, there's another drawback to this method. SVN freaks out. I can do some copy and paste workarounds after the fact to fix the checksum error that svn throws on a commit, but it makes the utility pointless.</p>
<p>Is there a better way to do this? I'm guessing that if I were editing the file in place there wouldn't be any sort of problem. How do I go about that?</p>
| 3
|
2009-03-09T15:12:30Z
| 626,649
|
<p>Try 'file = open('path/to/file', 'w+')'. This means you are updating an existing file, not writing a new one.</p>
| 0
|
2009-03-09T15:18:45Z
|
[
"python",
"svn"
] |
File editing in python
| 626,617
|
<p>I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories.</p>
<p>The problem is I'm not replacing in place. I'm opening files, passing the contents into memory, and then overwriting the file, like so:</p>
<pre><code>file = open('path/to/file','r')
in_string = file.read()
file.close()
# ...
#Processing logic
# ...
file = open('path/to/file','w')
file.write(out_string)
file.close()
</code></pre>
<p>Besides the obvious performance/memory concerns, which are legitimate, but not so much a problem for my use, there's another drawback to this method. SVN freaks out. I can do some copy and paste workarounds after the fact to fix the checksum error that svn throws on a commit, but it makes the utility pointless.</p>
<p>Is there a better way to do this? I'm guessing that if I were editing the file in place there wouldn't be any sort of problem. How do I go about that?</p>
| 3
|
2009-03-09T15:12:30Z
| 626,666
|
<p>I suspect the problem is that you are in fact editing wrong files. Subversion should never raise any errors about check sums when you are just modifying your tracked files -- independently of <em>how</em> you are modifying them.</p>
<p>Maybe you are accidentally editing files in the <code>.svn</code> directory? In <code>.svn/text-base</code>, Subversion stores copies of your files using the same name plus the extension <code>.svn-base</code>, make sure that you are not editing those!</p>
| 8
|
2009-03-09T15:21:22Z
|
[
"python",
"svn"
] |
File editing in python
| 626,617
|
<p>I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories.</p>
<p>The problem is I'm not replacing in place. I'm opening files, passing the contents into memory, and then overwriting the file, like so:</p>
<pre><code>file = open('path/to/file','r')
in_string = file.read()
file.close()
# ...
#Processing logic
# ...
file = open('path/to/file','w')
file.write(out_string)
file.close()
</code></pre>
<p>Besides the obvious performance/memory concerns, which are legitimate, but not so much a problem for my use, there's another drawback to this method. SVN freaks out. I can do some copy and paste workarounds after the fact to fix the checksum error that svn throws on a commit, but it makes the utility pointless.</p>
<p>Is there a better way to do this? I'm guessing that if I were editing the file in place there wouldn't be any sort of problem. How do I go about that?</p>
| 3
|
2009-03-09T15:12:30Z
| 626,667
|
<p>What do you mean by "SVN freaks out"?</p>
<p>Anyway, the way vi/emacs/etc works is as follows:</p>
<pre><code>f = open("/path/to/.file.tmp", "w")
f.write(out_string)
f.close()
os.rename("/path/to/.file.tmp", "/path/to/file")
</code></pre>
<p>(ok, there's actually an "fsync" in there... But I don't know off hand how to do that in Python)</p>
<p>The reason it does that copy is to ensure that, if the system dies half way through writing the new file, the old one is still there... And the 'rename' operation is defined as being atomic, so it will either work (you get 100% of the new file) or not work (you get 100% of the old file) -- you'll never be left with a half-file.</p>
| 2
|
2009-03-09T15:22:11Z
|
[
"python",
"svn"
] |
File editing in python
| 626,617
|
<p>I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories.</p>
<p>The problem is I'm not replacing in place. I'm opening files, passing the contents into memory, and then overwriting the file, like so:</p>
<pre><code>file = open('path/to/file','r')
in_string = file.read()
file.close()
# ...
#Processing logic
# ...
file = open('path/to/file','w')
file.write(out_string)
file.close()
</code></pre>
<p>Besides the obvious performance/memory concerns, which are legitimate, but not so much a problem for my use, there's another drawback to this method. SVN freaks out. I can do some copy and paste workarounds after the fact to fix the checksum error that svn throws on a commit, but it makes the utility pointless.</p>
<p>Is there a better way to do this? I'm guessing that if I were editing the file in place there wouldn't be any sort of problem. How do I go about that?</p>
| 3
|
2009-03-09T15:12:30Z
| 627,369
|
<p>Perhaps the <code>fileinput</code> module can make your code simpler/shorter:</p>
<p>Here's an example:</p>
<pre><code>import fileinput
for line in fileinput.input("test.txt", inplace=1):
print "%d: %s" % (fileinput.filelineno(), line),
</code></pre>
| 1
|
2009-03-09T18:03:39Z
|
[
"python",
"svn"
] |
File editing in python
| 626,617
|
<p>I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories.</p>
<p>The problem is I'm not replacing in place. I'm opening files, passing the contents into memory, and then overwriting the file, like so:</p>
<pre><code>file = open('path/to/file','r')
in_string = file.read()
file.close()
# ...
#Processing logic
# ...
file = open('path/to/file','w')
file.write(out_string)
file.close()
</code></pre>
<p>Besides the obvious performance/memory concerns, which are legitimate, but not so much a problem for my use, there's another drawback to this method. SVN freaks out. I can do some copy and paste workarounds after the fact to fix the checksum error that svn throws on a commit, but it makes the utility pointless.</p>
<p>Is there a better way to do this? I'm guessing that if I were editing the file in place there wouldn't be any sort of problem. How do I go about that?</p>
| 3
|
2009-03-09T15:12:30Z
| 627,374
|
<p>I suspect <a href="http://stackoverflow.com/questions/626617/file-editing-in-python/626666#626666">Ferdinand's answer</a>, that you are recursing into the .svn dir, explains why you are messing up SVN, but note that there is another flaw in the way you are processing files.</p>
<p>If your program is killed, or your computer crashes at the wrong point (when you are writing out the changed contents), you risk losing both the original and new contents of the file. A more robust approach is to perform the following steps:</p>
<ol>
<li>Read the file into memory, and perform your translations</li>
<li>Write the new contents to "filename.new", rather than the original filename.</li>
<li>Delete the original file, and rename "filename.new" to "filename"</li>
</ol>
<p>This way, you won't risk losing data if killed at the wrong point. Note that the <a href="http://docs.python.org/library/fileinput.html" rel="nofollow">fileinput</a> module will handle much of this for you. It can be given a sequence of files to process, and if you specify inplace=True, will redirect stdout to the appropriate file (keeping a backup). You could then structure your code something like:</p>
<pre><code>import os
import fileinput
def allfiles(dir, ignore_dirs=set(['.svn'])):
"""Generator yielding all writable filenames below dir.
Ignores directories specified
"""
for basedir, dirs, files in os.walk(dir):
if basedir in ignore_dirs:
dirs[:]=[] # Don't recurse
continue # Skip this directory
for filename in files:
filename = os.path.join(basedir, filename)
# Check the file is writable
if os.access(filename, os.W_OK):
yield filename
for line in fileinput.input(allfiles(PATH_TO_PROCESS), inplace=True):
line = perform_some_substitution(line)
print line.rstrip("\n") # Print adds a newline, but line already has one
</code></pre>
| 0
|
2009-03-09T18:05:26Z
|
[
"python",
"svn"
] |
Validating a Unicode Name
| 626,697
|
<p>In ASCII, validating a name isn't too difficult: just make sure all the characters are alphabetical.</p>
<p>But what about in Unicode (utf-8) ? How can I make sure there are no commas or underscores (outside of ASCII scope) in a given string?</p>
<p>(ideally in Python)</p>
| 3
|
2009-03-09T15:30:47Z
| 626,721
|
<p>Depending on how you define "name", you could go with checking it against this regex:</p>
<pre><code>^\w+$
</code></pre>
<p>However, this will allow numbers and underscores. To rule them out, you can do a second test against:</p>
<pre><code>[\d_]
</code></pre>
<p>and make your check fail on match. These two could be combined as follows:</p>
<pre><code>^(?:(?![\d_])\w)+$
</code></pre>
<p>But for regex performance reasons, I would rather do two separate checks.</p>
<p>From <a href="http://docs.python.org/library/re.html" rel="nofollow">the docs</a>:</p>
<blockquote>
<p><code>\w</code></p>
<p>When the <code>LOCALE</code> and <code>UNICODE</code> flags are
not specified, matches any
alphanumeric character and the
underscore; this is equivalent to the
set <code>[a-zA-Z0-9_]</code>. With <code>LOCALE</code>, it will
match the set <code>[0-9_]</code> plus whatever
characters are defined as alphanumeric
for the current locale. If <code>UNICODE</code> is
set, this will match the characters
<code>[0-9_]</code> plus whatever is classified as
alphanumeric in the Unicode character
properties database.</p>
</blockquote>
| 1
|
2009-03-09T15:35:53Z
|
[
"python",
"unicode",
"validation",
"character-properties"
] |
Validating a Unicode Name
| 626,697
|
<p>In ASCII, validating a name isn't too difficult: just make sure all the characters are alphabetical.</p>
<p>But what about in Unicode (utf-8) ? How can I make sure there are no commas or underscores (outside of ASCII scope) in a given string?</p>
<p>(ideally in Python)</p>
| 3
|
2009-03-09T15:30:47Z
| 626,722
|
<p>The <code>letters</code> property of the <code>string</code> module should give you what you want. This property is locale-specific, so as long as you know the language of the text being passed to you, you can use <code>setlocale()</code> and validate against those characters.</p>
<p><a href="http://docs.python.org/library/string.html#module-string" rel="nofollow">http://docs.python.org/library/string.html#module-string</a></p>
<p>As you point out, though, in a truly "unicode" world, there's no way at all to know what characters are "alphabetical" unless you know the language. If you don't know the language, you could either default to ASCII, or run through the locales for common languages.</p>
| 0
|
2009-03-09T15:35:58Z
|
[
"python",
"unicode",
"validation",
"character-properties"
] |
Validating a Unicode Name
| 626,697
|
<p>In ASCII, validating a name isn't too difficult: just make sure all the characters are alphabetical.</p>
<p>But what about in Unicode (utf-8) ? How can I make sure there are no commas or underscores (outside of ASCII scope) in a given string?</p>
<p>(ideally in Python)</p>
| 3
|
2009-03-09T15:30:47Z
| 626,745
|
<p>Maybe the <a href="http://docs.python.org/library/unicodedata.html" rel="nofollow">unicodedata module</a> is useful for this task. Especially the <code>category()</code> function. For existing unicode categories look at <a href="http://unicode.org/Public/UNIDATA/UCD.html#General%5FCategory%5FValues" rel="nofollow">unicode.org</a>. You can then filter on punctuation characters etc.</p>
| 5
|
2009-03-09T15:39:52Z
|
[
"python",
"unicode",
"validation",
"character-properties"
] |
Validating a Unicode Name
| 626,697
|
<p>In ASCII, validating a name isn't too difficult: just make sure all the characters are alphabetical.</p>
<p>But what about in Unicode (utf-8) ? How can I make sure there are no commas or underscores (outside of ASCII scope) in a given string?</p>
<p>(ideally in Python)</p>
| 3
|
2009-03-09T15:30:47Z
| 626,790
|
<p>Just convert bytestring (your utf-8) to unicode objects and check if all characters are alphabetic:</p>
<pre><code>s.isalpha()
</code></pre>
<p>This method is locale-dependent for bytestrings.</p>
| 5
|
2009-03-09T15:46:43Z
|
[
"python",
"unicode",
"validation",
"character-properties"
] |
Validating a Unicode Name
| 626,697
|
<p>In ASCII, validating a name isn't too difficult: just make sure all the characters are alphabetical.</p>
<p>But what about in Unicode (utf-8) ? How can I make sure there are no commas or underscores (outside of ASCII scope) in a given string?</p>
<p>(ideally in Python)</p>
| 3
|
2009-03-09T15:30:47Z
| 627,864
|
<p>This might be a step towards a solution:</p>
<pre><code>import unicodedata
EXCEPTIONS= frozenset(u"'.")
CATEGORIES= frozenset( ('Lu', 'Ll', 'Lt', 'Pd', 'Zs') )
# O'Rourke, Franklin D. Roosevelt
def test_unicode_name(unicode_name):
return all(
uchar in EXCEPTIONS
or unicodedata.category(uchar) in CATEGORIES
for uchar in unicode_name)
>>> test_unicode_name(u"Michael O'Rourke")
True
>>> test_unicode_name(u"ΧÏήÏÏÎ¿Ï ÎεÏÏγίοÏ
")
True
>>> test_unicode_name(u"Jean-Luc Géraud")
True
</code></pre>
<p>Add exceptions, and further checks that I possibly missed.</p>
| 1
|
2009-03-09T20:21:06Z
|
[
"python",
"unicode",
"validation",
"character-properties"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 626,764
|
<p>Lists are mutable; tuples are not.</p>
<p>From <a href="http://docs.python.org/2/tutorial/datastructures.html">docs.python.org/2/tutorial/datastructures.html</a> </p>
<blockquote>
<p>Tuples are immutable, and usually contain an heterogeneous sequence of
elements that are accessed via unpacking (see later in this section)
or indexing (or even by attribute in the case of namedtuples). Lists
are mutable, and their elements are usually homogeneous and are
accessed by iterating over the list.</p>
</blockquote>
| 24
|
2009-03-09T15:41:59Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 626,768
|
<p>The key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it.</p>
<p>So if you're going to need to change the values use a List.</p>
<p>Benefits to tuples:</p>
<ol>
<li>Slight performance improvement.</li>
<li>As a tuple is immutable it can be used as a key in a dictionary.</li>
<li>If you can't change it neither can anyone else, which is to say you don't need to worry about any API functions etc. changing your tuple without being asked.</li>
</ol>
| 54
|
2009-03-09T15:42:38Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 626,871
|
<p>Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. <strong>Tuples have structure, lists have order.</strong> </p>
<p>Using this distinction makes code more explicit and understandable.</p>
<p>One example would be pairs of page and line number to reference locations in a book, e.g.:</p>
<pre><code>my_location = (42, 11) # page number, line number
</code></pre>
<p>You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple locations. Naturally one might want to add or remove locations from the list, so it makes sense that lists are mutable. On the other hand it doesn't make sense to add or remove items from an existing location - hence tuples are immutable.</p>
<p>There might be situations where you want to change items within an existing location tuple, for example when iterating through the lines of a page. But tuple immutability forces you to create a new location tuple for each new value. This seems inconvenient on the face of it, but using immutable data like this is a cornerstone of value types and functional programming techniques, which can have substantial advantages.</p>
<p>There are some interesting articles on this issue, e.g. <a href="http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/">"Python Tuples are Not Just Constant Lists"</a> or <a href="http://news.e-scribe.com/397">"Understanding tuples vs. lists in Python"</a>. The official Python documentation <a href="http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences">also mentions this</a> (<em>"Tuples are immutable, and usually contain an heterogeneous sequence ..."</em>).</p>
<p>In a statically typed language like <em>Haskell</em> the values in a tuple generally have different types and the length of the tuple must be fixed. In a list the values all have the same type and the length is not fixed. So the difference is very obvious.</p>
<p>Finally there is the <a href="http://docs.python.org/dev/library/collections.html#collections.namedtuple">namedtuple</a> in Python, which makes sense because a tuple is already supposed to have structure. This underlines the idea that tuples are a light-weight alternative to classes and instances.</p>
| 636
|
2009-03-09T16:02:51Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 627,165
|
<p>If you went for a walk, you could note your coordinates at any instant in an (x,y) tuple.</p>
<p>If you wanted to record your journey, you could append your location every few seconds to a list.</p>
<p>But you couldn't do it the other way around.</p>
| 136
|
2009-03-09T17:14:47Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 627,901
|
<p>Lists are intended to be homogeneous sequences, while tuples are heterogeneous data structures. </p>
| 8
|
2009-03-09T20:29:55Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 16,097,958
|
<p>Lists are for looping, tuples are for structures i.e. <code>"%s %s" %tuple</code>.</p>
<p>Lists are usually homogeneous, tuples are usually heterogeneous. </p>
<p>Lists are for variable length, tuples are for fixed length.</p>
| 11
|
2013-04-19T05:43:14Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 16,960,687
|
<p>The values of <strong>list</strong> can be changed any time but the values of <strong>tuples</strong> can't be change.</p>
<p>The <strong>advantages and disadvantages</strong> depends upon the use. If you have such a data which you never want to change then you should have to use tuple, otherwise list is the best option.</p>
| 4
|
2013-06-06T11:14:54Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 18,181,253
|
<p>It's <a href="http://stackoverflow.com/a/626871/915501">been mentioned</a> that the difference is largely semantic: people expect a tuple and list to represent different information. But this goes further than a guideline, some libraries actually behave differently based on what they are passed. Take numpy for example (copied from <a href="http://stackoverflow.com/q/18181076/915501">another post</a> where I ask for more examples): </p>
<pre><code>>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> idx = (1,1)
>>> a[idx]
4
>>> idx = [1,1]
>>> a[idx]
array([[3, 4, 5],
[3, 4, 5]])
</code></pre>
<p>Point is, while numpy may not be part of the standard library, it's a <em>major</em> python library, and within numpy lists and tuples are completely different things. </p>
| 10
|
2013-08-12T07:06:24Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 18,892,969
|
<p>Difference between list and tuple</p>
<ol>
<li><p><strong>Literal</strong></p>
<pre><code>someTuple = (1,2)
someList = [1,2]
</code></pre></li>
<li><p><strong>Size</strong></p>
<pre><code>a = tuple(range(1000))
b = list(range(1000))
a.__sizeof__() # 8024
b.__sizeof__() # 9088
</code></pre>
<p>Due to the smaller size of a tuple operation with it a bit faster but not that much to mention about until you have a huge amount of elements.</p></li>
<li><p><strong>Permitted operations</strong></p>
<pre><code>b = [1,2]
b[0] = 3 # [3, 2]
a = (1,2)
a[0] = 3 # Error
</code></pre>
<p>that also mean that you can't delete element or sort tuple.
At the same time you could add new element to both list and tuple with the only difference that you will change id of the tuple by adding element</p>
<pre><code>a = (1,2)
b = [1,2]
id(a) # 140230916716520
id(b) # 748527696
a += (3,) # (1, 2, 3)
b += [3] # [1, 2, 3]
id(a) # 140230916878160
id(b) # 748527696
</code></pre></li>
<li><p><strong>Usage</strong></p>
<p>List being mutable can't be used as a key in the dictionary, while tuple can be used. as key in dictionary.</p>
<pre><code>a = (1,2)
b = [1,2]
c = {a: 1} # OK
c = {b: 1} # Error
</code></pre></li>
</ol>
| 157
|
2013-09-19T11:07:28Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 26,128,173
|
<p>List is mutable and tuples is immutable. The main difference between mutable and immutable is memory usage when you are trying to append an item. </p>
<p>When you create a variable, some fixed memory is assigned to the variable. If it is a list, more memory is assigned than actually used. E.g. if current memory assignment is 100 bytes, when you want to append the 101th byte, maybe another 100 bytes will be assigned (in total 200 bytes in this case). </p>
<p>However, if you know that you are not frequently add new elements, then you should use tuples. Tuples assigns exactly size of the memory needed, and hence saves memory, especially when you use large blocks of memory. </p>
| -1
|
2014-09-30T19:01:37Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 36,156,178
|
<p>This is an example of Python lists:</p>
<pre><code>my_list = [0,1,2,3,4]
top_rock_list = ["Bohemian Rhapsody","Kashmir","Sweet Emotion", "Fortunate Son"]
</code></pre>
<p>This is an example of Python tuple:</p>
<pre><code>my_tuple = (a,b,c,d,e)
celebrity_tuple = ("John", "Wayne", 90210, "Actor", "Male", "Dead")
</code></pre>
<p>Python lists and tuples are similar in that they both are ordered collections of values. Besides the shallow difference that lists are created using brackets "[ ... , ... ]" and tuples using parentheses "( ... , ... )", the core technical "hard coded in Python syntax" difference between them is that the elements of a particular tuple are immutable whereas lists are mutable (...so only tuples are hashable and can be used as dictionary/hash keys!). This gives rise to differences in how they can or can't be used (enforced a priori by syntax) and differences in how people choose to use them (encouraged as 'best practices,' a posteriori, this is what <em>smart</em> programers do). The main difference a posteriori in differentiating when tuples are used versus when lists are used lies in what <em>meaning</em> people give to the order of elements. </p>
<p>For tuples, 'order' signifies nothing more than just a specific 'structure' for holding information. What values are found in the first field can easily be switched into the second field as each provides values across two different dimensions or scales. They provide answers to different types of questions and are typically of the form: <em>for a given object/subject, what are its attributes?</em> The object/subject stays constant, the attributes differ.</p>
<p>For lists, 'order' signifies a sequence or a directionality. The second element <em>MUST come after</em> the first element because it's positioned in the 2nd place based on a particular and common scale or dimension. The elements are taken as a whole and mostly provide answers to a single question typically of the form, <em>for a given attribute, how do these objects/subjects compare?</em> The attribute stays constant, the object/subject differs.</p>
<p>There are countless examples of people in popular culture and programmers who don't conform to these differences and there are countless people who might use a salad fork for their main course. At the end of the day, it's fine and both can usually get the job done. </p>
<p><strong>To summerize some of the finer details...</strong></p>
<p><strong>Similarities:</strong></p>
<ol>
<li><em>Duplicates</em> - Both tuples and lists allow for duplicates</li>
<li><p><em>Indexing, Selecting, & Slicing</em> - Both tuples and lists index using integer values found within brackets. So, if you want the first 3 values of a given list or tuple, the syntax would be the same:</p>
<pre><code>>>> my_list[0:3]
[0,1,2]
>>> my_tuple[0:3]
[a,b,c]
</code></pre></li>
<li><p><em>Comparing & Sorting</em> - Two tuples or two lists are both compared by their first element, and if there is a tie, then by the second element, and so on. No further attention is paid to subsequent elements after earlier elements show a difference.</p>
<pre><code>>>> [0,2,0,0,0,0]>[0,0,0,0,0,500]
True
>>> (0,2,0,0,0,0)>(0,0,0,0,0,500)
True
</code></pre></li>
</ol>
<p><strong>Differences:</strong> - A priori, by definition</p>
<ol>
<li><p><em>Syntax</em> - Lists use [], tuples use ()</p></li>
<li><p><em>Mutability</em> - Elements in a given list are mutable, elements in a given tuple are NOT mutable. </p>
<pre><code># Lists are mutable:
>>> top_rock_list
['Bohemian Rhapsody', 'Kashmir', 'Sweet Emotion', 'Fortunate Son']
>>> top_rock_list[1]
'Kashmir'
>>> top_rock_list[1] = "Stairway to Heaven"
>>> top_rock_list
['Bohemian Rhapsody', 'Stairway to Heaven', 'Sweet Emotion', 'Fortunate Son']
# Tuples are NOT mutable:
>>> celebrity_tuple
('John', 'Wayne', 90210, 'Actor', 'Male', 'Dead')
>>> celebrity_tuple[5]
'Dead'
>>> celebrity_tuple[5]="Alive"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
</code></pre></li>
<li><p><em>Hashtables (Dictionaries)</em> - As hashtables (dictionaries) require that its keys are hashable and therefore immutable, only tuples can act as dictionary keys, not lists.</p>
<pre><code>#Lists CAN'T act as keys for hashtables(dictionaries)
>>> my_dict = {[a,b,c]:"some value"}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
#Tuples CAN act as keys for hashtables(dictionaries)
>>> my_dict = {("John","Wayne"): 90210}
>>> my_dict
{('John', 'Wayne'): 90210}
</code></pre></li>
</ol>
<p>Differences - A posteriori, in usage</p>
<ol>
<li><p>Homo vs. Hetereogeneity of Elements - Generally list objects are homogenous and tuple objects are hetereogenious. That is, lists are used for objects/subjects of the same type (like all presidential candidates, or all songs, or all runners) whereas although it's not forced by), whereas tuples are more for heterogenous objects.</p></li>
<li><p>Looping vs. Strucutres - Although both allow for looping (for x in my_list...), it only really makes sense to do it for a list. Tuples are more appropriate for structuring and presenting information (%s %s residing in %s is an %s and presently %s % ("John","Wayne",90210, "Actor","Dead"))</p></li>
</ol>
| 6
|
2016-03-22T13:48:58Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 36,495,737
|
<p>First of all, they both are the Non-scalar object (also known as a compound object) in Python.</p>
<ul>
<li>Tuples, ordered sequence of elements (which can contain any object with no aliasing issue)
<ul>
<li>Immutable (tuple, int, float, str)</li>
<li>Concatenation using <code>+</code> (brand new tuple will be created of course)</li>
<li>Indexing</li>
<li>Slicing</li>
<li>Singleton <code>(3,) # -> (3)</code> instead of <code>(3) # -> 3</code></li>
</ul></li>
<li>List (Array in other languages), ordered sequence of values
<ul>
<li>Mutable</li>
<li>Singleton <code>[3]</code></li>
<li>Cloning <code>new_array = origin_array[:]</code></li>
<li>List comprehension <code>[x**2 for x in range(1,7)]</code> gives you
<code>[1,4,9,16,25,36]</code> (Not readable)</li>
</ul></li>
</ul>
<p>Using list may also cause aliasing bug (Two distinct paths
pointing to the save object).</p>
| 0
|
2016-04-08T09:10:36Z
|
[
"python",
"list",
"tuples"
] |
What's the difference between list and tuples?
| 626,759
|
<p>What's the difference?</p>
<p>What are the advantages / disadvantages of tuples / lists?</p>
| 555
|
2009-03-09T15:41:25Z
| 39,644,028
|
<p>The <a href="https://www.python.org/dev/peps/pep-0484/#the-typing-module" rel="nofollow">PEP 484 -- Type Hints</a> says that the types of elements of a <code>tuple</code> can be individually typed; so that you can say <code>Tuple[str, int, float]</code>; but a <code>list</code>, with <code>List</code> typing class can take only one type parameter: <code>List[str]</code>, which hints that the difference of the 2 really is that the former is heterogeneous, whereas the latter intrinsically homogeneous.</p>
<p>Also, the standard library mostly uses the tuple as a return value from such standard functions where the C would return a <code>struct</code>.</p>
| 0
|
2016-09-22T16:13:04Z
|
[
"python",
"list",
"tuples"
] |
How do I find the Windows common application data folder using Python?
| 626,796
|
<p>I would like my application to store some data for access by all users. Using Python, how can I find where the data should go?</p>
| 28
|
2009-03-09T15:48:55Z
| 626,841
|
<p>Take a look at <a href="http://ginstrom.com/code/winpaths.html">http://ginstrom.com/code/winpaths.html</a>. This is a simple module that will retrieve Windows folder information. The module implements <code>get_common_appdata</code> to get the App Data folder for all users.</p>
| 10
|
2009-03-09T15:58:23Z
|
[
"python",
"windows",
"application-data",
"common-files"
] |
How do I find the Windows common application data folder using Python?
| 626,796
|
<p>I would like my application to store some data for access by all users. Using Python, how can I find where the data should go?</p>
| 28
|
2009-03-09T15:48:55Z
| 626,848
|
<p><em>Previous answer removed due to incompatibility with non-US versions of Windows, and Vista.</em></p>
<p><strong>EDIT:</strong> To expand on Out Into Space's answer, you would use the
<code>winpaths.get_common_appdata</code> function. You can get winpaths using <code>easy_install winpaths</code> or by going to the pypi page, <a href="http://pypi.python.org/pypi/winpaths/" rel="nofollow">http://pypi.python.org/pypi/winpaths/</a>, and downloading the .exe installer.</p>
| 3
|
2009-03-09T15:59:26Z
|
[
"python",
"windows",
"application-data",
"common-files"
] |
How do I find the Windows common application data folder using Python?
| 626,796
|
<p>I would like my application to store some data for access by all users. Using Python, how can I find where the data should go?</p>
| 28
|
2009-03-09T15:48:55Z
| 626,927
|
<p>If you don't want to add a dependency for a third-party module like winpaths, I would recommend using the environment variables already available in Windows: </p>
<ul>
<li><a href="http://windowsitpro.com/article/articleid/23873/what-environment-variables-are-available-in-windows.html"><strong>What environment variables are available in Windows?</strong></a></li>
</ul>
<p>Specifically you probably want <code>ALLUSERSPROFILE</code> to get the location of the common user profile folder, which is where the Application Data directory resides.</p>
<p>e.g.: </p>
<pre><code>C:\> python -c "import os; print os.environ['ALLUSERSPROFILE']"
C:\Documents and Settings\All Users
</code></pre>
<p><strong>EDIT</strong>: Looking at the winpaths module, it's using ctypes so if you wanted to just use the relevant part of the code without installing winpath, you can use this (obviously some error checking omitted for brevity).</p>
<pre><code>import ctypes
from ctypes import wintypes, windll
CSIDL_COMMON_APPDATA = 35
_SHGetFolderPath = windll.shell32.SHGetFolderPathW
_SHGetFolderPath.argtypes = [wintypes.HWND,
ctypes.c_int,
wintypes.HANDLE,
wintypes.DWORD, wintypes.LPCWSTR]
path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH)
result = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf)
print path_buf.value
</code></pre>
<p>Example run: </p>
<pre><code>C:\> python get_common_appdata.py
C:\Documents and Settings\All Users\Application Data
</code></pre>
| 37
|
2009-03-09T16:12:41Z
|
[
"python",
"windows",
"application-data",
"common-files"
] |
How do I find the Windows common application data folder using Python?
| 626,796
|
<p>I would like my application to store some data for access by all users. Using Python, how can I find where the data should go?</p>
| 28
|
2009-03-09T15:48:55Z
| 627,071
|
<p>You can access all of your OS environment variables using the <code>os.environ</code> dictionary in the <code>os</code> module. Choosing which key to use from that dictionary could be tricky, though. In particular, you should remain aware of internationalized (i.e., non-English) versions of Windows when using these paths.</p>
<p><code>os.environ['ALLUSERSPROFILE']</code> should give you the root directory for all users on the computer, but after that be careful not to hard code subdirectory names like "Application Data," because these directories don't exist on non-English versions of Windows. For that matter, you may want to do some research on what versions of Windows you can expect to have the ALLUSERSPROFILE environment variable set (I don't know myself -- it may be universal).</p>
<p>My XP machine here has a COMMONAPPDATA environment variable which points to the All Users\Application Data folder, but my Win2K3 system does not have this environment variable.</p>
| 3
|
2009-03-09T16:51:46Z
|
[
"python",
"windows",
"application-data",
"common-files"
] |
How do I find the Windows common application data folder using Python?
| 626,796
|
<p>I would like my application to store some data for access by all users. Using Python, how can I find where the data should go?</p>
| 28
|
2009-03-09T15:48:55Z
| 1,448,255
|
<p>From <a href="http://snipplr.com/view.php?codeview&id=7354" rel="nofollow">http://snipplr.com/view.php?codeview&id=7354</a></p>
<pre><code>homedir = os.path.expanduser('~')
# ...works on at least windows and linux.
# In windows it points to the user's folder
# (the one directly under Documents and Settings, not My Documents)
# In windows, you can choose to care about local versus roaming profiles.
# You can fetch the current user's through PyWin32.
#
# For example, to ask for the roaming 'Application Data' directory:
# (CSIDL_APPDATA asks for the roaming, CSIDL_LOCAL_APPDATA for the local one)
# (See microsoft references for further CSIDL constants)
try:
from win32com.shell import shellcon, shell
homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
except ImportError: # quick semi-nasty fallback for non-windows/win32com case
homedir = os.path.expanduser("~")
</code></pre>
<p>To get the app-data directory for all users, rather than the current user, just use <code>shellcon.CSIDL_COMMON_APPDATA</code> instead of <code>shellcon.CSIDL_APPDATA</code>.</p>
| 10
|
2009-09-19T09:57:14Z
|
[
"python",
"windows",
"application-data",
"common-files"
] |
How do I find the Windows common application data folder using Python?
| 626,796
|
<p>I would like my application to store some data for access by all users. Using Python, how can I find where the data should go?</p>
| 28
|
2009-03-09T15:48:55Z
| 20,079,912
|
<p>Since <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181.aspx" rel="nofollow">SHGetFolderPath</a> is deprecated, you can also use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb762188.aspx" rel="nofollow">SHGetKnownFolderPath</a> in Vista and newer. This also lets you look up more paths than SHGetFolderPath will. Here's a stripped-down example (full code <a href="https://gist.github.com/mkropat/7550097" rel="nofollow">available on Gist</a>):</p>
<pre><code>import ctypes, sys
from ctypes import windll, wintypes
from uuid import UUID
class GUID(ctypes.Structure): # [1]
_fields_ = [
("Data1", wintypes.DWORD),
("Data2", wintypes.WORD),
("Data3", wintypes.WORD),
("Data4", wintypes.BYTE * 8)
]
def __init__(self, uuid_):
ctypes.Structure.__init__(self)
self.Data1, self.Data2, self.Data3, self.Data4[0], self.Data4[1], rest = uuid_.fields
for i in range(2, 8):
self.Data4[i] = rest>>(8 - i - 1)*8 & 0xff
class FOLDERID: # [2]
LocalAppData = UUID('{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}')
LocalAppDataLow = UUID('{A520A1A4-1780-4FF6-BD18-167343C5AF16}')
RoamingAppData = UUID('{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}')
class UserHandle: # [3]
current = wintypes.HANDLE(0)
common = wintypes.HANDLE(-1)
_CoTaskMemFree = windll.ole32.CoTaskMemFree # [4]
_CoTaskMemFree.restype= None
_CoTaskMemFree.argtypes = [ctypes.c_void_p]
_SHGetKnownFolderPath = windll.shell32.SHGetKnownFolderPath # [5] [3]
_SHGetKnownFolderPath.argtypes = [
ctypes.POINTER(GUID), wintypes.DWORD, wintypes.HANDLE, ctypes.POINTER(ctypes.c_wchar_p)
]
class PathNotFoundException(Exception): pass
def get_path(folderid, user_handle=UserHandle.common):
fid = GUID(folderid)
pPath = ctypes.c_wchar_p()
S_OK = 0
if _SHGetKnownFolderPath(ctypes.byref(fid), 0, user_handle, ctypes.byref(pPath)) != S_OK:
raise PathNotFoundException()
path = pPath.value
_CoTaskMemFree(pPath)
return path
common_data_folder = get_path(FOLDERID.RoamingAppData)
# [1] http://msdn.microsoft.com/en-us/library/windows/desktop/aa373931.aspx
# [2] http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457.aspx
# [3] http://msdn.microsoft.com/en-us/library/windows/desktop/bb762188.aspx
# [4] http://msdn.microsoft.com/en-us/library/windows/desktop/ms680722.aspx
# [5] http://www.themacaque.com/?p=954
</code></pre>
| 0
|
2013-11-19T19:05:26Z
|
[
"python",
"windows",
"application-data",
"common-files"
] |
Is it possible to write to a python frame object as returned by sys._getframe() from python code running within the interpreter?
| 626,835
|
<p>Apropos of <a href="http://stackoverflow.com/questions/541329/is-it-possible-to-programmatically-construct-a-python-stack-frame-and-start-execu">This question</a>, there is a bit of scaffolding within the interpreter to inspect frame objects, which can be retrieved by <code>sys._getframe()</code>. The frame objects appear to be read only, but I can't find anything obvious in the docs that explicitly states this. Can someone confirm whether these objects are writeable (in some way) or read only?</p>
<pre><code>import sys
def foobar():
xx='foo'
ff = sys._getframe()
ff.f_locals['xx'] = 'bar'
print xx
if __name__ == '__main__':
foobar()
</code></pre>
<p>This prints out '<code>foo</code>' when run but the post below demonstrates the variable being writable when run from the current frame in an interactive shell.</p>
| 1
|
2009-03-09T15:57:39Z
| 626,939
|
<p>From CPython source, <code>Objects/frameobject.c</code>:</p>
<pre class="lang-c prettyprint-override"><code>static PyMemberDef frame_memberlist[] = {
{"f_back", T_OBJECT, OFF(f_back), RO},
{"f_code", T_OBJECT, OFF(f_code), RO},
{"f_builtins", T_OBJECT, OFF(f_builtins),RO},
{"f_globals", T_OBJECT, OFF(f_globals), RO},
{"f_lasti", T_INT, OFF(f_lasti), RO},
{"f_exc_type", T_OBJECT, OFF(f_exc_type)},
{"f_exc_value", T_OBJECT, OFF(f_exc_value)},
{"f_exc_traceback", T_OBJECT, OFF(f_exc_traceback)},
{NULL} /* Sentinel */
};
...
static PyGetSetDef frame_getsetlist[] = {
{"f_locals", (getter)frame_getlocals, NULL, NULL},
{"f_lineno", (getter)frame_getlineno,
(setter)frame_setlineno, NULL},
{"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
{"f_restricted",(getter)frame_getrestricted,NULL, NULL},
{0}
};
</code></pre>
<p>For the <code>PyMemberDef</code>, the flags <code>RO</code> or <code>READONLY</code> means it's attributes are read-only. For the <code>PyGetSetDef</code>, if it only has a getter, it's read only. This means all attributes but <code>f_exc_type</code>, <code>f_exc_value</code>, <code>f_exc_traceback</code> and <code>f_trace</code> are read-only after creation. This is also mentioned in the docs, under <a href="http://docs.python.org/reference/datamodel.html#index-1767" rel="nofollow">Data model</a>.</p>
<p>The objects referred to by the attributes is not necessarily read-only. You could do this:</p>
<pre><code>>>> f = sys._getframe()
>>> f.f_locals['foo'] = 3
>>> foo
3
>>>
</code></pre>
<p>Though this works in the interpreter, it fails inside functions. The execution engine uses a separate array for local variables (<code>f_fastlocals</code>), which is merged into <code>f_locals</code> on access, but the converse is not true.</p>
<pre><code>>>> def foo():
... x = 3
... f = sys._getframe()
... print f.f_locals['x']
... x = 4
... print f.f_locals['x']
... d = f.f_locals
... x = 5
... print d['x']
... f.f_locals
... print d['x']
...
>>> foo()
3
4
4
5
>>>
</code></pre>
<p>On the global frame, <code>f_local</code> refers to <code>f_globals</code>, which makes this trick work in the interpreter. Modifying <code>f_globals</code> works, but affects the whole module.</p>
| 7
|
2009-03-09T16:15:24Z
|
[
"python",
"introspection",
"frame",
"sys"
] |
Is it possible to write to a python frame object as returned by sys._getframe() from python code running within the interpreter?
| 626,835
|
<p>Apropos of <a href="http://stackoverflow.com/questions/541329/is-it-possible-to-programmatically-construct-a-python-stack-frame-and-start-execu">This question</a>, there is a bit of scaffolding within the interpreter to inspect frame objects, which can be retrieved by <code>sys._getframe()</code>. The frame objects appear to be read only, but I can't find anything obvious in the docs that explicitly states this. Can someone confirm whether these objects are writeable (in some way) or read only?</p>
<pre><code>import sys
def foobar():
xx='foo'
ff = sys._getframe()
ff.f_locals['xx'] = 'bar'
print xx
if __name__ == '__main__':
foobar()
</code></pre>
<p>This prints out '<code>foo</code>' when run but the post below demonstrates the variable being writable when run from the current frame in an interactive shell.</p>
| 1
|
2009-03-09T15:57:39Z
| 627,145
|
<p>The f_locals['foo'] example by NXC works because the code is in module scope. In that case, f_locals is f_globals, and f_globals is both modifiable and modifications are reflected in the module.</p>
<p>Inside of function scope, locals() and f_locals are writable, but "[changes may not affect the values of local variables used by the interpreter]." [1] It's an implementation choice. In CPython there's a optimized bytecode for local variables, LOAD_FAST. In Python, local variables are (almost always) known once the function is defined, and CPython uses an index lookup to get the variable value, rather than a dictionary lookup.</p>
<p>In theory the dictionary lookup could proxy that table, but that's a lot of work for little gain.</p>
<p>The exceptions to "local variables are known" are if the function uses an exec statement, and the deprecated case of "from module import *". The generated byte code is different, and slower, for these cases.</p>
| 1
|
2009-03-09T17:08:37Z
|
[
"python",
"introspection",
"frame",
"sys"
] |
How to remove an element from a list by index in Python?
| 627,435
|
<p>How to remove an element from a list by index in Python?</p>
<p>I found the <code>list.remove</code> method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.</p>
| 623
|
2009-03-09T18:16:11Z
| 627,441
|
<p>You probably want <code>pop</code>:</p>
<pre><code>a = ['a', 'b', 'c', 'd']
a.pop(1)
# now a is ['a', 'c', 'd']
</code></pre>
<p>By default, <code>pop</code> without any arguments removes the last item:</p>
<pre><code>a = ['a', 'b', 'c', 'd']
a.pop()
# now a is ['a', 'b', 'c']
</code></pre>
| 300
|
2009-03-09T18:17:48Z
|
[
"python",
"list"
] |
How to remove an element from a list by index in Python?
| 627,435
|
<p>How to remove an element from a list by index in Python?</p>
<p>I found the <code>list.remove</code> method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.</p>
| 623
|
2009-03-09T18:16:11Z
| 627,453
|
<p>Use <code>del</code> and specify the element you want to delete with the index:</p>
<pre><code>In [9]: a = range(10)
In [10]: a
Out[10]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [11]: del a[-1]
In [12]: a
Out[12]: [0, 1, 2, 3, 4, 5, 6, 7, 8]
</code></pre>
<p><a href="http://docs.python.org/tutorial/datastructures.html#the-del-statement">Here</a> is the section from the tutorial.</p>
| 730
|
2009-03-09T18:21:24Z
|
[
"python",
"list"
] |
How to remove an element from a list by index in Python?
| 627,435
|
<p>How to remove an element from a list by index in Python?</p>
<p>I found the <code>list.remove</code> method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.</p>
| 623
|
2009-03-09T18:16:11Z
| 19,466,364
|
<p><a href="https://docs.python.org/library/stdtypes.html#mutable-sequence-types"><code>pop</code></a> is also useful to remove and keep an item from a list. Where <code>del</code> actually trashes the item.</p>
<pre><code>>>> x = [1, 2, 3, 4]
>>> p = x.pop(1)
>>> p
2
</code></pre>
| 31
|
2013-10-19T13:10:02Z
|
[
"python",
"list"
] |
How to remove an element from a list by index in Python?
| 627,435
|
<p>How to remove an element from a list by index in Python?</p>
<p>I found the <code>list.remove</code> method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.</p>
| 623
|
2009-03-09T18:16:11Z
| 24,352,671
|
<p>Like others mentioned pop and del are <em>the</em> efficient ways to remove an item of given index.
Yet just for the sake of completion ( since the same thing can be done via many ways in python ):</p>
<p><strong>Using slices ( This does not do inplace removal of item from original list ) :</strong></p>
<p>( Also this will be the least efficient method when working with python list but this could be useful ( but not efficient, I reiterate ) when working with user defined objects that do not support pop, yet do define a <code>__getitem__</code> ): </p>
<pre><code>>>> a = [ 1, 2, 3, 4, 5, 6 ]
>>> index = 3 # Only Positive index
>>> a = a[:index] + a[index+1 :]
# a is now [ 1, 2, 3, 5, 6 ]
</code></pre>
<p><strong>Note:</strong> Please note that this method does not modify the list inplace like <code>pop</code> and <code>del</code>. It instead makes two copies of lists ( one from the start until the index but without it ( <code>a[:index]</code> ) and one after the index till the last element ( <code>a[index+1:]</code> ) ) and creates a new list object by adding both. This is then reassigned to the list variable ( <code>a</code> ). The old list object is hence dereferenced and hence garbage collected ( provided the original list object is not referenced by any variable other than a )</p>
<p>This makes this method very inefficient and it can also produce undesirable side effects ( especially when other variables point to the original list object which remains un-modified )</p>
<p>Thanks to @MarkDickinson for pointing this out ... </p>
<p><a href="http://stackoverflow.com/a/509295/3244627">This</a> Stack Overflow answer explains the concept of slicing.</p>
<p>Also note that this works only with positive indices.</p>
<p>While using with objects, the <code>__getitem__</code> method must have been defined and more importantly the <strong><code>__add__</code></strong> method must have been defined to return an object containing items from both the operands.</p>
<p>In essence this works with any object whose class definition is like :</p>
<pre><code>class foo(object):
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return foo(self.items[index])
def __add__(self, right):
return foo( self.items + right.items )
</code></pre>
<p>This works with <code>list</code> which defines <code>__getitem__</code> and <code>__add__</code> methods.</p>
<p><strong>Comparison of the three ways in terms of efficiency:</strong></p>
<p>Assume the following is predefined : </p>
<pre><code>a = range(10)
index = 3
</code></pre>
<p><strong>The <code>del object[index]</code> method:</strong></p>
<p>By far the most efficient method. Works will all objects that define a <code>__del__</code> method.</p>
<p>The disassembly is as follows : </p>
<p>Code:</p>
<pre><code>def del_method():
global a
global index
del a[index]
</code></pre>
<p>Disassembly:</p>
<pre><code> 10 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 DELETE_SUBSCR # This is the line that deletes the item
7 LOAD_CONST 0 (None)
10 RETURN_VALUE
None
</code></pre>
<p><strong><code>pop</code> method:</strong></p>
<p>Less efficient than the del method. Used when you need to get the deleted item.</p>
<p>Code:</p>
<pre><code>def pop_method():
global a
global index
a.pop(index)
</code></pre>
<p>Disassembly:</p>
<pre><code> 17 0 LOAD_GLOBAL 0 (a)
3 LOAD_ATTR 1 (pop)
6 LOAD_GLOBAL 2 (index)
9 CALL_FUNCTION 1
12 POP_TOP
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
</code></pre>
<p><strong>The slice and add method.</strong></p>
<p>The least efficient.</p>
<p>Code:</p>
<pre><code>def slice_method():
global a
global index
a = a[:index] + a[index+1:]
</code></pre>
<p>Disassembly:</p>
<pre><code> 24 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (index)
6 SLICE+2
7 LOAD_GLOBAL 0 (a)
10 LOAD_GLOBAL 1 (index)
13 LOAD_CONST 1 (1)
16 BINARY_ADD
17 SLICE+1
18 BINARY_ADD
19 STORE_GLOBAL 0 (a)
22 LOAD_CONST 0 (None)
25 RETURN_VALUE
None
</code></pre>
<p>Note : In all three disassembles ignore the last 2 lines which basically are <code>return None</code>
Also the first 2 lines are loading the global values <code>a</code> and <code>index</code>.</p>
| 41
|
2014-06-22T15:21:00Z
|
[
"python",
"list"
] |
How to remove an element from a list by index in Python?
| 627,435
|
<p>How to remove an element from a list by index in Python?</p>
<p>I found the <code>list.remove</code> method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.</p>
| 623
|
2009-03-09T18:16:11Z
| 32,948,546
|
<p>Generally, I am using the following method:</p>
<pre><code>>>> myList = [10,20,30,40,50]
>>> rmovIndxNo = 3
>>> del myList[rmovIndxNo]
>>> myList
[10, 20, 30, 50]
</code></pre>
| 3
|
2015-10-05T12:23:32Z
|
[
"python",
"list"
] |
How to remove an element from a list by index in Python?
| 627,435
|
<p>How to remove an element from a list by index in Python?</p>
<p>I found the <code>list.remove</code> method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.</p>
| 623
|
2009-03-09T18:16:11Z
| 35,122,409
|
<p>One can either use del or pop, but I prefer del, since you can specify index and slices, giving the user more control over the data.</p>
| 0
|
2016-02-01T03:00:01Z
|
[
"python",
"list"
] |
How to remove an element from a list by index in Python?
| 627,435
|
<p>How to remove an element from a list by index in Python?</p>
<p>I found the <code>list.remove</code> method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.</p>
| 623
|
2009-03-09T18:16:11Z
| 38,066,478
|
<p>As previously mentioned, best practice is del(); or pop() if you need to know the value.</p>
<p>An alternate solution is to re-stack only those elements you want:</p>
<pre><code> a = ['a', 'b', 'c', 'd']
def remove_element(list_,index_):
clipboard = []
for i in range(len(list_)):
if i is not index_:
clipboard.append(list_[i])
return clipboard
print(remove_element(a,2))
>> ['a', 'b', 'd']
</code></pre>
<p>eta: hmm... will not work on negative index values, will ponder and update</p>
<p>I suppose </p>
<pre><code>if index_<0:index_=len(list_)+index_
</code></pre>
<p>would patch it... but suddenly this idea seems very brittle. Interesting thought experiment though. Seems there should be a 'proper' way to do this with append() / list comprehension. </p>
<p><em>pondering</em></p>
| 0
|
2016-06-28T03:15:54Z
|
[
"python",
"list"
] |
How can I use named arguments in a decorator?
| 627,501
|
<p>If I have the following function:</p>
<pre><code>
def intercept(func):
# do something here
@intercept(arg1=20)
def whatever(arg1,arg2):
# do something here
</code></pre>
<p>I would like for intercept to fire up only when <strong>arg1</strong> is 20. I would like to be able to pass named parameters to the function. How could I accomplish this?</p>
<p>Here's a little code sample :</p>
<pre><code>
def intercept(func):
def intercepting_func(*args,**kargs):
print "whatever"
return func(*args,**kargs)
return intercepting_func
@intercept(a="g")
def test(a,b):
print "test with %s %s" %(a,b)
test("g","d")
</code></pre>
<p><strong>This throws the following exception TypeError: intercept() got an unexpected keyword argument 'a'</strong></p>
| 4
|
2009-03-09T18:37:20Z
| 627,519
|
<pre><code>from functools import wraps
def intercept(target,**trigger):
def decorator(func):
names = getattr(func,'_names',None)
if names is None:
code = func.func_code
names = code.co_varnames[:code.co_argcount]
@wraps(func)
def decorated(*args,**kwargs):
all_args = kwargs.copy()
for n,v in zip(names,args):
all_args[n] = v
for k,v in trigger.iteritems():
if k in all_args and all_args[k] != v:
break
else:
return target(all_args)
return func(*args,**kwargs)
decorated._names = names
return decorated
return decorator
</code></pre>
<p>Example:</p>
<pre><code>def interceptor1(kwargs):
print 'Intercepted by #1!'
def interceptor2(kwargs):
print 'Intercepted by #2!'
def interceptor3(kwargs):
print 'Intercepted by #3!'
@intercept(interceptor1,arg1=20,arg2=5) # if arg1 == 20 and arg2 == 5
@intercept(interceptor2,arg1=20) # elif arg1 == 20
@intercept(interceptor3,arg2=5) # elif arg2 == 5
def foo(arg1,arg2):
return arg1+arg2
>>> foo(3,4)
7
>>> foo(20,4)
Intercepted by #2!
>>> foo(3,5)
Intercepted by #3!
>>> foo(20,5)
Intercepted by #1!
>>>
</code></pre>
<p><code>functools.wraps</code> does what the "simple decorator" on the wiki does; Updates <code>__doc__</code>, <code>__name__</code> and other attribute of the decorator.</p>
| 7
|
2009-03-09T18:43:30Z
|
[
"python",
"language-features",
"decorator"
] |
How can I use named arguments in a decorator?
| 627,501
|
<p>If I have the following function:</p>
<pre><code>
def intercept(func):
# do something here
@intercept(arg1=20)
def whatever(arg1,arg2):
# do something here
</code></pre>
<p>I would like for intercept to fire up only when <strong>arg1</strong> is 20. I would like to be able to pass named parameters to the function. How could I accomplish this?</p>
<p>Here's a little code sample :</p>
<pre><code>
def intercept(func):
def intercepting_func(*args,**kargs):
print "whatever"
return func(*args,**kargs)
return intercepting_func
@intercept(a="g")
def test(a,b):
print "test with %s %s" %(a,b)
test("g","d")
</code></pre>
<p><strong>This throws the following exception TypeError: intercept() got an unexpected keyword argument 'a'</strong></p>
| 4
|
2009-03-09T18:37:20Z
| 627,527
|
<p>You can do this by using *args and **kwargs in the decorator:</p>
<pre><code>def intercept(func, *dargs, **dkwargs):
def intercepting_func(*args, **kwargs):
if (<some condition on dargs, dkwargs, args and kwargs>):
print 'I intercepted you.'
return func(*args, **kwargs)
return intercepting_func
</code></pre>
<p>It's up to you how you wish to pass in arguments to control the behavior of the decorator.</p>
<p>To make this as transparent as possible to the end user, you can use the "simple decorator" on the <a href="http://wiki.python.org/moin/PythonDecoratorLibrary" rel="nofollow">Python wiki</a> or Michele Simionato's <a href="http://www.phyast.pitt.edu/~micheles/python/documentation.html#id9" rel="nofollow">"decorator decorator"</a></p>
| 3
|
2009-03-09T18:45:26Z
|
[
"python",
"language-features",
"decorator"
] |
How can I use named arguments in a decorator?
| 627,501
|
<p>If I have the following function:</p>
<pre><code>
def intercept(func):
# do something here
@intercept(arg1=20)
def whatever(arg1,arg2):
# do something here
</code></pre>
<p>I would like for intercept to fire up only when <strong>arg1</strong> is 20. I would like to be able to pass named parameters to the function. How could I accomplish this?</p>
<p>Here's a little code sample :</p>
<pre><code>
def intercept(func):
def intercepting_func(*args,**kargs):
print "whatever"
return func(*args,**kargs)
return intercepting_func
@intercept(a="g")
def test(a,b):
print "test with %s %s" %(a,b)
test("g","d")
</code></pre>
<p><strong>This throws the following exception TypeError: intercept() got an unexpected keyword argument 'a'</strong></p>
| 4
|
2009-03-09T18:37:20Z
| 628,309
|
<p>Remember that</p>
<pre><code>@foo
def bar():
pass
</code></pre>
<p>is equivalent to:</p>
<pre><code>def bar():
pass
bar = foo(bar)
</code></pre>
<p>so if you do:</p>
<pre><code>@foo(x=3)
def bar():
pass
</code></pre>
<p>that's equivalent to:</p>
<pre><code>def bar():
pass
bar = foo(x=3)(bar)
</code></pre>
<p>so your decorator needs to look something like this:</p>
<pre><code>def foo(x=1):
def wrap(f):
def f_foo(*args, **kw):
# do something to f
return f(*args, **kw)
return f_foo
return wrap
</code></pre>
<p>In other words, <code>def wrap(f)</code> is really the decorator, and <code>foo(x=3)</code> is a function call that returns a decorator.</p>
| 10
|
2009-03-09T22:38:50Z
|
[
"python",
"language-features",
"decorator"
] |
Form Field API?
| 627,583
|
<p>I am iterating through list of form fields. How do I identify the type of each field? For checkbox I can call field.is_checkbox...are there similar methods for lists, multiplechoicefields etc. ?</p>
<p>Thanks </p>
| 2
|
2009-03-09T19:01:00Z
| 627,592
|
<p>Presuming you're using HTML here... Because it isn't very clear.</p>
<p>How about giving it an extra class.</p>
<p>And if you didn't know allready, the class attribute will recognise this:</p>
<pre><code>class="hello there you"
</code></pre>
<p>as having 3 classes. The class 'hello', the class 'there', and the class 'you'.
So if they allready have a class, just add a space and your custom clasname.</p>
| -1
|
2009-03-09T19:03:52Z
|
[
"python",
"django",
"django-forms"
] |
Form Field API?
| 627,583
|
<p>I am iterating through list of form fields. How do I identify the type of each field? For checkbox I can call field.is_checkbox...are there similar methods for lists, multiplechoicefields etc. ?</p>
<p>Thanks </p>
| 2
|
2009-03-09T19:01:00Z
| 627,622
|
<p>Have a look at the class for each field on your form:</p>
<pre><code>for f_name, f_type in my_form_instance.fields.items():
print "I am a ",type(f_type)
# or f_type.__class__
</code></pre>
<p>This will produce output similar to <code><class 'django.forms.fields.BooleanField'></code>.</p>
<p>You can get the name as a simple string, if you prefer that, with:</p>
<pre><code>print type(f_type).__name__
# produces 'BooleanField'
</code></pre>
<p>Edit: Also be careful about the distinction between a field and a widget. There isn't a Checkbox field in Django, but only a CheckboxInput widget, which is the default for a BooleanField. Do you mean to look up the widget (which is very rendering specific), or the field (which has more of a relation to the data type and validation for that form field)? If the widget, you can get the widget type using:</p>
<pre><code>f_type.widget
</code></pre>
<p>Hope that helps!</p>
| 3
|
2009-03-09T19:13:14Z
|
[
"python",
"django",
"django-forms"
] |
Form Field API?
| 627,583
|
<p>I am iterating through list of form fields. How do I identify the type of each field? For checkbox I can call field.is_checkbox...are there similar methods for lists, multiplechoicefields etc. ?</p>
<p>Thanks </p>
| 2
|
2009-03-09T19:01:00Z
| 627,642
|
<p>I am not sure if this is what you want, but if you want to know what kind of field it is going to end up being in the HTML, you can check it with this:</p>
<pre><code>{% for field in form %}
{{ field.field.widget.input_type }}
{% endfor %}
</code></pre>
<p>widget.input_type will hold text, password, select, etc.</p>
<p>P.S. I did not know this until 5 seconds ago. #django irc.freenode.net always has good help.</p>
| 1
|
2009-03-09T19:22:29Z
|
[
"python",
"django",
"django-forms"
] |
Using Python to get Windows system internals info
| 627,596
|
<p>I'd like to write some quick Python code to assess the CPU, memory, disk, and networking usage of my Windows XP system. </p>
<p>Are there existing Python libraries that would allow me to access that information? Or, are there DLL's that I can call from Python? (If so, a code sample would be appreciated)</p>
| 1
|
2009-03-09T19:06:09Z
| 627,619
|
<p>I think WMI is the resource to use. Especially, look at the <a href="http://msdn.microsoft.com/en-us/library/aa394084%28VS.85%29.aspx" rel="nofollow"><code>Win32_PerfFormattedData*</code> classes in the MSDN</a>.</p>
<p>A quick search turned this up (among others):</p>
<p><a href="http://timgolden.me.uk/python/wmi.html" rel="nofollow">http://timgolden.me.uk/python/wmi.html</a></p>
| 4
|
2009-03-09T19:12:58Z
|
[
"python",
"windows-xp"
] |
Using Python to get Windows system internals info
| 627,596
|
<p>I'd like to write some quick Python code to assess the CPU, memory, disk, and networking usage of my Windows XP system. </p>
<p>Are there existing Python libraries that would allow me to access that information? Or, are there DLL's that I can call from Python? (If so, a code sample would be appreciated)</p>
| 1
|
2009-03-09T19:06:09Z
| 628,334
|
<p>The MS <a href="http://www.microsoft.com/downloads/details.aspx?DisplayLang=en&FamilyID=09dfc342-648b-4119-b7eb-783b0f7d1178" rel="nofollow">Scriptomatic</a> tool can generate WMI scripts in Python as well as VBScript, JScript and Perl.</p>
| 0
|
2009-03-09T22:47:46Z
|
[
"python",
"windows-xp"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 627,731
|
<p>I'd go with Perl. Not everyone will agree with me here, but it's a great language well suited to system administration work, and it'll expose you to some more functional programming constructs. It's a great language for learning how to use the smallest amount of code for a given task, as well.</p>
<p>For the usage scenario you mentioned though, I think PHP may be your best bet still. Python does have some great web frameworks, however, so if you just want to try out a new language for developing web applications, Python might be your bet.</p>
| 10
|
2009-03-09T19:48:40Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 627,764
|
<p>Honestly, the "majority" of my programming has been in Perl and PHP and I recently decided to do my latest project in Python, and I must admit it is very nice to program with. I was hesitant of the whole no curly braces thing as that's what I've always done, but it is really very clean. At the end of the day, though, you can make good web applications with all 3, but if you are dead-set on dropping PHP to try something new I would recommend Python and the Django framework. </p>
| 11
|
2009-03-09T19:56:31Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 627,788
|
<p>I have no experience with Python. I vouch strongly to learn Perl, not out of attrition, but because there is a TON to learn in the platform. The key concepts of Perl are: Do What I Mean (<a href="http://en.wikipedia.org/wiki/DWIM" rel="nofollow">DWIM</a>) and There's More Than One Way To Do It (<a href="http://en.wikipedia.org/wiki/There%5Fis%5Fmore%5Fthan%5Fone%5Fway%5Fto%5Fdo%5Fit" rel="nofollow">TMTOWTDI</a>). This means, hypothetically there's often no wrong way to approach a problem if the problem is adequately solved.</p>
<p>Start with learning the base language of Perl, then extend yourself to learning the key Perl modules, like IO::File, DBI, HTML::Template, XML::LibXML, etc. etc. <a href="http://search.cpan.org" rel="nofollow">search.cpan.org</a> will be your resource. <a href="http://perlmonks.org" rel="nofollow">perlmonks.org</a> will be your guide. Just about everything useful to do will likely have a module published.</p>
<p>Keep in mind that Perl is a dynamic and loosely structured language. Perl is not the platform to enforce draconian OOP standards, but for good reason. You'll find the language extremely flexible.</p>
<p>Where is Perl used? System Admins use it heavily, as already mentioned. You can still do excellent web apps either by simple CGI or MVC framework.</p>
| 7
|
2009-03-09T20:01:48Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 627,790
|
<p>As a Perl programmer, I would normally say Perl. But coming from PHP, I think Perl is too similar and you won't actually get that much out of it. (Not because there isn't a lot to learn, but you are likely to program in Perl using the same style as you program in PHP.)</p>
<p>I'd suggest something completely different: Haskell (suggested by Joel), Lisp, Lua, JavaScript or C. Any one of these would make you a better programmer by opening up new ways of looking at the world.</p>
<p>But there's no reason to stop learning PHP in the meantime.</p>
<p>For a good look at the dark side of these languages, I heartily recommend: <a href="http://stackoverflow.com/questions/282329/what-are-five-things-you-hate-about-your-favorite-language">What are five things you hate about your favorite language?</a></p>
| 3
|
2009-03-09T20:02:01Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 627,794
|
<p>I haven't worked with Python much, but I can tell why I <em>didn't</em> like about Perl when I used it.</p>
<ol>
<li>OO support feels tacked on. OO in perl is very different from OO support in the other languages I've used (which include things like PHP, Java, and C#)</li>
<li>TMTOWTDI (There's More Than One Way To Do It). Good idea in theory, terrible idea in practice as it reduces code readability.</li>
<li>Perl uses a lot of magic symbols.</li>
<li>Perl doesn't support named function arguments, meaning that you need to dig into the @_ array to get the arguments passed to a function (or rather, a sub as perl doesn't have the function keyword). This means you'll see a lot of things like the example below (moved 'cause SO doesn't like code in numbered lists)</li>
</ol>
<p>Having said all that, I'd look into Python. Unless you want to go with something heavier-weight like C++ or C#/Java.</p>
<p>Oh, before I forgot: I wanted to put an example for 4 above, but SO doesn't like putting code in numbered lists:</p>
<pre><code>sub mySub {
#extremely common to see in Perl, as built-ins operators operate on the $_ scalar or @_ array implicitly
my $arg1 = shift;
my $arg2 = shift;
}
</code></pre>
| 7
|
2009-03-09T20:02:32Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 627,862
|
<p>Perl is a very nice language and CPAN has a ton of mature modules that will save you a lot of time. Furthermore, Perl is really moving forwards nowadays with a lot of interesting projects (unlike what uninformed fanboys like to spread around). Even a <a href="http://rakudo.org/">Perl 6 implementation</a> is by now releasing working Perl 6.</p>
<p>I you want to do OO, I would recommend <a href="http://search.cpan.org/dist/Moose/lib/Moose.pm">Moose</a>.</p>
| 24
|
2009-03-09T20:20:42Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 627,879
|
<p>Why isn't there Ruby on your list? Maybe you should give it a try.</p>
| 2
|
2009-03-09T20:23:34Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 627,893
|
<p>If those 2 are your only choices, I would choose Python.</p>
<p>Otherwise you should learn javascript. </p>
<p>No I mean <em>really</em> learn it...</p>
| 1
|
2009-03-09T20:27:15Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 627,972
|
<p>"I'd like to follow OOP structure..." advocates for Python or, even more so if you're open, Ruby. On the other hand, in terms of existing libraries, the order is probably Perl > Python >> Ruby. In terms of your career, Perl on your resume is unlikely to make you stand out, while Python and Ruby may catch the eye of a hiring manager. </p>
<p>As a PHP programmer, you are probably going to see all 3 as somewhat "burdensome" to get a Web page up. All have good solutions for Web frameworks, but none is quite as focussed on rendering a Web page as is PHP. </p>
<p>I think that Python is quite likely to be a better choice for you than Perl. It has many good resources, a large community (although not as large as Perl, probably), "stands out" a little on a resume, and has a good reputation. </p>
| 2
|
2009-03-09T20:46:48Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 628,181
|
<p>If you won't be doing web development with this language, either of them would do. If you are, you may find that doing web development in perl is a bit more complicated, since all of the frameworks require more knowledge of the language.
You can do nice things in both, but my opinion is that perl allows more rapid development.<br/> Also, perl's regexes rock!</p>
| 1
|
2009-03-09T21:55:09Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 628,947
|
<p>I suggest going through a beginner tutorial of each and decide for yourself which fits you better. You'll find you can do what you need to do in either:</p>
<p><strong><a href="http://docs.python.org/tutorial/index.html" rel="nofollow">Python Tutorial</a></strong> (<a href="http://docs.python.org/tutorial/classes.html#class-objects" rel="nofollow">Python Classes</a>)</p>
<p><strong><a href="http://www.perl.com/pub/a/2000/10/begperl1.html" rel="nofollow">Perl Tutorial</a></strong> (<a href="http://perldoc.perl.org/perltoot.html" rel="nofollow">Perl Classes</a>)
(Couldn't find a single 'official' perl tutorial, feel free to suggest one)</p>
<p><hr /></p>
<p>In my experience python provides a cleaner, more straight-forward experience.</p>
<p>My issues with perl:</p>
<ul>
<li><p><a href="http://www.perl.com/pub/a/2001/01/begperl6.html" rel="nofollow">'use strict;', Taint, Warnings?</a> - Ideally these shouldn't be needed.</p></li>
<li><p>Passing variables: @<em>; vs. $</em>, vs shift</p></li>
<li><p>Scoping <a href="http://perldoc.perl.org/functions/my.html" rel="nofollow">my</a>, <a href="http://perldoc.perl.org/functions/local.html" rel="nofollow">local</a>, <a href="http://perldoc.perl.org/functions/our.html" rel="nofollow">ours</a>? (The local defintion seems to particularly point out some confusion with perl, "You really probably want to be using my instead, because local isn't what most people think of as "local".".)</p></li>
</ul>
<p>In general with my perl skills I still find my self referencing documentation for built-in features. Where as in python I find this less so. <em>(I've worked in both roughly the same amount of time, but my general programming expereince has grown with time. In other words, I'd probably be a better perl programmer now)</em></p>
<p>If your a unix command line guru though, perl may come more naturally to you. Or, if your using it mainly as a replacement or extension to command line admin tasks, it may suit your needs fine. In my opinion perl is "faster on the draw" at the command line than python is.</p>
| 3
|
2009-03-10T04:33:54Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 629,604
|
<p>I recently made the step from Perl over to Python, after a couple of Perl-only years. Soon thereafter I discovered I had started to read through all kinds of Python-code just as it were any other easy to read text â something I've never done with Perl. Having to delve into third-party Perl code has always been kind of a nightmare for me, so this came as a very very nice surprise!</p>
<p>For me, this means Python-code is much easier to maintain, which on the long run makes Python much more attractive than Perl.</p>
| 7
|
2009-03-10T10:32:52Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 632,119
|
<p>Python is clean and elegant, and the fact that LOTS of C APIs have been wrapped, gives you powerful hooks to much. I also like the "<a href="http://www.python.org/dev/peps/pep-0020/">Zen of Python</a>".</p>
<ul>
<li>Beautiful is better than ugly.</li>
<li>Explicit is better than implicit.</li>
<li>Simple is better than complex.</li>
<li>Complex is better than complicated.</li>
<li>Flat is better than nested.</li>
<li>Sparse is better than dense.</li>
<li>Readability counts.</li>
<li>Special cases aren't special enough to break the rules.</li>
<li>Although practicality beats purity.</li>
<li>Errors should never pass silently.</li>
<li>Unless explicitly silenced.</li>
<li>In the face of ambiguity, refuse the temptation to guess.</li>
<li>There should be one-- and preferably only one --obvious way to
do it.</li>
<li>Although that way may not be obvious at first unless you're Dutch.</li>
<li>Now is better than never.</li>
<li>Although never is often better than <em>right</em> now.</li>
<li>If the implementation is hard to explain, it's a bad idea.</li>
<li>If the implementation is easy to explain, it may be a good idea.</li>
<li>Namespaces are one honking great idea -- let's do more of those!</li>
</ul>
| 5
|
2009-03-10T20:24:03Z
|
[
"python",
"perl"
] |
Next step after PHP: Perl or Python?
| 627,721
|
<p>It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear <em>others' opinions</em>.</p>
<p>I have experience with <strong>PHP 5</strong>, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.</p>
<p>Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, <strong>its performance is also controversial</strong> and often said to be poor compared to competitors.</p>
<p>In the <a href="http://blog.stackoverflow.com/2009/02/podcast-42/" rel="nofollow">42nd podcast at Stack Overflow blog</a> a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that <strong>every one of them would help</strong>, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.</p>
<p>From a beginner point of view, <s>there are not</s> one may not see (correction suggested by <a href="http://stackoverflow.com/users/10661/s-lott">S. Lott</a>) many differences between <strong>Perl & Python</strong>. I would like You to emphasize their strenghts and weaknesses and name a few unique services.</p>
<p>Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.</p>
<p>First of all, I'd like to follow <strong>OOP structures</strong> and use it fundamentally. I partly planned a multiuser <strong>CMS</strong> using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, <strong>string manipulation</strong> will be used intensively.</p>
<p>If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.</p>
<p>So, here's my question: which one should I try <strong>first</strong> -- Perl || Python?</p>
<p><hr /></p>
<h2>Conclusion</h2>
<p>Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.</p>
<p>I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.</p>
<p>During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.</p>
<p><strong>Edit:</strong> There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.</p>
<p>In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.</p>
| 20
|
2009-03-09T19:45:26Z
| 18,619,414
|
<p>Every dynamic language is from same family. It does not matter Which is the tool you work with it matter how you do..</p>
<p><a href="http://blog.oykko.com/2013/09/python-or-php.html" rel="nofollow">PHP VS PYTHON OT PERL OR RUBY? Stop it</a></p>
<p>As many comments mentioned python is cleaner well sometime whose curly brackets are use full to. You just have to practice. </p>
| 0
|
2013-09-04T16:40:52Z
|
[
"python",
"perl"
] |
Django forms
| 627,772
|
<p>I had asked a question pertaining to this. But I think it would be better to ask my question directly.
I have a "User" table with manytomany relationship with two other tables "Domain" and "Groups".
So in the admin interface I see the Groups and Domains as 2 ModelMultipleChoiceFields.
But I want to present them on the UI in a more user friendly way.
I would like to show each available choice in Domain and Group with a checkbox that is selected/unselected depending on the User properties.
Was wondering if I can do this in admin or I need to write my own view independent of admin. </p>
| 2
|
2009-03-09T19:58:35Z
| 627,936
|
<p>I think the built-in widget <code>CheckboxSelectMultiple</code> does what you want. If it doesn't, you're going to have to create your own widget. The <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#ref-forms-widgets" rel="nofollow">documentation for widgets</a> is a good place to start. The easiest way to start is by copying an existing widget from the Django source and modifying it.</p>
| 2
|
2009-03-09T20:39:20Z
|
[
"python",
"django",
"django-admin"
] |
Django forms
| 627,772
|
<p>I had asked a question pertaining to this. But I think it would be better to ask my question directly.
I have a "User" table with manytomany relationship with two other tables "Domain" and "Groups".
So in the admin interface I see the Groups and Domains as 2 ModelMultipleChoiceFields.
But I want to present them on the UI in a more user friendly way.
I would like to show each available choice in Domain and Group with a checkbox that is selected/unselected depending on the User properties.
Was wondering if I can do this in admin or I need to write my own view independent of admin. </p>
| 2
|
2009-03-09T19:58:35Z
| 627,997
|
<p>I'm not completely sure I understand what you are attempting to do, but perhaps something like <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#filter-horizontal" rel="nofollow">filter_horizontal</a> would do what you want.</p>
| 0
|
2009-03-09T20:52:04Z
|
[
"python",
"django",
"django-admin"
] |
Django forms
| 627,772
|
<p>I had asked a question pertaining to this. But I think it would be better to ask my question directly.
I have a "User" table with manytomany relationship with two other tables "Domain" and "Groups".
So in the admin interface I see the Groups and Domains as 2 ModelMultipleChoiceFields.
But I want to present them on the UI in a more user friendly way.
I would like to show each available choice in Domain and Group with a checkbox that is selected/unselected depending on the User properties.
Was wondering if I can do this in admin or I need to write my own view independent of admin. </p>
| 2
|
2009-03-09T19:58:35Z
| 629,235
|
<p>It actually uses model form by default in the admin. So, you need to overwrite it.</p>
<pre><code>from django import forms
from django.forms import widgets
class DomainForm(forms.ModelForm):
field2 = YourField(widget=widgets.CheckboxSelectMultiple)
class Meta:
model = Domain()
fields = ('field1', 'field2')
</code></pre>
<p>So, In this case i have overwritten the default FIELD2 field type.</p>
| 1
|
2009-03-10T07:36:02Z
|
[
"python",
"django",
"django-admin"
] |
Django forms
| 627,772
|
<p>I had asked a question pertaining to this. But I think it would be better to ask my question directly.
I have a "User" table with manytomany relationship with two other tables "Domain" and "Groups".
So in the admin interface I see the Groups and Domains as 2 ModelMultipleChoiceFields.
But I want to present them on the UI in a more user friendly way.
I would like to show each available choice in Domain and Group with a checkbox that is selected/unselected depending on the User properties.
Was wondering if I can do this in admin or I need to write my own view independent of admin. </p>
| 2
|
2009-03-09T19:58:35Z
| 630,463
|
<p>Well to be precise its the widget that Django Admin choses to show in case of ManyToManyField.
Here in this case its SelectMultiple widget which you feel, is less user friendly.</p>
<p>Well easy part is, you can always chose the widget while using your own ModelForm.
But in case you want that in Django Admin you need a roundtrip. Check this out.</p>
<pre><code>from django.forms import widgets
from django.contrib import admin
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
"""
Get a form Field for a ManyToManyField.
"""
# If it uses an intermediary model, don't show field in admin.
if db_field.rel.through is not None:
return None
if db_field.name in self.raw_id_fields:
kwargs['widget'] = admin.widgets.ManyToManyRawIdWidget(db_field.rel)
kwargs['help_text'] = ''
elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
kwargs['widget'] = admin.widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
else:
kwargs['widget'] = widgets.CheckboxSelectMultiple()
kwargs['help_text'] = ''
return db_field.formfield(**kwargs)
</code></pre>
<p>Now, define your routine admin in admin.py as </p>
<pre><code>class SomeModelAdmin(MyModelAdmin):
search_fields = ['foo', 'bar']
list_display = ('foo',)
ordering = ('-bar',)
admin.site.register(SomeModel, SomeModelAdmin)
</code></pre>
<p>You will get checkboxes in DJango Admin now. Of course you will need some CSS changes.</p>
| 2
|
2009-03-10T14:27:24Z
|
[
"python",
"django",
"django-admin"
] |
Django forms
| 627,772
|
<p>I had asked a question pertaining to this. But I think it would be better to ask my question directly.
I have a "User" table with manytomany relationship with two other tables "Domain" and "Groups".
So in the admin interface I see the Groups and Domains as 2 ModelMultipleChoiceFields.
But I want to present them on the UI in a more user friendly way.
I would like to show each available choice in Domain and Group with a checkbox that is selected/unselected depending on the User properties.
Was wondering if I can do this in admin or I need to write my own view independent of admin. </p>
| 2
|
2009-03-09T19:58:35Z
| 4,285,813
|
<p>You can change django admin interface field widget</p>
<pre><code>from django.forms import widgets
class UserAdmin(admin.ModelAdmin):
model = User
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if db_field.name == 'domain' or db_field.name == 'groups':
kwargs['widget'] = widgets.CheckboxSelectMultiple()
# or just make all the manytomany fields as checkbox
kwargs['widget'] = widgets.CheckboxSelectMultiple()
return db_field.formfield(**kwargs)
# for other field
def formfield_for_dbfield(self, db_field, **kwargs):
.....
return super(UserAdmin, self).formfield_for_dbfield(db_field, **kwargs)
admin.site.register(User, UserAdmin)
</code></pre>
| 0
|
2010-11-26T13:47:34Z
|
[
"python",
"django",
"django-admin"
] |
Python dlopen/dlfunc/dlsym wrappers
| 627,786
|
<p>Anybody knows if actually exists a wrapper or ported library to access to Unix dynamic linker on Python?</p>
| 3
|
2009-03-09T20:01:36Z
| 627,820
|
<p>Would <a href="http://docs.python.org/library/ctypes.html">ctypes</a> do what you want?</p>
| 7
|
2009-03-09T20:09:46Z
|
[
"python",
"linker",
"dlopen"
] |
Python dlopen/dlfunc/dlsym wrappers
| 627,786
|
<p>Anybody knows if actually exists a wrapper or ported library to access to Unix dynamic linker on Python?</p>
| 3
|
2009-03-09T20:01:36Z
| 627,829
|
<p>The module is called <a href="http://docs.python.org/library/dl.html" rel="nofollow">dl</a>:</p>
<pre><code>>>> import dl
>>> dl.open("libfoo.so")
<dl.dl object at 0xb7f580c0>
>>> dl.open("libfoo.so").sym('bar')
1400432
</code></pre>
<p>... though it's nasty and you might want to consider using ctypes or an extension module.</p>
<p><strong>Edit</strong></p>
<p>Apparently, dl is deprecated in 2.6 so you'll want to use ctypes which has a better API anyhow.</p>
| 1
|
2009-03-09T20:12:31Z
|
[
"python",
"linker",
"dlopen"
] |
Django Form Preview - How to work with 'cleaned_data'
| 628,132
|
<p>Thanks to Insin for answering a previous <a href="http://stackoverflow.com/questions/625800/django-form-preview-adding-the-user-to-the-form-before-save">question</a> related to this one.</p>
<p>His answer worked and works well, however, I'm perplexed at the provision of 'cleaned_data', or more precisely, how to use it?</p>
<pre><code>class RegistrationFormPreview(FormPreview):
preview_template = 'workshops/workshop_register_preview.html'
form_template = 'workshops/workshop_register_form.html'
def done(self, request, cleaned_data):
# Do something with the cleaned_data, then redirect
# to a "success" page.
registration = Registration(cleaned_data)
registration.user = request.user
registration.save()
# an attempt to work with cleaned_data throws the error: TypeError
# int() argument must be a string or a number, not 'dict'
# obviously the fk are python objects(?) and not fk_id
# but how to proceed here in an easy way?
# the following works fine, however, it seems to be double handling the POST data
# which had already been processed in the django.formtools.preview.post_post
# method, and passed through to this 'done' method, which is designed to
# be overidden.
'''
form = self.form(request.POST) # instansiate the form with POST data
registration = form.save(commit=False) # save before adding the user
registration.user = request.user # add the user
registration.save() # and save.
'''
return HttpResponseRedirect('/register/success')
</code></pre>
<p>For quick reference, here's the contents of the post_post method:</p>
<pre><code>def post_post(self, request):
"Validates the POST data. If valid, calls done(). Else, redisplays form."
f = self.form(request.POST, auto_id=AUTO_ID)
if f.is_valid():
if self.security_hash(request, f) != request.POST.get(self.unused_name('hash')):
return self.failed_hash(request) # Security hash failed.
return self.done(request, f.cleaned_data)
else:
return render_to_response(self.form_template,
{'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state},
context_instance=RequestContext(request))
</code></pre>
| 3
|
2009-03-09T21:39:21Z
| 628,470
|
<p>I've never tried what you're doing here with a ModelForm before, but you might be able to use the ** operator to expand your cleaned_data dictionary into the keyword arguments expected for your Registration constructor:</p>
<pre><code> registration = Registration (**cleaned_data)
</code></pre>
<p>The constructor to your model classes take keyword arguments that Django's Model meta class converts to instance-level attributes on the resulting object. The ** operator is a calling convention that tells Python to expand your dictionary into those keyword arguments.</p>
<p>In other words...</p>
<p>What you're doing currently is tantamount to this:</p>
<pre><code>registration = Registration ({'key':'value', ...})
</code></pre>
<p>Which is not what you want because the constructor expects keyword arguments as opposed to a dictionary that contains your keyword arguments.</p>
<p>What you want to be doing is this</p>
<pre><code>registration = Registration (key='value', ...)
</code></pre>
<p>Which is analogous to this:</p>
<pre><code>registration = Registration (**{'key':'value', ...})
</code></pre>
<p>Again, I've never tried it, but it seems like it would work as long as you aren't doing anything fancy with your form, such as adding new attributes to it that aren't expected by your Registration constructor. In that case you'd likely have to modify the items in the cleaned_data dictionary prior to doing this.</p>
<p>It does seem like you're losing out on some of the functionality inherent in ModelForms by going through the form preview utility, though. Perhaps you should take your use case to the Django mailing list and see if there's a potential enhancement to this API that could make it work better with ModelForms.</p>
<p><strong>Edit</strong></p>
<p>Short of what I've described above, you can always just extract the fields from your cleaned_data dictionary "by hand" and pass those into your Registration constructor too, but with the caveat that you have to remember to update this code as you add new fields to your model.</p>
<pre><code>registration = Registration (
x=cleaned_data['x'],
y=cleaned_data['y'],
z=cleaned_data['z'],
...
)
</code></pre>
| 9
|
2009-03-09T23:46:11Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
How to run an operation on a collection in Python and collect the results?
| 628,150
|
<p>How to run an operation on a collection in Python and collect the results?</p>
<p>So if I have a list of 100 numbers, and I want to run a function like this for each of them:</p>
<pre><code>Operation ( originalElement, anotherVar ) # returns new number.
</code></pre>
<p>and collect the result like so:</p>
<p>result = another list...</p>
<p>How do I do it? Maybe using lambdas?</p>
| 4
|
2009-03-09T21:45:56Z
| 628,159
|
<p><a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">List comprehensions.</a> In Python they look something like:</p>
<pre><code>a = [f(x) for x in bar]
</code></pre>
<p>Where f(x) is some function and bar is a sequence.</p>
<p>You can define f(x) as a partially applied function with a construct like:</p>
<pre><code>def foo(x):
return lambda f: f*x
</code></pre>
<p>Which will return a function that multiplies the parameter by x. A trivial example of this type of construct used in a list comprehension looks like:</p>
<pre><code>>>> def foo (x):
... return lambda f: f*x
...
>>> a=[1,2,3]
>>> fn_foo = foo(5)
>>> [fn_foo (y) for y in a]
[5, 10, 15]
</code></pre>
<p>Although I don't imagine using this sort of construct in any but fairly esoteric cases. Python is not a true functional language, so it has less scope to do clever tricks with higher order functions than (say) Haskell. You may find applications for this type of construct, but it's not really <em>that</em> pythonic. You could achieve a simple transformation with something like:</p>
<pre><code>>>> y=5
>>> a=[1,2,3]
>>> [x*y for x in a]
[5, 10, 15]
</code></pre>
| 10
|
2009-03-09T21:48:40Z
|
[
"python",
"list",
"lambda"
] |
How to run an operation on a collection in Python and collect the results?
| 628,150
|
<p>How to run an operation on a collection in Python and collect the results?</p>
<p>So if I have a list of 100 numbers, and I want to run a function like this for each of them:</p>
<pre><code>Operation ( originalElement, anotherVar ) # returns new number.
</code></pre>
<p>and collect the result like so:</p>
<p>result = another list...</p>
<p>How do I do it? Maybe using lambdas?</p>
| 4
|
2009-03-09T21:45:56Z
| 628,178
|
<p><a href="http://docs.python.org/tutorial/datastructures.html" rel="nofollow">List comprehensions</a>, <a href="http://www.python.org/dev/peps/pep-0289/" rel="nofollow">generator expressions</a>, <a href="http://docs.python.org/library/functions.html#reduce" rel="nofollow">reduce function</a>.</p>
| 0
|
2009-03-09T21:54:18Z
|
[
"python",
"list",
"lambda"
] |
How to run an operation on a collection in Python and collect the results?
| 628,150
|
<p>How to run an operation on a collection in Python and collect the results?</p>
<p>So if I have a list of 100 numbers, and I want to run a function like this for each of them:</p>
<pre><code>Operation ( originalElement, anotherVar ) # returns new number.
</code></pre>
<p>and collect the result like so:</p>
<p>result = another list...</p>
<p>How do I do it? Maybe using lambdas?</p>
| 4
|
2009-03-09T21:45:56Z
| 629,270
|
<p>Another (somewhat depreciated) method of doing this is:</p>
<p>def kevin(v):
return v*v</p>
<p>vals = range(0,100)</p>
<p>map(kevin,vals)</p>
| 1
|
2009-03-10T07:53:30Z
|
[
"python",
"list",
"lambda"
] |
Single implementation to cover both single and multiple values in Python?
| 628,162
|
<p>Say you have a value like this:</p>
<p>n = 5</p>
<p>and a method that returns the factorial of it, like so:</p>
<p>Factorial ( 5 )</p>
<p>How do you handle multiple values:</p>
<p>nums = [1,2,3,4,5]</p>
<p>Factorial ( nums )</p>
<p>so it returns the factorials of all these values as a list.</p>
<p>What's the cleanest way to handle this, without writing 2 methods? Does python have a good way to handle these kind of situations?</p>
| 4
|
2009-03-09T21:49:37Z
| 628,173
|
<p><a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">List comprehension</a>:</p>
<pre><code>[fac(n) for n in nums]
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Sorry, I misunderstood, you want a method that handles both sequences and single values? I can't imagine why you wouldn't do this with two methods.</p>
<pre><code>def factorial(n):
# implement factorial here
return answer
def factorial_list(nums):
return [factorial(n) for n in nums]
</code></pre>
<p>The alternative would be to do some sort of type-checking, which is better avoided unless you have some terribly compelling reason to do so.</p>
<p><strong>EDIT 2:</strong></p>
<p>MizardX's answer is better, vote for that one. Cheers.</p>
| 9
|
2009-03-09T21:53:08Z
|
[
"python",
"list"
] |
Single implementation to cover both single and multiple values in Python?
| 628,162
|
<p>Say you have a value like this:</p>
<p>n = 5</p>
<p>and a method that returns the factorial of it, like so:</p>
<p>Factorial ( 5 )</p>
<p>How do you handle multiple values:</p>
<p>nums = [1,2,3,4,5]</p>
<p>Factorial ( nums )</p>
<p>so it returns the factorials of all these values as a list.</p>
<p>What's the cleanest way to handle this, without writing 2 methods? Does python have a good way to handle these kind of situations?</p>
| 4
|
2009-03-09T21:49:37Z
| 628,177
|
<p>If you're asking if Python can do method overloading: no. Hence, doing multi-methods like that is a rather un-Pythonic way of defining a method. Also, naming convention usually upper-cases class names, and lower-cases functions/methods.</p>
<p>If you want to go ahead anyway, simplest way would be to just make a branch:</p>
<pre><code>def Factorial(arg):
if getattr(arg, '__iter__', False): # checks if arg is iterable
return [Factorial(x) for x in arg]
else:
# ...
</code></pre>
<p>Or, if you're feeling fancy, you could make a decorator that does this to any function:</p>
<pre><code>def autoMap(f):
def mapped(arg):
if getattr(arg, '__iter__', False):
return [mapped(x) for x in arg]
else:
return f(arg)
return mapped
@autoMap
def fact(x):
if x == 1 or x == 0:
return 1
else:
return fact(x-1) + fact(x-2)
>>> fact(3)
3
>>> fact(4)
5
>>> fact(5)
8
>>> fact(6)
13
>>> fact([3,4,5,6])
[3, 5, 8, 13]
</code></pre>
<p>Although a more Pythonic way is to use variable argument lengths:</p>
<pre><code>def autoMap2(f):
def mapped(*arg):
if len(arg) != 1:
return [f(x) for x in arg]
else:
return f(arg[0])
return mapped
@autoMap2
def fact(n):
# ...
>>> fact(3,4,5,6)
[3, 5, 8, 13]
</code></pre>
<p>Putting the two together into a deep mapping decorator:</p>
<pre><code>def autoDeepMap(f):
def mapped(*args):
if len(args) != 1:
return [mapped(x) for x in args]
elif getattr(args[0], '__iter__', False):
return [mapped(x) for x in args[0]]
else:
return f(args[0])
return mapped
@autoDeepMap
def fact(n):
# ...
>>> fact(0)
1
>>> fact(0,1,2,3,4,5,6)
[1, 1, 2, 3, 5, 8, 13]
>>> fact([0,1,2,3,4,5,6])
[1, 1, 2, 3, 5, 8, 13]
>>> fact([0,1,2],[3,4,5,6])
[[1, 1, 2], [3, 5, 8, 13]]
>>> fact([0,1,2],[3,(4,5),6])
[[1, 1, 2], [3, [5, 8], 13]]
</code></pre>
| 6
|
2009-03-09T21:54:11Z
|
[
"python",
"list"
] |
Single implementation to cover both single and multiple values in Python?
| 628,162
|
<p>Say you have a value like this:</p>
<p>n = 5</p>
<p>and a method that returns the factorial of it, like so:</p>
<p>Factorial ( 5 )</p>
<p>How do you handle multiple values:</p>
<p>nums = [1,2,3,4,5]</p>
<p>Factorial ( nums )</p>
<p>so it returns the factorials of all these values as a list.</p>
<p>What's the cleanest way to handle this, without writing 2 methods? Does python have a good way to handle these kind of situations?</p>
| 4
|
2009-03-09T21:49:37Z
| 628,186
|
<pre><code>def Factorial(arg):
try:
it = iter(arg)
except TypeError:
pass
else:
return [Factorial(x) for x in it]
return math.factorial(arg)
</code></pre>
<p>If it's iterable, apply recursivly. Otherwise, proceed normally.</p>
<p>Alternatively, you could move the last <code>return</code> into the <code>except</code> block.</p>
<p>If you are sure the body of <code>Factorial</code> will never raise <code>TypeError</code>, it could be simplified to:</p>
<pre><code>def Factorial(arg):
try:
return [Factorial(x) for x in arg]
except TypeError:
return math.factorial(arg)
</code></pre>
| 13
|
2009-03-09T21:56:19Z
|
[
"python",
"list"
] |
Single implementation to cover both single and multiple values in Python?
| 628,162
|
<p>Say you have a value like this:</p>
<p>n = 5</p>
<p>and a method that returns the factorial of it, like so:</p>
<p>Factorial ( 5 )</p>
<p>How do you handle multiple values:</p>
<p>nums = [1,2,3,4,5]</p>
<p>Factorial ( nums )</p>
<p>so it returns the factorials of all these values as a list.</p>
<p>What's the cleanest way to handle this, without writing 2 methods? Does python have a good way to handle these kind of situations?</p>
| 4
|
2009-03-09T21:49:37Z
| 628,257
|
<p>This is done sometimes.</p>
<pre><code>def factorial( *args ):
def fact( n ):
if n == 0: return 1
return n*fact(n-1)
return [ fact(a) for a in args ]
</code></pre>
<p>It gives an almost magical function that works with simple values as well as sequences.</p>
<pre><code>>>> factorial(5)
[120]
>>> factorial( 5, 6, 7 )
[120, 720, 5040]
>>> factorial( *[5, 6, 7] )
[120, 720, 5040]
</code></pre>
| 7
|
2009-03-09T22:20:37Z
|
[
"python",
"list"
] |
Single implementation to cover both single and multiple values in Python?
| 628,162
|
<p>Say you have a value like this:</p>
<p>n = 5</p>
<p>and a method that returns the factorial of it, like so:</p>
<p>Factorial ( 5 )</p>
<p>How do you handle multiple values:</p>
<p>nums = [1,2,3,4,5]</p>
<p>Factorial ( nums )</p>
<p>so it returns the factorials of all these values as a list.</p>
<p>What's the cleanest way to handle this, without writing 2 methods? Does python have a good way to handle these kind of situations?</p>
| 4
|
2009-03-09T21:49:37Z
| 628,265
|
<p>Or if you don't like the list comprehension syntax, and wish to skip having a new method:</p>
<pre><code>def factorial(num):
if num == 0:
return 1
elif num > 0:
return num * factorial(num - 1)
else:
raise Exception("Negative num has no factorial.")
nums = [1, 2, 3, 4, 5]
# [1, 2, 3, 4, 5]
map(factorial, nums)
# [1, 2, 6, 24, 120, 720]
</code></pre>
| 3
|
2009-03-09T22:22:41Z
|
[
"python",
"list"
] |
Single implementation to cover both single and multiple values in Python?
| 628,162
|
<p>Say you have a value like this:</p>
<p>n = 5</p>
<p>and a method that returns the factorial of it, like so:</p>
<p>Factorial ( 5 )</p>
<p>How do you handle multiple values:</p>
<p>nums = [1,2,3,4,5]</p>
<p>Factorial ( nums )</p>
<p>so it returns the factorials of all these values as a list.</p>
<p>What's the cleanest way to handle this, without writing 2 methods? Does python have a good way to handle these kind of situations?</p>
| 4
|
2009-03-09T21:49:37Z
| 628,313
|
<p>You might want to take a look at NumPy/SciPy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html" rel="nofollow">vectorize</a>.</p>
<p>In the numpy world, given your single-int-arg Factorial function,
you'd do things like</p>
<pre><code> vFactorial=np.vectorize(Factorial)
vFactorial([1,2,3,4,5])
vFactorial(6)
</code></pre>
<p>although note that the last case returns a single-element numpy array rather than a raw int.</p>
| 3
|
2009-03-09T22:39:54Z
|
[
"python",
"list"
] |
Python equivalent to java.util.SortedSet?
| 628,192
|
<p>Does anybody know if Python has an equivalent to Java's SortedSet interface?</p>
<p>Heres what I'm looking for: lets say I have an object of type <code>foo</code>, and I know how to compare two objects of type <code>foo</code> to see whether <code>foo1</code> is "greater than" or "less than" <code>foo2</code>. I want a way of storing many objects of type <code>foo</code> in a list <code>L</code>, so that whenever I traverse the list <code>L</code>, I get the objects in order, according to the comparison method I define.</p>
<h3>Edit:</h3>
<p>I guess I can use a dictionary or a list and <code>sort()</code> it every time I modify it, but is this the best way?</p>
| 19
|
2009-03-09T21:58:14Z
| 628,246
|
<p>If you only need the keys, and no associated value, Python offers sets:</p>
<pre><code>s = set(a_list)
for k in sorted(s):
print k
</code></pre>
<p>However, you'll be sorting the set each time you do this.
If that is too much overhead you may want to look at <a href="http://docs.python.org/library/heapq.html" rel="nofollow">HeapQueues</a>. They may not be as elegant and "Pythonic" but maybe they suit your needs.</p>
| 3
|
2009-03-09T22:16:35Z
|
[
"python",
"data-structures"
] |
Python equivalent to java.util.SortedSet?
| 628,192
|
<p>Does anybody know if Python has an equivalent to Java's SortedSet interface?</p>
<p>Heres what I'm looking for: lets say I have an object of type <code>foo</code>, and I know how to compare two objects of type <code>foo</code> to see whether <code>foo1</code> is "greater than" or "less than" <code>foo2</code>. I want a way of storing many objects of type <code>foo</code> in a list <code>L</code>, so that whenever I traverse the list <code>L</code>, I get the objects in order, according to the comparison method I define.</p>
<h3>Edit:</h3>
<p>I guess I can use a dictionary or a list and <code>sort()</code> it every time I modify it, but is this the best way?</p>
| 19
|
2009-03-09T21:58:14Z
| 628,264
|
<p>You can use <code>insort</code> from the <a href="http://docs.python.org/library/bisect.html#module-bisect"><code>bisect</code></a> module to insert new elements efficiently in an already sorted list:</p>
<pre><code>from bisect import insort
items = [1,5,7,9]
insort(items, 3)
insort(items, 10)
print items # -> [1, 3, 5, 7, 9, 10]
</code></pre>
<p>Note that this does not directly correspond to <code>SortedSet</code>, because it uses a list. If you insert the same item more than once you will have duplicates in the list.</p>
| 12
|
2009-03-09T22:22:21Z
|
[
"python",
"data-structures"
] |
Python equivalent to java.util.SortedSet?
| 628,192
|
<p>Does anybody know if Python has an equivalent to Java's SortedSet interface?</p>
<p>Heres what I'm looking for: lets say I have an object of type <code>foo</code>, and I know how to compare two objects of type <code>foo</code> to see whether <code>foo1</code> is "greater than" or "less than" <code>foo2</code>. I want a way of storing many objects of type <code>foo</code> in a list <code>L</code>, so that whenever I traverse the list <code>L</code>, I get the objects in order, according to the comparison method I define.</p>
<h3>Edit:</h3>
<p>I guess I can use a dictionary or a list and <code>sort()</code> it every time I modify it, but is this the best way?</p>
| 19
|
2009-03-09T21:58:14Z
| 628,319
|
<p>If you're looking for an implementation of an efficient container type for Python implemented using something like a balanced search tree (A Red-Black tree for example) then it's not part of the standard library.</p>
<p>I was able to find this, though:</p>
<p><a href="http://www.brpreiss.com/books/opus7/" rel="nofollow">http://www.brpreiss.com/books/opus7/</a></p>
<p>The source code is available here:</p>
<p><a href="http://www.brpreiss.com/books/opus7/public/Opus7-1.0.tar.gz" rel="nofollow">http://www.brpreiss.com/books/opus7/public/Opus7-1.0.tar.gz</a></p>
<p>I don't know how the source code is licensed, and I haven't used it myself, but it would be a good place to start looking if you're not interested in rolling your own container classes.</p>
<p>There's <a href="http://linux.softpedia.com/get/Programming/Libraries/pyavl-43893.shtml" rel="nofollow">PyAVL</a> which is a C module implementing an AVL tree.</p>
<p>Also, <a href="http://mail.python.org/pipermail/python-list/2007-September/628938.html" rel="nofollow">this thread</a> might be useful to you. It contains a lot of suggestions on how to use the bisect module to enhance the existing Python dictionary to do what you're asking.</p>
<p>Of course, using insort() that way would be pretty expensive for insertion and deletion, so consider it carefully for your application. Implementing an appropriate data structure would probably be a better approach.</p>
<p>In any case, to understand whether you should keep the data structure sorted or sort it when you iterate over it you'll have to know whether you intend to insert a lot or iterate a lot. Keeping the data structure sorted makes sense if you modify its content relatively infrequently but iterate over it a lot. Conversely, if you insert and delete members all the time but iterate over the collection relatively infrequently, sorting the collection of keys before iterating will be faster. There is no one correct approach. </p>
| 4
|
2009-03-09T22:41:52Z
|
[
"python",
"data-structures"
] |
Python equivalent to java.util.SortedSet?
| 628,192
|
<p>Does anybody know if Python has an equivalent to Java's SortedSet interface?</p>
<p>Heres what I'm looking for: lets say I have an object of type <code>foo</code>, and I know how to compare two objects of type <code>foo</code> to see whether <code>foo1</code> is "greater than" or "less than" <code>foo2</code>. I want a way of storing many objects of type <code>foo</code> in a list <code>L</code>, so that whenever I traverse the list <code>L</code>, I get the objects in order, according to the comparison method I define.</p>
<h3>Edit:</h3>
<p>I guess I can use a dictionary or a list and <code>sort()</code> it every time I modify it, but is this the best way?</p>
| 19
|
2009-03-09T21:58:14Z
| 628,432
|
<p>Take a look at <a href="http://pypi.python.org/pypi?%3Aaction=search&term=btree">BTrees</a>. It look like you need one of them. As far as I understood you need structure that will support relatively cheap insertion of element into storage structure and cheap sorting operation (or even lack of it). BTrees offers that.</p>
<p>I've experience with ZODB.BTrees, and they scale to thousands and millions of elements.</p>
| 11
|
2009-03-09T23:33:08Z
|
[
"python",
"data-structures"
] |
Python equivalent to java.util.SortedSet?
| 628,192
|
<p>Does anybody know if Python has an equivalent to Java's SortedSet interface?</p>
<p>Heres what I'm looking for: lets say I have an object of type <code>foo</code>, and I know how to compare two objects of type <code>foo</code> to see whether <code>foo1</code> is "greater than" or "less than" <code>foo2</code>. I want a way of storing many objects of type <code>foo</code> in a list <code>L</code>, so that whenever I traverse the list <code>L</code>, I get the objects in order, according to the comparison method I define.</p>
<h3>Edit:</h3>
<p>I guess I can use a dictionary or a list and <code>sort()</code> it every time I modify it, but is this the best way?</p>
| 19
|
2009-03-09T21:58:14Z
| 12,309,435
|
<p>Use <code>blist.sortedlist</code> from the <a href="http://pypi.python.org/pypi/blist/" rel="nofollow">blist package</a>.</p>
<pre><code>from blist import sortedlist
z = sortedlist([2, 3, 5, 7, 11])
z.add(6)
z.add(3)
z.add(10)
print z
</code></pre>
<p>This will output:</p>
<pre><code>sortedlist([2, 3, 3, 5, 6, 7, 10, 11])
</code></pre>
<p>The resulting object can be used just like a python list.</p>
<pre><code>>>> len(z)
8
>>> [2 * x for x in z]
[4, 6, 6, 10, 12, 14, 20, 22]
</code></pre>
| 2
|
2012-09-06T22:36:48Z
|
[
"python",
"data-structures"
] |
Python equivalent to java.util.SortedSet?
| 628,192
|
<p>Does anybody know if Python has an equivalent to Java's SortedSet interface?</p>
<p>Heres what I'm looking for: lets say I have an object of type <code>foo</code>, and I know how to compare two objects of type <code>foo</code> to see whether <code>foo1</code> is "greater than" or "less than" <code>foo2</code>. I want a way of storing many objects of type <code>foo</code> in a list <code>L</code>, so that whenever I traverse the list <code>L</code>, I get the objects in order, according to the comparison method I define.</p>
<h3>Edit:</h3>
<p>I guess I can use a dictionary or a list and <code>sort()</code> it every time I modify it, but is this the best way?</p>
| 19
|
2009-03-09T21:58:14Z
| 20,666,684
|
<p>Do you have the possibility of using Jython? I just mention it because using TreeMap, TreeSet, etc. is trivial. Also if you're coming from a Java background and you want to head in a Pythonic direction Jython is wonderful for making the transition easier. Though I recognise that use of TreeSet in this case would not be part of such a "transition".</p>
<p>For Jython superusers I have a question myself: the blist package can't be imported because it uses a C file which must be imported. But would there be any advantage of using blist instead of TreeSet? Can we generally assume the JVM uses algorithms which are essentially as good as those of CPython stuff?</p>
| 0
|
2013-12-18T19:24:11Z
|
[
"python",
"data-structures"
] |
Python equivalent to java.util.SortedSet?
| 628,192
|
<p>Does anybody know if Python has an equivalent to Java's SortedSet interface?</p>
<p>Heres what I'm looking for: lets say I have an object of type <code>foo</code>, and I know how to compare two objects of type <code>foo</code> to see whether <code>foo1</code> is "greater than" or "less than" <code>foo2</code>. I want a way of storing many objects of type <code>foo</code> in a list <code>L</code>, so that whenever I traverse the list <code>L</code>, I get the objects in order, according to the comparison method I define.</p>
<h3>Edit:</h3>
<p>I guess I can use a dictionary or a list and <code>sort()</code> it every time I modify it, but is this the best way?</p>
| 19
|
2009-03-09T21:58:14Z
| 25,988,158
|
<p>Similar to blist.sortedlist, the <a href="http://www.grantjenks.com/docs/sortedcontainers/" rel="nofollow">sortedcontainers</a> module provides a sorted list, sorted set, and sorted dict data type. It uses a modified B-tree in the underlying implementation and is faster than blist in most cases.</p>
<p>The sortedcontainers module is pure-Python so installation is easy:</p>
<pre><code>pip install sortedcontainers
</code></pre>
<p>Then for example:</p>
<pre><code>from sortedcontainers import SortedList, SortedDict, SortedSet
help(SortedList)
</code></pre>
<p>The sortedcontainers module has 100% coverage testing and hours of stress. There's a pretty comprehensive <a href="http://www.grantjenks.com/docs/sortedcontainers/performance.html" rel="nofollow">performance comparison</a> that lists most of the options you'd consider for this.</p>
| 2
|
2014-09-23T06:19:16Z
|
[
"python",
"data-structures"
] |
Decoding HTML Entities With Python
| 628,332
|
<p>The following Python code uses BeautifulStoneSoup to fetch the LibraryThing API information for Tolkien's "The Children of Húrin".</p>
<pre><code>import urllib2
from BeautifulSoup import BeautifulStoneSoup
URL = ("http://www.librarything.com/services/rest/1.0/"
"?method=librarything.ck.getwork&id=1907912"
"&apikey=2a2e596b887f554db2bbbf3b07ff812a")
soup = BeautifulStoneSoup(urllib2.urlopen(URL),
convertEntities=BeautifulStoneSoup.ALL_ENTITIES)
title_field = soup.find('field', attrs={'name': 'canonicaltitle'})
print title_field.find('fact').string
</code></pre>
<p>Unfortunately, instead of 'Húrin', it prints out 'Húrin'. This is obviously an encoding issue, but I can't work out what I need to do to get the expected output. Help would be greatly appreciated.</p>
| 0
|
2009-03-09T22:47:01Z
| 628,347
|
<p>The web page may be lying about its encoding. The output looks like UTF-8. If you got a str at the end then you'll need to decode it as UTF-8. If you have a unicode instead then you'll need to encode as Latin-1 first.</p>
| 1
|
2009-03-09T22:53:49Z
|
[
"python",
"unicode",
"encoding",
"utf-8",
"beautifulsoup"
] |
Decoding HTML Entities With Python
| 628,332
|
<p>The following Python code uses BeautifulStoneSoup to fetch the LibraryThing API information for Tolkien's "The Children of Húrin".</p>
<pre><code>import urllib2
from BeautifulSoup import BeautifulStoneSoup
URL = ("http://www.librarything.com/services/rest/1.0/"
"?method=librarything.ck.getwork&id=1907912"
"&apikey=2a2e596b887f554db2bbbf3b07ff812a")
soup = BeautifulStoneSoup(urllib2.urlopen(URL),
convertEntities=BeautifulStoneSoup.ALL_ENTITIES)
title_field = soup.find('field', attrs={'name': 'canonicaltitle'})
print title_field.find('fact').string
</code></pre>
<p>Unfortunately, instead of 'Húrin', it prints out 'Húrin'. This is obviously an encoding issue, but I can't work out what I need to do to get the expected output. Help would be greatly appreciated.</p>
| 0
|
2009-03-09T22:47:01Z
| 628,382
|
<p>In the source of the web page it looks like this: <code>The Children of H&Atilde;&ordm;rin</code>. So the encoding is already broken somewhere on their side before it even gets converted to XML...</p>
<p>If it's a general issue with all the books and you need to work around it, this seems to work:</p>
<pre><code>unicode(title_field.find('fact').string).encode("latin1").decode("utf-8")
</code></pre>
| 4
|
2009-03-09T23:05:28Z
|
[
"python",
"unicode",
"encoding",
"utf-8",
"beautifulsoup"
] |
Google Data Source JSON not valid?
| 628,505
|
<p>I am implementing a Google Data Source using their <a href="http://code.google.com/apis/visualization/documentation/dev/gviz_api_lib.html#tojsonexample" rel="nofollow">Python Library</a>. I would like the response from the library to be able to be imported in another Python script using the <a href="http://simplejson.googlecode.com/svn/tags/simplejson-2.0.9/docs/index.html" rel="nofollow">simplejson library.</a></p>
<p>However, even their <a href="http://google-visualization.appspot.com/python/dynamic_example" rel="nofollow">example</a> doesn't validate in JSONLint:</p>
<pre><code>{cols:
[{id:'name',label:'Name',type:'string'},
{id:'salary',label:'Salary',type:'number'},
{id:'full_time',label:'Full Time Employee',type:'boolean'}],
rows:
[{c:[{v:'Jim'},{v:800,f:'$800'},{v:false}]},
{c:[{v:'Bob'},{v:7000,f:'$7,000'},{v:true}]},
{c:[{v:'Mike'},{v:10000,f:'$10,000'},{v:true}]},
{c:[{v:'Alice'},{v:12500,f:'$12,500'},{v:true}]}]}
</code></pre>
<p>How do I tweak the simplejson 'loads' function to import the above JSON? I think the main problem is that the object keys are not strings. </p>
<p>I would rather not write a regex to convert the keys to strings since I think such code would be annoying to maintain. </p>
<p>I am currently getting an "Expecting property name: line 1 column 1 (char 1)" error when trying to import the above json into python with simplejson.</p>
| 5
|
2009-03-10T00:07:31Z
| 628,634
|
<p>It is considered to be invalid JSON without the string keys.</p>
<pre><code>{id:'name',label:'Name',type:'string'}
</code></pre>
<p>must be:</p>
<pre><code>{'id':'name','label':'Name','type':'string'}
</code></pre>
<p>According to the <a href="http://code.google.com/apis/visualization/documentation/dev/implementing%5Fdata%5Fsource.html#jsondatatable">Google Data Source</a> page, they're returning invalid JSON. They don't specifically say it, but all their examples lack quotes on the keys.</p>
<p>Here is a fairly complete list of <a href="http://deron.meranda.us/python/comparing%5Fjson%5Fmodules/basic">JSON processors for Python</a> which goes into detail about what formats they support, and how well. Most don't support non-string keys, <strong>but it appears that <a href="http://deron.meranda.us/python/demjson/">demjson</a> will convert it.</strong></p>
<pre><code>easy_install demjson
</code></pre>
| 8
|
2009-03-10T01:35:25Z
|
[
"python",
"simplejson"
] |
How to divide a set of overlapping ranges into non-overlapping ranges?
| 628,837
|
<p>Let's say you have a set of ranges:</p>
<ul>
<li>0 - 100: 'a'</li>
<li>0 - 75: 'b'</li>
<li>95 - 150: 'c'</li>
<li>120 - 130: 'd'</li>
</ul>
<p>Obviously, these ranges overlap at certain points. How would you dissect these ranges to produce a list of non-overlapping ranges, while retaining information associated with their original range (in this case, the letter after the range)?</p>
<p>For example, the results of the above after running the algorithm would be:</p>
<ul>
<li>0 - 75: 'a', 'b'</li>
<li>76 - 94: 'a'</li>
<li>95 - 100: 'a', 'c'</li>
<li>101 - 119: 'c'</li>
<li>120 - 130: 'c', 'd'</li>
<li>131 - 150: 'c'</li>
</ul>
| 8
|
2009-03-10T03:21:07Z
| 628,849
|
<p>I'd say create a list of the endpoints and sort it, also index the list of ranges by starting and ending points. Then iterate through the list of sorted endpoints, and for each one, check the ranges to see which ones are starting/stopping at that point.</p>
<p>This is probably better represented in code... if your ranges are represented by tuples:</p>
<pre><code>ranges = [(0,100,'a'),(0,75,'b'),(95,150,'c'),(120,130,'d')]
endpoints = sorted(list(set([r[0] for r in ranges] + [r[1] for r in ranges])))
start = {}
end = {}
for e in endpoints:
start[e] = set()
end[e] = set()
for r in ranges:
start[r[0]].add(r[2])
end[r[1]].add(r[2])
current_ranges = set()
for e1, e2 in zip(endpoints[:-1], endpoints[1:]):
current_ranges.difference_update(end[e1])
current_ranges.update(start[e1])
print '%d - %d: %s' % (e1, e2, ','.join(current_ranges))
</code></pre>
<p>Although looking at this in retrospect, I'd be surprised if there wasn't a more efficient (or at least cleaner-looking) way to do it.</p>
| 1
|
2009-03-10T03:25:59Z
|
[
"python",
"algorithm",
"math",
"range",
"rectangles"
] |
How to divide a set of overlapping ranges into non-overlapping ranges?
| 628,837
|
<p>Let's say you have a set of ranges:</p>
<ul>
<li>0 - 100: 'a'</li>
<li>0 - 75: 'b'</li>
<li>95 - 150: 'c'</li>
<li>120 - 130: 'd'</li>
</ul>
<p>Obviously, these ranges overlap at certain points. How would you dissect these ranges to produce a list of non-overlapping ranges, while retaining information associated with their original range (in this case, the letter after the range)?</p>
<p>For example, the results of the above after running the algorithm would be:</p>
<ul>
<li>0 - 75: 'a', 'b'</li>
<li>76 - 94: 'a'</li>
<li>95 - 100: 'a', 'c'</li>
<li>101 - 119: 'c'</li>
<li>120 - 130: 'c', 'd'</li>
<li>131 - 150: 'c'</li>
</ul>
| 8
|
2009-03-10T03:21:07Z
| 628,859
|
<p>I had the same question when writing a program to mix (partly overlapping) audio samples.</p>
<p>What I did was add an "start event" and "stop event" (for each item) to a list, sort the list by time point, and then process it in order. You could do the same, except using an integer point instead of a time, and instead of mixing sounds you'd be adding symbols to the set corresponding to a range. Whether you'd generate empty ranges or just omit them would be optional.</p>
<p><code>Edit</code> Perhaps some code...</p>
<pre><code># input = list of (start, stop, symbol) tuples
points = [] # list of (offset, plus/minus, symbol) tuples
for start,stop,symbol in input:
points.append((start,'+',symbol))
points.append((stop,'-',symbol))
points.sort()
ranges = [] # output list of (start, stop, symbol_set) tuples
current_set = set()
last_start = None
for offset,pm,symbol in points:
if pm == '+':
if last_start is not None:
#TODO avoid outputting empty or trivial ranges
ranges.append((last_start,offset-1,current_set))
current_set.add(symbol)
last_start = offset
elif pm == '-':
# Getting a minus without a last_start is unpossible here, so not handled
ranges.append((last_start,offset-1,current_set))
current_set.remove(symbol)
last_start = offset
# Finish off
if last_start is not None:
ranges.append((last_start,offset-1,current_set))
</code></pre>
<p>Totally untested, obviously.</p>
| 11
|
2009-03-10T03:32:48Z
|
[
"python",
"algorithm",
"math",
"range",
"rectangles"
] |
How to divide a set of overlapping ranges into non-overlapping ranges?
| 628,837
|
<p>Let's say you have a set of ranges:</p>
<ul>
<li>0 - 100: 'a'</li>
<li>0 - 75: 'b'</li>
<li>95 - 150: 'c'</li>
<li>120 - 130: 'd'</li>
</ul>
<p>Obviously, these ranges overlap at certain points. How would you dissect these ranges to produce a list of non-overlapping ranges, while retaining information associated with their original range (in this case, the letter after the range)?</p>
<p>For example, the results of the above after running the algorithm would be:</p>
<ul>
<li>0 - 75: 'a', 'b'</li>
<li>76 - 94: 'a'</li>
<li>95 - 100: 'a', 'c'</li>
<li>101 - 119: 'c'</li>
<li>120 - 130: 'c', 'd'</li>
<li>131 - 150: 'c'</li>
</ul>
| 8
|
2009-03-10T03:21:07Z
| 628,899
|
<p>Pseudocode:</p>
<pre><code>unusedRanges = [ (each of your ranges) ]
rangesInUse = []
usedRanges = []
beginningBoundary = nil
boundaries = [ list of all your ranges' start and end values, sorted ]
resultRanges = []
for (boundary in boundaries) {
rangesStarting = []
rangesEnding = []
// determine which ranges begin at this boundary
for (range in unusedRanges) {
if (range.begin == boundary) {
rangesStarting.add(range)
}
}
// if there are any new ones, start a new range
if (rangesStarting isn't empty) {
if (beginningBoundary isn't nil) {
// add the range we just passed
resultRanges.add(beginningBoundary, boundary - 1, [collected values from rangesInUse])
}
// note that we are starting a new range
beginningBoundary = boundary
for (range in rangesStarting) {
rangesInUse.add(range)
unusedRanges.remove(range)
}
}
// determine which ranges end at this boundary
for (range in rangesInUse) {
if (range.end == boundary) {
rangesEnding.add(range)
}
}
// if any boundaries are ending, stop the range
if (rangesEnding isn't empty) {
// add the range up to this boundary
resultRanges.add(beginningBoundary, boundary, [collected values from rangesInUse]
for (range in rangesEnding) {
usedRanges.add(range)
rangesInUse.remove(range)
}
if (rangesInUse isn't empty) {
// some ranges didn't end; note that we are starting a new range
beginningBoundary = boundary + 1
}
else {
beginningBoundary = nil
}
}
}
</code></pre>
<p>Unit test:</p>
<p>At the end, resultRanges should have the results you're looking for, unusedRanges and rangesInUse should be empty, beginningBoundary should be nil, and usedRanges should contain what unusedRanges used to contain (but sorted by range.end).</p>
| 0
|
2009-03-10T04:01:29Z
|
[
"python",
"algorithm",
"math",
"range",
"rectangles"
] |
How to divide a set of overlapping ranges into non-overlapping ranges?
| 628,837
|
<p>Let's say you have a set of ranges:</p>
<ul>
<li>0 - 100: 'a'</li>
<li>0 - 75: 'b'</li>
<li>95 - 150: 'c'</li>
<li>120 - 130: 'd'</li>
</ul>
<p>Obviously, these ranges overlap at certain points. How would you dissect these ranges to produce a list of non-overlapping ranges, while retaining information associated with their original range (in this case, the letter after the range)?</p>
<p>For example, the results of the above after running the algorithm would be:</p>
<ul>
<li>0 - 75: 'a', 'b'</li>
<li>76 - 94: 'a'</li>
<li>95 - 100: 'a', 'c'</li>
<li>101 - 119: 'c'</li>
<li>120 - 130: 'c', 'd'</li>
<li>131 - 150: 'c'</li>
</ul>
| 8
|
2009-03-10T03:21:07Z
| 628,906
|
<p>What you describe is an example of set theory. For a general algorithm for computing unions, intersections, and differences of sets see:</p>
<p><a href="http://www.gvu.gatech.edu/~jarek/graphics/papers/04PolygonBooleansMargalit.pdf" rel="nofollow">www.gvu.gatech.edu/~jarek/graphics/papers/04PolygonBooleansMargalit.pdf</a></p>
<p>While the paper is targeted at graphics it is applicable to general set theory as well. Not exactly light reading material.</p>
| 1
|
2009-03-10T04:07:40Z
|
[
"python",
"algorithm",
"math",
"range",
"rectangles"
] |
Performance Advantages to Iterators?
| 628,903
|
<p>What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that. </p>
| 14
|
2009-03-10T04:05:59Z
| 628,957
|
<p>Iterators are just classes that implement <a href="http://docs.python.org/library/stdtypes.html#iterator-types" rel="nofollow">a particular interface</a>, specifically an interface for <em>going to the next one</em>. In Python, lists, tuples, dicts, strings, and files all implement this interface. If they are implemented poorly, it may result in poor performance, but there is nothing inherent to the interface that implies good or bad performance.</p>
| 2
|
2009-03-10T04:42:36Z
|
[
"python",
"performance",
"iterator"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.