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 |
|---|---|---|---|---|---|---|---|---|---|
Can't find my PYTHONPATH | 859,594 | <p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p>
<p>However, it Python I can easily see it exists. So where is it?</p>
| 9 | 2009-05-13T18:28:59Z | 3,079,003 | <p>MacOS 10.5.8, Python 2.6, Eclipse+Pydev 1.5.7</p>
<ol>
<li><p>Python installation's site-package is, for example:
<pre><code>/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages</pre></code></p></li>
<li><p>create symlinks YOUR LIBRARY inside into site-package, for example:
<pre><code>cd /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages
ln -s /path/to/YOUR/LIBRARY/ YOUR_LIBRARY_NAME
</pre></code>
Now You can use in commandline: <pre><code> import YOUR_LIBRARY_NAME </pre></code></p></li>
<li><p>run Eclipse with Pydev, go to Preferences->Pydev->Interpreter Python</p></li>
<li><p><strong>remove</strong> Your Python interpreter record, if exists;</p></li>
<li><p>click <strong>New</strong> and add Python 2.6 interpreter path, for example:
<pre><code>/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6
</pre></code></p></li>
<li><p>notice, that Eclipse Pydev display Python System Library, accept that</p></li>
<li><p>in Library section click <strong>New Folder</strong> and write path to YOUR LIBRARY, for example:
<pre><code>/path/to/YOUR/LIBRARY/</pre></code></p></li>
<li><p>click <strong>Apply</strong> - it is essential, because Eclipse Pydev built now his own "library map", when this operation finish - click [OK]</p></li>
<li><p>close Eclipse</p></li>
<li><p>run Eclipse again - now You should use in Pydev:<pre><code> import YOUR_LIBRARY_NAME </pre></code></p></li>
</ol>
| 1 | 2010-06-20T11:09:30Z | [
"python",
"windows",
"path"
] |
Can't find my PYTHONPATH | 859,594 | <p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p>
<p>However, it Python I can easily see it exists. So where is it?</p>
| 9 | 2009-05-13T18:28:59Z | 6,400,643 | <p>And, as with all good things in life, you can find it in the documentation:
<a href="http://docs.python.org/install/index.html#modifying-python-s-search-path" rel="nofollow">http://docs.python.org/install/index.html#modifying-python-s-search-path</a></p>
| 1 | 2011-06-19T04:57:21Z | [
"python",
"windows",
"path"
] |
whoami in python | 860,140 | <p>What is the best way to find out the user that a python process is running under?</p>
<p>I could do this:</p>
<pre><code>name = os.popen('whoami').read()
</code></pre>
<p>But that has to start a whole new process.</p>
<pre><code>os.environ["USER"]
</code></pre>
<p>works sometimes, but sometimes that environment variable isn't set.</p>
| 24 | 2009-05-13T20:09:24Z | 860,154 | <p>This should work under Unix.</p>
<pre><code>import os
print os.getuid() # numeric uid
import pwd
print pwd.getpwuid(os.getuid()) # full /etc/passwd info
</code></pre>
| 18 | 2009-05-13T20:12:10Z | [
"python",
"posix"
] |
whoami in python | 860,140 | <p>What is the best way to find out the user that a python process is running under?</p>
<p>I could do this:</p>
<pre><code>name = os.popen('whoami').read()
</code></pre>
<p>But that has to start a whole new process.</p>
<pre><code>os.environ["USER"]
</code></pre>
<p>works sometimes, but sometimes that environment variable isn't set.</p>
| 24 | 2009-05-13T20:09:24Z | 860,156 | <pre><code>import getpass
print getpass.getuser()
</code></pre>
<p>See the documentation of the <a href="http://docs.python.org/library/getpass.html">getpass</a> module.</p>
<blockquote>
<p>getpass.getuser()</p>
<p>Return the âlogin nameâ of the user. Availability: Unix, Windows.</p>
<p>This function checks the environment variables LOGNAME, USER,
LNAME and USERNAME, in order, and
returns the value of the first one
which is set to a non-empty string. If
none are set, the login name from the
password database is returned on
systems which support the pwd module,
otherwise, an exception is raised.</p>
</blockquote>
| 50 | 2009-05-13T20:12:15Z | [
"python",
"posix"
] |
django and mod_wsgi having database connection issues | 860,169 | <p>I've noticed that whenever I enable the database settings on my django project (starting to notice a trend in my questions?) it gives me an internal server error. Setting the database settings to be blank makes the error go away. Here are the apache error logs that it outputs.</p>
<pre><code>mod_wsgi (pid=770): Exception occurred processing WSGI script '/Users/teifionjordan/rob2/apache/django.wsgi'.
Traceback (most recent call last):
File "/Library/Python/2.5/site-packages/django/core/handlers/wsgi.py", line 239, in __call__
response = self.get_response(request)
File "/Library/Python/2.5/site-packages/django/core/handlers/base.py", line 67, in get_response
response = middleware_method(request)
File "/Library/Python/2.5/site-packages/django/contrib/sessions/middleware.py", line 9, in process_request
engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
File "/Library/Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line 2, in <module>
from django.contrib.sessions.models import Session
File "/Library/Python/2.5/site-packages/django/contrib/sessions/models.py", line 4, in <module>
from django.db import models
File "/Library/Python/2.5/site-packages/django/db/__init__.py", line 16, in <module>
backend = __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, {}, [''])
File "/Library/Python/2.5/site-packages/django/db/backends/mysql/base.py", line 10, in <module>
import MySQLdb as Database
File "build/bdist.macosx-10.5-i386/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 4, in __bootstrap__
File "/Library/Python/2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 841, in resource_filename
self, resource_name
File "/Library/Python/2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 1310, in get_resource_filename
self._extract_resource(manager, self._eager_to_zip(name))
File "/Library/Python/2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 1332, in _extract_resource
self.egg_name, self._parts(zip_path)
File "/Library/Python/2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 921, in get_cache_path
self.extraction_error()
File "/Library/Python/2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 887, in extraction_error
raise err
ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 20] Not a directory: '/Library/WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp'
The Python egg cache directory is currently set to:
/Library/WebServer/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.
</code></pre>
<p>And here is the django.wsgi file</p>
<pre><code>import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'rob2.settings'
sys.path.append('/Users/teifionjordan')
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>I have several other scripts that all connect to a mysql database just fine, if I run the tutorial server then it displays the admin panel correctly. I have tried changing the environ variables for eggs but still nothing changes.</p>
| 2 | 2009-05-13T20:13:16Z | 861,806 | <p>You need to set the <code>PYTHON_EGG_CACHE</code> environment variable. Apache/mod_wsgi is trying to extract the egg into a directory that Apache doesn't have write access to....or that doesn't exist.</p>
<p>It's explained in the <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/#using-eggs-with-mod-python" rel="nofollow">Django docs here</a>.</p>
<p>Does <code>/Library/WebServer/.python-eggs</code> exist? What does your Apache config file look like?</p>
| 8 | 2009-05-14T06:15:16Z | [
"python",
"django",
"mod-wsgi"
] |
Emacs function to add symbol to __all__ in Python mode? | 860,357 | <p>Is there an existing Emacs function that adds the symbol currently under the point to <code>__all__</code> when editing Python code?</p>
<p>E.g., say the cursor was on the first <code>o</code> in <code>foo</code>:</p>
<pre><code># v---- cursor is on that 'o'
def foo():
return 42
</code></pre>
<p>If you did <b>M-x python-add-to-all</b> (or whatever) it would add <code>'foo'</code> to <code>__all__</code>.</p>
<p>I didn't see one when I googled around, but, as always, maybe I'm missing something obvious.</p>
<h2>Update</h2>
<p>I tried out <a href="http://stackoverflow.com/questions/860357/emacs-function-to-add-symbol-to-all-in-python-mode/860569#860569">Trey Jackson's answer</a> (thanks, Trey!) and made a few fixes/enhancements, in case anyone's interested (won't double-insert anymore, and puts <code>__all__</code> in a more typical spot if it doesn't already exist):</p>
<pre>
(defun python-add-to-all ()
"Take the symbol under the point and add it to the __all__
list, if it's not already there."
(interactive)
(save-excursion
(let ((thing (thing-at-point 'symbol)))
(if (progn (goto-char (point-min))
(let (found)
(while (and (not found)
(re-search-forward (rx symbol-start "__all__" symbol-end
(0+ space) "=" (0+ space)
(syntax open-parenthesis))
nil t))
(setq found (not (python-in-string/comment))))
found))
(when (not (looking-at (rx-to-string
`(and (0+ (not (syntax close-parenthesis)))
(syntax string-quote) ,thing (syntax string-quote)))))
(insert (format "\'%s\', " thing)))
(beginning-of-buffer)
;; Put before any import lines, or if none, the first class or
;; function.
(when (not (re-search-forward (rx bol (or "import" "from") symbol-end) nil t))
(re-search-forward (rx symbol-start (or "def" "class") symbol-end) nil t))
(forward-line -1)
(insert (format "\n__all__ = [\'%s\']\n" thing))))))
</pre>
| 5 | 2009-05-13T20:50:43Z | 860,569 | <p>Not being a python programmer, I'm not sure this covers all the cases, but works for me in a simple case. It'll add the symbol to the array if the array exists, and create <code>__all__</code> if it doesn't exist. <em>Note: it does not parse the array to avoid double insertion.</em></p>
<pre><code>(defun python-add-to-all ()
"take the symbol under the point and add to the __all__ routine"
(interactive)
(save-excursion
(let ((thing (thing-at-point 'word))
p)
(if (progn (goto-char (point-min))
(re-search-forward "^__all__ = \\[" nil t))
(insert (format "\"%s\", " thing))
(goto-char (point-min))
(insert (format "__all__ = [\"%s\"]\n" thing))))))
</code></pre>
| 10 | 2009-05-13T21:40:04Z | [
"python",
"emacs"
] |
GUI app spawned from a LocalSystem Service (via CreateProcessAsUser) does not have focus | 860,428 | <p>I have created a service which display a sort of splash screen on the desktop of a specific user and only when that user is logged in (kiosk user).</p>
<p>That splash screen, once entered a valid code, will tell that to the service and the service goes to sleep for an x amount of time (depending of the code).</p>
<p>The splash screen simply quits. Now when the service wakes up it sees that the splash is no longer there and so start it up.</p>
<p>This all is working, the only problem is that the launched application does not have focus, i.e. if I am working in notepad and the time is up, the splash screen is displayed (full screen though) behind notepad.</p>
<p>I only have to worry about Windows Vista, I am coding in Python using win32 extensions but I believe this problem lies in CreateProcessAsUser when called from the LocalSystem account.</p>
<p><hr /></p>
<h3>Update:</h3>
<p>The 'problem' is actually an on purpose limitation to prevent 'irritating' applications like mine from stealing focus.</p>
<p>You can change the behaviour by setting:
win32gui.SystemParametersInfo(win32con.SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0)
which is equivalent in temporarily setting the registry value:
HKEY_CURRENT_USER\Control Panel\Desktop\ForegroundLockTimeout
This must be done as the user itself, so either build it in the app you are launching or build an launching helper for the app you want to launch.</p>
<p>However an application might want to prevent getting it's focus stolen by using some API call which I don't remember right now.</p>
<p>A probably good solution would be to find all window handles currently from that user and then use each of these handles to use win32gui.ShowWindow(handle, command) to minimize it.</p>
<p>Although for this particular problem setting the locktimeout setting was enough.</p>
<p>If anyone wonders how I managed to launch an application to a desktop from a service, here is a <a href="http://blog.dcuktec.com/2009/05/python-on-windows-from-service-launch.html" rel="nofollow">link to the code</a>.</p>
| 1 | 2009-05-13T21:04:40Z | 860,711 | <p>Have you tried launching another processes than your own from the service to see if it gets focus? Like notepad and see if it steals focus from your browser? If so perhaps its the program that can take back the focus when it starts.</p>
<p>I otherwise beilive it's the wShowWindow attribute from the STARTUPINFO struct the lpStartupInfo points to that should control it. You also need STARTF_USESHOWWINDOW in dwFlags to use nShowWindow. The values should be SW_SHOW i think, they are listed for the ShowWindow function if you want to try other.</p>
| 2 | 2009-05-13T22:18:23Z | [
"python",
"windows-services",
"tkinter",
"pywin32"
] |
GUI app spawned from a LocalSystem Service (via CreateProcessAsUser) does not have focus | 860,428 | <p>I have created a service which display a sort of splash screen on the desktop of a specific user and only when that user is logged in (kiosk user).</p>
<p>That splash screen, once entered a valid code, will tell that to the service and the service goes to sleep for an x amount of time (depending of the code).</p>
<p>The splash screen simply quits. Now when the service wakes up it sees that the splash is no longer there and so start it up.</p>
<p>This all is working, the only problem is that the launched application does not have focus, i.e. if I am working in notepad and the time is up, the splash screen is displayed (full screen though) behind notepad.</p>
<p>I only have to worry about Windows Vista, I am coding in Python using win32 extensions but I believe this problem lies in CreateProcessAsUser when called from the LocalSystem account.</p>
<p><hr /></p>
<h3>Update:</h3>
<p>The 'problem' is actually an on purpose limitation to prevent 'irritating' applications like mine from stealing focus.</p>
<p>You can change the behaviour by setting:
win32gui.SystemParametersInfo(win32con.SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0)
which is equivalent in temporarily setting the registry value:
HKEY_CURRENT_USER\Control Panel\Desktop\ForegroundLockTimeout
This must be done as the user itself, so either build it in the app you are launching or build an launching helper for the app you want to launch.</p>
<p>However an application might want to prevent getting it's focus stolen by using some API call which I don't remember right now.</p>
<p>A probably good solution would be to find all window handles currently from that user and then use each of these handles to use win32gui.ShowWindow(handle, command) to minimize it.</p>
<p>Although for this particular problem setting the locktimeout setting was enough.</p>
<p>If anyone wonders how I managed to launch an application to a desktop from a service, here is a <a href="http://blog.dcuktec.com/2009/05/python-on-windows-from-service-launch.html" rel="nofollow">link to the code</a>.</p>
| 1 | 2009-05-13T21:04:40Z | 892,142 | <p>For various very legitimated reasons, Microsoft would rather not see a service launching an app and stealing focus, however I found the following work around to still accomplish what I want.</p>
<p>The original intend is to have a kiosk like application hindered by a pass code like splash screen, which upon entering a 8 character code closes the splash screen for a period time as in the pass code defined. Originally the actual application to use was started by the autostart folder.</p>
<p>However I now rewrote it that it is launched from my service, this way I can hide the application by launching an helper application from the service that just hides the program and launches the splash screen, upon exiting the splash screen the program is returned to the previous state.</p>
| 0 | 2009-05-21T09:44:09Z | [
"python",
"windows-services",
"tkinter",
"pywin32"
] |
Lay out import pathing in Python, straight and simple? | 860,672 | <p>If a group of Python developers wants to put their shared code somewhere, in a hierarchical structure, what's the structure, and what's the related "import" syntax?</p>
<p>Does java-style reference work in Python also? I.e., do directories correspond to dots? </p>
<p>What is standard setup for an internal-use-only library of Python code, and what's the syntax for imports from that library area, say 3 levels deep?</p>
<p>I've read Learning Python, saw PYTHONPATH, been fiddling with code for a few weeks now, love it, but I'm just dense on "import" beyond trivial cases. If too general send me back to the books.</p>
| 2 | 2009-05-13T22:06:46Z | 860,721 | <blockquote>
<p>If a group of Python developers wants to put their shared code somewhere, in a hierarchical structure, what's the structure, and what's the related "import" syntax?</p>
</blockquote>
<p>You put it in your C:\python26\Lib\site-packages\ directory under your own folder.</p>
<p>Inside that folder you should include an __init__.py file which will be run upon import, this can be empty.</p>
<blockquote>
<p>Does java-style reference work in Python also? I.e., do directories correspond to dots? </p>
</blockquote>
<p>Yes as long as the directories contain __init__.py files.</p>
<blockquote>
<p>What is standard setup for an internal-use-only library of Python code, and what's the syntax for imports from that library area, say 3 levels deep?</p>
</blockquote>
<pre><code>MyCompany/MyProject/ -> import MyCompany.MyProject
</code></pre>
| 2 | 2009-05-13T22:20:40Z | [
"python",
"import"
] |
Lay out import pathing in Python, straight and simple? | 860,672 | <p>If a group of Python developers wants to put their shared code somewhere, in a hierarchical structure, what's the structure, and what's the related "import" syntax?</p>
<p>Does java-style reference work in Python also? I.e., do directories correspond to dots? </p>
<p>What is standard setup for an internal-use-only library of Python code, and what's the syntax for imports from that library area, say 3 levels deep?</p>
<p>I've read Learning Python, saw PYTHONPATH, been fiddling with code for a few weeks now, love it, but I'm just dense on "import" beyond trivial cases. If too general send me back to the books.</p>
| 2 | 2009-05-13T22:06:46Z | 860,876 | <p>What we do.</p>
<p><strong>Development</strong></p>
<ul>
<li><p>c:\someroot\project\thing__init__.py # makes thing a package</p></li>
<li><p>c:\someroot\project\thing\foo.py</p></li>
<li><p>c:\someroot\project\thing\bar.py</p></li>
</ul>
<p>Our "environment" (set in a variety of ways</p>
<pre><code>SET PYTHONPATH="C:\someroot\project"
</code></pre>
<p>Some file we're working on</p>
<pre><code> import thing.foo
import thing.bar
</code></pre>
<p><strong>Deployment</strong></p>
<ul>
<li><p>/opt/someroot/project/project-1.1/thing/<strong>init</strong>.py # makes thing a package</p></li>
<li><p>/opt/someroot/project/project-1.1/thing/foo.py</p></li>
<li><p>/opt/someroot/project/project-1.1/thing/bar.py</p></li>
</ul>
<p>Our "environment" (set in a variety of ways</p>
<pre><code>SET PYTHONPATH="/opt/someroot/project/project-1.1"
</code></pre>
<p>This allows multiple versions to be deployed side-by-side.</p>
<p>Each of the various "things" are designed to be separate, reusable packages.</p>
| 6 | 2009-05-13T23:13:53Z | [
"python",
"import"
] |
How use __setattr__ & __getattr__ for map INI values? | 860,744 | <p>I want to map a INI file as a python object. So if the file have:</p>
<pre><code>[UserOptions]
SampleFile = sample.txt
SamplePort = 80
SampleInt = 1
Sample = Aja
SampleDate = 10/02/2008
</code></pre>
<p>Then I want:</p>
<pre><code>c = Configuration('sample.ini')
c.UserOptions.SamplePort = 90
</code></pre>
<p>I'm looking to <strong>setattr</strong> but I get a recursion error.</p>
<p>This is what I have:</p>
<pre><code>class Configuration:
def __init__ (self, fileName):
cp = SafeConfigParser()
cp.read(fileName)
self.__parser = cp
self.fileName = fileName
def __getattr__ (self, name):
if name in self.__parser.sections():
return Section(name, self.__parser)
else:
return None
def __str__ (self):
p = self.__parser
result = []
result.append('<Configuration from %s>' % self.fileName)
for s in p.sections():
result.append('[%s]' % s)
for o in p.options(s):
result.append('%s=%s' % (o, p.get(s, o)))
return '\n'.join(result)
class Section:
def __init__ (self, name, parser):
self.__name = name
self.__parser = parser
def __getattr__ (self, name):
if self.__dict__.has_key(name): # any normal attributes are handled normally
return __getattr__(self, item)
else:
return self.__parser.get(self.name, name)
def __setattr__(self, item, value):
"""Maps attributes to values.
Only if we are initialised
"""
if self.__dict__.has_key(item): # any normal attributes are handled normally
dict.__setattr__(self, item, value)
else:
self.__parser.set('UserOptions',item, value)
</code></pre>
<p>Now I wonder why in <code>self.__parser.set('UserOptions',item, value)</code> I get the error. I read in the pythons docs and I don't get what to do. I suspect that I need store a dict with the fields name and first look there but how?</p>
| 4 | 2009-05-13T22:25:58Z | 860,852 | <p>You are trying to get the sections on request. But it is much easier to iterate over sections and options and add them as attribute in <code>__init__</code>. I edited my example to support setattr as well. You problem is explained <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fsetattr%5F%5F" rel="nofollow">here</a> you are assigning the attributes in <code>__setattr__</code> while you should use <code>__dict__</code> instead</p>
<pre><code>from ConfigParser import SafeConfigParser
class Section:
def __init__(self, name, parser):
self.__dict__['name'] = name
self.__dict__['parser'] = parser
def __setattr__(self, attr, value):
self.__dict__[attr] = str(value)
self.parser.set(self.name, attr, str(value))
class Configuration(object):
def __init__(self, fileName):
self.__parser = SafeConfigParser()
self.__parser.read(fileName)
self.fileName = fileName
for section in self.__parser.sections():
setattr(self, section, Section(section, self.__parser))
for option in self.__parser.options(section):
setattr(getattr(self, section), option,
self.__parser.get(section, option))
def __getattr__(self, attr):
self.__parser.add_section(attr)
setattr(self, attr, Section(attr, self.__parser))
return getattr(self, attr)
def save(self):
f = open(self.fileName, 'w')
self.__parser.write(f)
f.close()
c = Configuration('config.ini')
print dir(c) -> will print all sections
print dir(c.UserOptions) -> will print all user options
print c.UserOptions.sampledate
c.new.value = 10
c.save()
</code></pre>
| 4 | 2009-05-13T23:04:38Z | [
"python",
"configuration-files"
] |
How use __setattr__ & __getattr__ for map INI values? | 860,744 | <p>I want to map a INI file as a python object. So if the file have:</p>
<pre><code>[UserOptions]
SampleFile = sample.txt
SamplePort = 80
SampleInt = 1
Sample = Aja
SampleDate = 10/02/2008
</code></pre>
<p>Then I want:</p>
<pre><code>c = Configuration('sample.ini')
c.UserOptions.SamplePort = 90
</code></pre>
<p>I'm looking to <strong>setattr</strong> but I get a recursion error.</p>
<p>This is what I have:</p>
<pre><code>class Configuration:
def __init__ (self, fileName):
cp = SafeConfigParser()
cp.read(fileName)
self.__parser = cp
self.fileName = fileName
def __getattr__ (self, name):
if name in self.__parser.sections():
return Section(name, self.__parser)
else:
return None
def __str__ (self):
p = self.__parser
result = []
result.append('<Configuration from %s>' % self.fileName)
for s in p.sections():
result.append('[%s]' % s)
for o in p.options(s):
result.append('%s=%s' % (o, p.get(s, o)))
return '\n'.join(result)
class Section:
def __init__ (self, name, parser):
self.__name = name
self.__parser = parser
def __getattr__ (self, name):
if self.__dict__.has_key(name): # any normal attributes are handled normally
return __getattr__(self, item)
else:
return self.__parser.get(self.name, name)
def __setattr__(self, item, value):
"""Maps attributes to values.
Only if we are initialised
"""
if self.__dict__.has_key(item): # any normal attributes are handled normally
dict.__setattr__(self, item, value)
else:
self.__parser.set('UserOptions',item, value)
</code></pre>
<p>Now I wonder why in <code>self.__parser.set('UserOptions',item, value)</code> I get the error. I read in the pythons docs and I don't get what to do. I suspect that I need store a dict with the fields name and first look there but how?</p>
| 4 | 2009-05-13T22:25:58Z | 860,867 | <p>Your problem is in <code>Section.__init__</code>. When you set <code>self.__name = name</code> it calls your <code>__setattr__</code> method, doesn't find the key in <code>__dict__</code> so it goes to</p>
<pre><code> self.__parser.set('UserOptions',item, value)
</code></pre>
<p>So now it needs <code>self.__parser</code>. </p>
<p>Which hasn't been set yet. So it tries to get it using <code>__getattr__</code>. Which sends it looking for <code>self.__parser</code>. Which hasn't been set yet. So it tries to get it using <code>__getattr__</code>. So... you get the point :-)</p>
<p>One way to avoid this is by adding a condition in <code>Section.__setattr__</code> like this</p>
<pre><code>if item.startswith('_') or self.__dict__.has_key(item):
^^^^^^^^^^^^^^^^^^^^^^^
...
</code></pre>
<p>which will make sure <code>__name</code> and <code>__parser</code> are set properly on initialization.</p>
| 4 | 2009-05-13T23:11:08Z | [
"python",
"configuration-files"
] |
Is python automagically parallelizing IO- and CPU- or memory-bound sections? | 860,893 | <p>This is a follow-up questions on a <a href="http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io">previous one</a>.</p>
<p>Consider this code, which is less toyish than the one in the <a href="http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io">previous question</a> (but still much simpler than my real one)</p>
<pre><code>import sys
data=[]
for line in open(sys.argv[1]):
data.append(line[-1])
print data[-1]
</code></pre>
<p>Now, I was expecting a longer run time (my benchmark file is 65150224 lines long), possibly much longer. This was not the case, it runs in ~ 2 minutes on the same hw as before!</p>
<p>Is it data.append() very lightweight? I don't believe so, thus I wrote this fake code to test it:</p>
<pre><code>data=[]
counter=0
string="a\n"
for counter in xrange(65150224):
data.append(string[-1])
print data[-1]
</code></pre>
<p>This runs in 1.5 to 3 minutes (there is strong variability among runs)</p>
<p>Why don't I get 3.5 to 5 minutes in the former program? Obviously data.append() is happening in parallel with the IO. </p>
<p>This is good news! </p>
<p>But how does it work? Is it a documented feature? Is there any requirement on my code that I should follow to make it works as much as possible (besides load-balancing IO and memory/CPU activities)? Or is it just plain buffering/caching in action?</p>
<p>Again, I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you think it's worth doing.</p>
| 3 | 2009-05-13T23:21:09Z | 860,951 | <p>How big are the lines in your file? If they're not very long (anything under about 1K probably qualifies) then you're likely seeing performance gains because of input buffering.</p>
| 1 | 2009-05-13T23:37:27Z | [
"python",
"linux",
"performance",
"text-files"
] |
Is python automagically parallelizing IO- and CPU- or memory-bound sections? | 860,893 | <p>This is a follow-up questions on a <a href="http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io">previous one</a>.</p>
<p>Consider this code, which is less toyish than the one in the <a href="http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io">previous question</a> (but still much simpler than my real one)</p>
<pre><code>import sys
data=[]
for line in open(sys.argv[1]):
data.append(line[-1])
print data[-1]
</code></pre>
<p>Now, I was expecting a longer run time (my benchmark file is 65150224 lines long), possibly much longer. This was not the case, it runs in ~ 2 minutes on the same hw as before!</p>
<p>Is it data.append() very lightweight? I don't believe so, thus I wrote this fake code to test it:</p>
<pre><code>data=[]
counter=0
string="a\n"
for counter in xrange(65150224):
data.append(string[-1])
print data[-1]
</code></pre>
<p>This runs in 1.5 to 3 minutes (there is strong variability among runs)</p>
<p>Why don't I get 3.5 to 5 minutes in the former program? Obviously data.append() is happening in parallel with the IO. </p>
<p>This is good news! </p>
<p>But how does it work? Is it a documented feature? Is there any requirement on my code that I should follow to make it works as much as possible (besides load-balancing IO and memory/CPU activities)? Or is it just plain buffering/caching in action?</p>
<p>Again, I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you think it's worth doing.</p>
| 3 | 2009-05-13T23:21:09Z | 860,988 | <p>Why do you think list.append() would be a slower operation? It is extremely fast, considering the internal pointer arrays used by lists to hold references to the objects in them are allocated in increasingly large blocks, so that every append does not actually re-allocate the array, and most can simply increment the length counter and set a pointer and incref.</p>
| 1 | 2009-05-13T23:52:30Z | [
"python",
"linux",
"performance",
"text-files"
] |
Is python automagically parallelizing IO- and CPU- or memory-bound sections? | 860,893 | <p>This is a follow-up questions on a <a href="http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io">previous one</a>.</p>
<p>Consider this code, which is less toyish than the one in the <a href="http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io">previous question</a> (but still much simpler than my real one)</p>
<pre><code>import sys
data=[]
for line in open(sys.argv[1]):
data.append(line[-1])
print data[-1]
</code></pre>
<p>Now, I was expecting a longer run time (my benchmark file is 65150224 lines long), possibly much longer. This was not the case, it runs in ~ 2 minutes on the same hw as before!</p>
<p>Is it data.append() very lightweight? I don't believe so, thus I wrote this fake code to test it:</p>
<pre><code>data=[]
counter=0
string="a\n"
for counter in xrange(65150224):
data.append(string[-1])
print data[-1]
</code></pre>
<p>This runs in 1.5 to 3 minutes (there is strong variability among runs)</p>
<p>Why don't I get 3.5 to 5 minutes in the former program? Obviously data.append() is happening in parallel with the IO. </p>
<p>This is good news! </p>
<p>But how does it work? Is it a documented feature? Is there any requirement on my code that I should follow to make it works as much as possible (besides load-balancing IO and memory/CPU activities)? Or is it just plain buffering/caching in action?</p>
<p>Again, I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you think it's worth doing.</p>
| 3 | 2009-05-13T23:21:09Z | 861,004 | <blockquote>
<p>Obviously data.append() is happening in parallel with the IO.</p>
</blockquote>
<p>I'm afraid not. It <em>is</em> possible to parallelize IO and computation in Python, but it doesn't happen magically.</p>
<p>One thing you could do is use <code>posix_fadvise(2)</code> to give the OS a hint that you plan to read the file sequentially (<code>POSIX_FADV_SEQUENTIAL</code>).</p>
<p>In some rough tests doing "wc -l" on a 600 meg file (an ISO) the performance increased by about 20%. Each test was done immediately after clearing the disk cache.</p>
<p>For a Python interface to fadvise see <a href="http://chris-lamb.co.uk/projects/python-fadvise/">python-fadvise</a>.</p>
| 8 | 2009-05-13T23:58:13Z | [
"python",
"linux",
"performance",
"text-files"
] |
Is python automagically parallelizing IO- and CPU- or memory-bound sections? | 860,893 | <p>This is a follow-up questions on a <a href="http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io">previous one</a>.</p>
<p>Consider this code, which is less toyish than the one in the <a href="http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io">previous question</a> (but still much simpler than my real one)</p>
<pre><code>import sys
data=[]
for line in open(sys.argv[1]):
data.append(line[-1])
print data[-1]
</code></pre>
<p>Now, I was expecting a longer run time (my benchmark file is 65150224 lines long), possibly much longer. This was not the case, it runs in ~ 2 minutes on the same hw as before!</p>
<p>Is it data.append() very lightweight? I don't believe so, thus I wrote this fake code to test it:</p>
<pre><code>data=[]
counter=0
string="a\n"
for counter in xrange(65150224):
data.append(string[-1])
print data[-1]
</code></pre>
<p>This runs in 1.5 to 3 minutes (there is strong variability among runs)</p>
<p>Why don't I get 3.5 to 5 minutes in the former program? Obviously data.append() is happening in parallel with the IO. </p>
<p>This is good news! </p>
<p>But how does it work? Is it a documented feature? Is there any requirement on my code that I should follow to make it works as much as possible (besides load-balancing IO and memory/CPU activities)? Or is it just plain buffering/caching in action?</p>
<p>Again, I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you think it's worth doing.</p>
| 3 | 2009-05-13T23:21:09Z | 861,013 | <p>I don't see any evidence that "data.append() is happening in parallel with the IO." Like Benji, I don't think this is automatic in the way you think. You showed that doing data.append(line[-1]) takes about the same amount of time as lc = lc + 1 (essentially no time at all, compared to the IO and line splitting). It's not really surprising that data.append(line[-1]) is very fast. One would expect the whole line to be in a fast cache, and as noted append prepares buffers ahead of time and only rarely has to reallocate. Moreover, line[-1] will always be '\n', except possibly for the last line of the file (no idea if Python optimizes for this).</p>
<p>The only part I'm a little surprised about is that the xrange is so variable. I would expect it to always be faster, since there's no IO, and you're not actually using the counter.</p>
| 1 | 2009-05-14T00:02:32Z | [
"python",
"linux",
"performance",
"text-files"
] |
Is python automagically parallelizing IO- and CPU- or memory-bound sections? | 860,893 | <p>This is a follow-up questions on a <a href="http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io">previous one</a>.</p>
<p>Consider this code, which is less toyish than the one in the <a href="http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io">previous question</a> (but still much simpler than my real one)</p>
<pre><code>import sys
data=[]
for line in open(sys.argv[1]):
data.append(line[-1])
print data[-1]
</code></pre>
<p>Now, I was expecting a longer run time (my benchmark file is 65150224 lines long), possibly much longer. This was not the case, it runs in ~ 2 minutes on the same hw as before!</p>
<p>Is it data.append() very lightweight? I don't believe so, thus I wrote this fake code to test it:</p>
<pre><code>data=[]
counter=0
string="a\n"
for counter in xrange(65150224):
data.append(string[-1])
print data[-1]
</code></pre>
<p>This runs in 1.5 to 3 minutes (there is strong variability among runs)</p>
<p>Why don't I get 3.5 to 5 minutes in the former program? Obviously data.append() is happening in parallel with the IO. </p>
<p>This is good news! </p>
<p>But how does it work? Is it a documented feature? Is there any requirement on my code that I should follow to make it works as much as possible (besides load-balancing IO and memory/CPU activities)? Or is it just plain buffering/caching in action?</p>
<p>Again, I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you think it's worth doing.</p>
| 3 | 2009-05-13T23:21:09Z | 861,513 | <p>If your run times are varying by that amount for the second example, I'd suspect your method of timing or outside influences (other processes / system load) to be skewing the times to the point where they don't give any reliable information.</p>
| 1 | 2009-05-14T04:11:56Z | [
"python",
"linux",
"performance",
"text-files"
] |
How to do this join query in Django | 860,941 | <p>In Django, I have two models:</p>
<pre><code>class Product(models.Model):
name = models.CharField(max_length = 50)
categories = models.ManyToManyField(Category)
class ProductRank(models.Model):
product = models.ForeignKey(Product)
rank = models.IntegerField(default = 0)
</code></pre>
<p>I put the rank into a separate table because every view of a page will cause the rank to change and I was worried that all these writes would make my other (mostly read) queries slow down.</p>
<p>I gather a list of <code>Products</code> from a simple query:</p>
<pre><code>cat = Category.objects.get(pk = 1)
products = Product.objects.filter(categories = cat)
</code></pre>
<p>I would now like to get all the ranks for these products. I would prefer to do it all in one go (using a SQL join) and was wondering how to express that using Django's query mechanism.</p>
<p>What is the right way to do this in Django?</p>
| 8 | 2009-05-13T23:34:24Z | 860,985 | <p>Add a call to the QuerySet's select_related() method, though I'm not positive that grabs references in both directions, it is the most likely answer.</p>
| 2 | 2009-05-13T23:50:08Z | [
"python",
"sql",
"django"
] |
How to do this join query in Django | 860,941 | <p>In Django, I have two models:</p>
<pre><code>class Product(models.Model):
name = models.CharField(max_length = 50)
categories = models.ManyToManyField(Category)
class ProductRank(models.Model):
product = models.ForeignKey(Product)
rank = models.IntegerField(default = 0)
</code></pre>
<p>I put the rank into a separate table because every view of a page will cause the rank to change and I was worried that all these writes would make my other (mostly read) queries slow down.</p>
<p>I gather a list of <code>Products</code> from a simple query:</p>
<pre><code>cat = Category.objects.get(pk = 1)
products = Product.objects.filter(categories = cat)
</code></pre>
<p>I would now like to get all the ranks for these products. I would prefer to do it all in one go (using a SQL join) and was wondering how to express that using Django's query mechanism.</p>
<p>What is the right way to do this in Django?</p>
| 8 | 2009-05-13T23:34:24Z | 860,997 | <p>This can be done in Django, but you will need to restructure your models a little bit differently:</p>
<pre><code>class Product(models.Model):
name = models.CharField(max_length=50)
product_rank = models.OneToOneField('ProductRank')
class ProductRank(models.Model):
rank = models.IntegerField(default=0)
</code></pre>
<p>Now, when fetching Product objects, you can following the one-to-one relationship in one query using the <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related" rel="nofollow">select_related()</a> method:</p>
<pre><code>Product.objects.filter([...]).select_related()
</code></pre>
<p>This will produce one query that fetches product ranks using a join:</p>
<pre><code>SELECT "example_product"."id", "example_product"."name", "example_product"."product_rank_id", "example_productrank"."id", "example_productrank"."rank" FROM "example_product" INNER JOIN "example_productrank" ON ("example_product"."product_rank_id" = "example_productrank"."id")
</code></pre>
<p>I had to move the relationship field between Product and ProductRank to the Product model because it looks like select_related() follows foreign keys in one direction only.</p>
| 10 | 2009-05-13T23:55:05Z | [
"python",
"sql",
"django"
] |
How to do this join query in Django | 860,941 | <p>In Django, I have two models:</p>
<pre><code>class Product(models.Model):
name = models.CharField(max_length = 50)
categories = models.ManyToManyField(Category)
class ProductRank(models.Model):
product = models.ForeignKey(Product)
rank = models.IntegerField(default = 0)
</code></pre>
<p>I put the rank into a separate table because every view of a page will cause the rank to change and I was worried that all these writes would make my other (mostly read) queries slow down.</p>
<p>I gather a list of <code>Products</code> from a simple query:</p>
<pre><code>cat = Category.objects.get(pk = 1)
products = Product.objects.filter(categories = cat)
</code></pre>
<p>I would now like to get all the ranks for these products. I would prefer to do it all in one go (using a SQL join) and was wondering how to express that using Django's query mechanism.</p>
<p>What is the right way to do this in Django?</p>
| 8 | 2009-05-13T23:34:24Z | 861,156 | <p>I haven't checked but:</p>
<pre><code>products = Product.objects.filter(categories__pk=1).select_related()
</code></pre>
<p>Should grab every instance.</p>
| 4 | 2009-05-14T01:20:40Z | [
"python",
"sql",
"django"
] |
A class method which behaves differently when called as an instance method? | 861,055 | <p>I'm wondering if it's possible to make a method which behaves differently when called as a class method than when called as an instance method.</p>
<p>For example, as a skills-improvement project, I'm writing a <code>Matrix</code> class (yes, I know there are perfectly good matrix classes already out there). I've created a class method for it called <code>identity</code> which returns an identity matrix of a specified size.</p>
<p>Now, when called on an <em>instance</em> of <code>Matrix</code>, it seems logical that the size shouldn't need to be specified; it should return an identity matrix of the same size as the <code>Matrix</code> it's called on.</p>
<p>In other words, I'd like to define a method which can determine whether it was called via an instance and, if so, access that instance's attributes. Unfortunately, even after digging through the documentation and a few Google searches, I haven't found anything which suggests this is possible. Does anyone know differently?</p>
<p><strong>Edit:</strong></p>
<p>Wow! Clearly, I'm still not quite used to first-class functions. Here's what I ended up with â thanks to Unknown for providing the key!</p>
<pre><code>class Foo(object):
def __init__(self, bar):
self.baz = bar
self.bar = MethodType(lambda self: self.__class__.bar(self.baz), self, self.__class__)
@classmethod
def bar(cls, baz):
return 5 * baz
Foo.bar(3) # returns 15
foo = Foo(7)
foo.bar() # returns 35
</code></pre>
<p><strong>Edit 2:</strong></p>
<p>Just a quick note â this technique (and most of those presented below) won't work on classes which define <code>__slots__</code>, as you cannot reassign the method.</p>
| 24 | 2009-05-14T00:26:24Z | 861,092 | <p>I think the larger problem is that you are overloading the name 'bar' on class 'Foo', something python doesn't allow. The second definition of 'bar' clobbers the first definition of 'bar'. </p>
<p>Try to think of unique names for your classmethod and instance method. i.e.</p>
<pre><code>@classmethod
def create(cls, baz):
...
def rubber_stamp(self):
...
</code></pre>
| 3 | 2009-05-14T00:44:27Z | [
"python",
"class",
"methods"
] |
A class method which behaves differently when called as an instance method? | 861,055 | <p>I'm wondering if it's possible to make a method which behaves differently when called as a class method than when called as an instance method.</p>
<p>For example, as a skills-improvement project, I'm writing a <code>Matrix</code> class (yes, I know there are perfectly good matrix classes already out there). I've created a class method for it called <code>identity</code> which returns an identity matrix of a specified size.</p>
<p>Now, when called on an <em>instance</em> of <code>Matrix</code>, it seems logical that the size shouldn't need to be specified; it should return an identity matrix of the same size as the <code>Matrix</code> it's called on.</p>
<p>In other words, I'd like to define a method which can determine whether it was called via an instance and, if so, access that instance's attributes. Unfortunately, even after digging through the documentation and a few Google searches, I haven't found anything which suggests this is possible. Does anyone know differently?</p>
<p><strong>Edit:</strong></p>
<p>Wow! Clearly, I'm still not quite used to first-class functions. Here's what I ended up with â thanks to Unknown for providing the key!</p>
<pre><code>class Foo(object):
def __init__(self, bar):
self.baz = bar
self.bar = MethodType(lambda self: self.__class__.bar(self.baz), self, self.__class__)
@classmethod
def bar(cls, baz):
return 5 * baz
Foo.bar(3) # returns 15
foo = Foo(7)
foo.bar() # returns 35
</code></pre>
<p><strong>Edit 2:</strong></p>
<p>Just a quick note â this technique (and most of those presented below) won't work on classes which define <code>__slots__</code>, as you cannot reassign the method.</p>
| 24 | 2009-05-14T00:26:24Z | 861,109 | <p>Questionably useful Python hacks are my forte.</p>
<pre><code>from types import *
class Foo(object):
def __init__(self):
self.bar = methodize(bar, self)
self.baz = 999
@classmethod
def bar(cls, baz):
return 2 * baz
def methodize(func, instance):
return MethodType(func, instance, instance.__class__)
def bar(self):
return 4*self.baz
>>> Foo.bar(5)
10
>>> a=Foo()
>>> a.bar()
3996
</code></pre>
| 35 | 2009-05-14T00:56:35Z | [
"python",
"class",
"methods"
] |
A class method which behaves differently when called as an instance method? | 861,055 | <p>I'm wondering if it's possible to make a method which behaves differently when called as a class method than when called as an instance method.</p>
<p>For example, as a skills-improvement project, I'm writing a <code>Matrix</code> class (yes, I know there are perfectly good matrix classes already out there). I've created a class method for it called <code>identity</code> which returns an identity matrix of a specified size.</p>
<p>Now, when called on an <em>instance</em> of <code>Matrix</code>, it seems logical that the size shouldn't need to be specified; it should return an identity matrix of the same size as the <code>Matrix</code> it's called on.</p>
<p>In other words, I'd like to define a method which can determine whether it was called via an instance and, if so, access that instance's attributes. Unfortunately, even after digging through the documentation and a few Google searches, I haven't found anything which suggests this is possible. Does anyone know differently?</p>
<p><strong>Edit:</strong></p>
<p>Wow! Clearly, I'm still not quite used to first-class functions. Here's what I ended up with â thanks to Unknown for providing the key!</p>
<pre><code>class Foo(object):
def __init__(self, bar):
self.baz = bar
self.bar = MethodType(lambda self: self.__class__.bar(self.baz), self, self.__class__)
@classmethod
def bar(cls, baz):
return 5 * baz
Foo.bar(3) # returns 15
foo = Foo(7)
foo.bar() # returns 35
</code></pre>
<p><strong>Edit 2:</strong></p>
<p>Just a quick note â this technique (and most of those presented below) won't work on classes which define <code>__slots__</code>, as you cannot reassign the method.</p>
| 24 | 2009-05-14T00:26:24Z | 861,119 | <p><strong>[edited: use attribute to be a more direct answer; see the helpful comment by John Fouhy]</strong></p>
<p>You can use a descriptor to do what you want:</p>
<pre><code>class cls_or_inst_method(object):
def __init__(self, class_method, instance_method):
self.class_method = class_method
self.instance_method = instance_method
def __get__(self, obj, objtype):
if obj is None:
return self.class_method
else:
return lambda: self.instance_method(obj)
def my_class_method(baz):
return baz + 1
def my_instance_method(self):
return self.baz * 2
class Foo(object):
baz = 10
bar = cls_or_inst_method(my_class_method, my_instance_method)
</code></pre>
<p>Using the above:</p>
<pre><code>>>> print Foo.bar(5)
6
>>> my_foo = Foo()
>>> print my_foo.bar()
20
</code></pre>
| 6 | 2009-05-14T01:00:08Z | [
"python",
"class",
"methods"
] |
A class method which behaves differently when called as an instance method? | 861,055 | <p>I'm wondering if it's possible to make a method which behaves differently when called as a class method than when called as an instance method.</p>
<p>For example, as a skills-improvement project, I'm writing a <code>Matrix</code> class (yes, I know there are perfectly good matrix classes already out there). I've created a class method for it called <code>identity</code> which returns an identity matrix of a specified size.</p>
<p>Now, when called on an <em>instance</em> of <code>Matrix</code>, it seems logical that the size shouldn't need to be specified; it should return an identity matrix of the same size as the <code>Matrix</code> it's called on.</p>
<p>In other words, I'd like to define a method which can determine whether it was called via an instance and, if so, access that instance's attributes. Unfortunately, even after digging through the documentation and a few Google searches, I haven't found anything which suggests this is possible. Does anyone know differently?</p>
<p><strong>Edit:</strong></p>
<p>Wow! Clearly, I'm still not quite used to first-class functions. Here's what I ended up with â thanks to Unknown for providing the key!</p>
<pre><code>class Foo(object):
def __init__(self, bar):
self.baz = bar
self.bar = MethodType(lambda self: self.__class__.bar(self.baz), self, self.__class__)
@classmethod
def bar(cls, baz):
return 5 * baz
Foo.bar(3) # returns 15
foo = Foo(7)
foo.bar() # returns 35
</code></pre>
<p><strong>Edit 2:</strong></p>
<p>Just a quick note â this technique (and most of those presented below) won't work on classes which define <code>__slots__</code>, as you cannot reassign the method.</p>
| 24 | 2009-05-14T00:26:24Z | 861,137 | <p>@Unknown What's the difference between your's and this:</p>
<pre><code>class Foo(object):
def _bar(self, baz):
print "_bar, baz:", baz
def __init__(self, bar):
self.bar = self._bar
self.baz = bar
@classmethod
def bar(cls, baz):
print "bar, baz:", baz
In [1]: import foo
In [2]: f = foo.Foo(42)
In [3]: f.bar(1)
_bar, baz: 1
In [4]: foo.Foo.bar(1)
bar, baz: 1
In [5]: f.__class__.bar(1)
bar, baz: 1
</code></pre>
| 7 | 2009-05-14T01:14:02Z | [
"python",
"class",
"methods"
] |
A class method which behaves differently when called as an instance method? | 861,055 | <p>I'm wondering if it's possible to make a method which behaves differently when called as a class method than when called as an instance method.</p>
<p>For example, as a skills-improvement project, I'm writing a <code>Matrix</code> class (yes, I know there are perfectly good matrix classes already out there). I've created a class method for it called <code>identity</code> which returns an identity matrix of a specified size.</p>
<p>Now, when called on an <em>instance</em> of <code>Matrix</code>, it seems logical that the size shouldn't need to be specified; it should return an identity matrix of the same size as the <code>Matrix</code> it's called on.</p>
<p>In other words, I'd like to define a method which can determine whether it was called via an instance and, if so, access that instance's attributes. Unfortunately, even after digging through the documentation and a few Google searches, I haven't found anything which suggests this is possible. Does anyone know differently?</p>
<p><strong>Edit:</strong></p>
<p>Wow! Clearly, I'm still not quite used to first-class functions. Here's what I ended up with â thanks to Unknown for providing the key!</p>
<pre><code>class Foo(object):
def __init__(self, bar):
self.baz = bar
self.bar = MethodType(lambda self: self.__class__.bar(self.baz), self, self.__class__)
@classmethod
def bar(cls, baz):
return 5 * baz
Foo.bar(3) # returns 15
foo = Foo(7)
foo.bar() # returns 35
</code></pre>
<p><strong>Edit 2:</strong></p>
<p>Just a quick note â this technique (and most of those presented below) won't work on classes which define <code>__slots__</code>, as you cannot reassign the method.</p>
| 24 | 2009-05-14T00:26:24Z | 861,177 | <p>You can reassign your identity method in <strong>init</strong> with short lambda function:</p>
<pre><code>class Matrix(object):
def __init__(self):
self.identity = lambda s=self:s.__class__.identity(s)
#...whatever initialization code you have...
self.size = 10
@classmethod
def identity(self, other):
#...always do you matrix calculations on 'other', not 'self'...
return other.size
m = Matrix()
print m.identity()
print Matrix.identity(m)
</code></pre>
<p>If you're not familiar with lambda, it creates an anonymous function. It's rarely necessary, but it can make your code more concise. The lambda line above could be rewritten:</p>
<pre><code> def identity(self):
self.__class__.indentity(self)
self.identity = identity
</code></pre>
| 2 | 2009-05-14T01:32:30Z | [
"python",
"class",
"methods"
] |
How do capture groups work? (wrt python regular expressions) | 861,060 | <p>While using regex to help solve a problem in the <a href="http://www.pythonchallenge.com/" rel="nofollow">Python Challenge</a>, I came across some behaviour that confused me.</p>
<p>from <a href="http://docs.python.org/library/re.html#regular-expression-syntax" rel="nofollow">here</a>:</p>
<p>(...) Matches whatever regular expression is inside the parentheses.</p>
<p>and </p>
<p>'+' Causes the resulting RE to match 1 or more repetitions of the preceding RE.</p>
<p>So this makes sense:</p>
<pre><code>>>>import re
>>>re.findall(r"(\d+)", "1111112")
['1111112']
</code></pre>
<p>But this doesn't:</p>
<pre><code>>>> re.findall(r"(\d)+", "1111112")
['2']
</code></pre>
<p>I realise that findall returns only groups when groups are present in the regex, but why is only the '2' returned? What happends to all the 1's in the match?</p>
| 1 | 2009-05-14T00:27:52Z | 861,070 | <p>Because you only have one capturing group, but it's "run" repeatedly, the new matches are repeatedly entered into the "storage space" for that group. In other words, the <code>1</code>s were lost when they were "overwritten" by subsequent <code>1</code>s and eventually the <code>2</code>.</p>
| 9 | 2009-05-14T00:31:22Z | [
"python",
"regex"
] |
How do capture groups work? (wrt python regular expressions) | 861,060 | <p>While using regex to help solve a problem in the <a href="http://www.pythonchallenge.com/" rel="nofollow">Python Challenge</a>, I came across some behaviour that confused me.</p>
<p>from <a href="http://docs.python.org/library/re.html#regular-expression-syntax" rel="nofollow">here</a>:</p>
<p>(...) Matches whatever regular expression is inside the parentheses.</p>
<p>and </p>
<p>'+' Causes the resulting RE to match 1 or more repetitions of the preceding RE.</p>
<p>So this makes sense:</p>
<pre><code>>>>import re
>>>re.findall(r"(\d+)", "1111112")
['1111112']
</code></pre>
<p>But this doesn't:</p>
<pre><code>>>> re.findall(r"(\d)+", "1111112")
['2']
</code></pre>
<p>I realise that findall returns only groups when groups are present in the regex, but why is only the '2' returned? What happends to all the 1's in the match?</p>
| 1 | 2009-05-14T00:27:52Z | 861,076 | <p>You are repeating the group itself by appending '+' after ')', I do not know the implementation details but it matches 7 times, and returns only the last match.</p>
<p>In the first one, you are matching 7 digits, and making it a group.</p>
| 1 | 2009-05-14T00:33:45Z | [
"python",
"regex"
] |
Ordering a list of dictionaries in python | 861,190 | <p>I've got a python list of dictionaries:</p>
<pre><code>mylist = [
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'}
]
</code></pre>
<p>Whats the most efficient/cleanest way to order that list by weight then factor (numericaly). The resulting list should look like:</p>
<pre><code>mylist = [
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
]
</code></pre>
| 7 | 2009-05-14T01:41:03Z | 861,218 | <p>Something along the lines of the following ought to work:</p>
<pre><code>def cmp_dict(x, y):
weight_diff = y['weight'] - x['weight']
if weight_diff == 0:
return y['factor'] - x['factor']
else:
return weight_diff
myList.sort(cmp_dict)
</code></pre>
| 1 | 2009-05-14T01:52:03Z | [
"python",
"list",
"dictionary",
"order"
] |
Ordering a list of dictionaries in python | 861,190 | <p>I've got a python list of dictionaries:</p>
<pre><code>mylist = [
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'}
]
</code></pre>
<p>Whats the most efficient/cleanest way to order that list by weight then factor (numericaly). The resulting list should look like:</p>
<pre><code>mylist = [
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
]
</code></pre>
| 7 | 2009-05-14T01:41:03Z | 861,238 | <pre><code>mylist.sort(key=lambda d: (d['weight'], d['factor']))
</code></pre>
<p>or</p>
<pre><code>import operator
mylist.sort(key=operator.itemgetter('weight', 'factor'))
</code></pre>
| 23 | 2009-05-14T01:59:25Z | [
"python",
"list",
"dictionary",
"order"
] |
Ordering a list of dictionaries in python | 861,190 | <p>I've got a python list of dictionaries:</p>
<pre><code>mylist = [
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'}
]
</code></pre>
<p>Whats the most efficient/cleanest way to order that list by weight then factor (numericaly). The resulting list should look like:</p>
<pre><code>mylist = [
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
]
</code></pre>
| 7 | 2009-05-14T01:41:03Z | 861,355 | <p>I accepted dF's answer for the inspiration, but here is what I ultimately settled on for my scenario:</p>
<pre><code>@staticmethod
def ordered_list(mylist):
def sort_func(d):
return (d['weight'], d['factor'])
mylist.sort(key=sort_func)
</code></pre>
| 1 | 2009-05-14T03:00:47Z | [
"python",
"list",
"dictionary",
"order"
] |
Ordering a list of dictionaries in python | 861,190 | <p>I've got a python list of dictionaries:</p>
<pre><code>mylist = [
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'}
]
</code></pre>
<p>Whats the most efficient/cleanest way to order that list by weight then factor (numericaly). The resulting list should look like:</p>
<pre><code>mylist = [
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
]
</code></pre>
| 7 | 2009-05-14T01:41:03Z | 863,820 | <pre><code>decoratedlist = [(item[weight], item) for item in mylist]
decoratedlist.sort()
results = [item for (key, item) in decoratedlist]
</code></pre>
| -1 | 2009-05-14T14:57:51Z | [
"python",
"list",
"dictionary",
"order"
] |
Use of cycle in django | 861,855 | <p>I have a webpage where I am looping,and using cycle inside the loop.</p>
<pre><code>{% for o in something %}
{% for c in o %}
<div class="{% cycle 'white' 'black'%}"></div>
{% endfor %}
</code></pre>
<p>Now, this means everytime inside the loop, first div tag gets white.But,what I want is to alternate between white and black i.e. start with white, then next time when inside the loop start the first div tag with black.Is it possible to achieve here?</p>
| 5 | 2009-05-14T06:33:33Z | 861,952 | <p>Something like this might work (untested):</p>
<pre><code>{% for o in something %}
{% for c in o %}
{% ifchanged forloop.parent.counter %}
<div class="{% cycle 'white' 'black' %}"></div>
{% else %}
<div class="{% cycle 'black' 'white' %}"></div>
{% endifchanged %}
{% endfor %}
{% endfor %}
</code></pre>
| 0 | 2009-05-14T07:10:21Z | [
"python",
"django",
"django-templates"
] |
Use of cycle in django | 861,855 | <p>I have a webpage where I am looping,and using cycle inside the loop.</p>
<pre><code>{% for o in something %}
{% for c in o %}
<div class="{% cycle 'white' 'black'%}"></div>
{% endfor %}
</code></pre>
<p>Now, this means everytime inside the loop, first div tag gets white.But,what I want is to alternate between white and black i.e. start with white, then next time when inside the loop start the first div tag with black.Is it possible to achieve here?</p>
| 5 | 2009-05-14T06:33:33Z | 3,765,829 | <p>There is an accept <a href="http://code.djangoproject.com/ticket/5908" rel="nofollow">bug</a> open about this issue. You may want to try the proposed change to see if it works for you.</p>
<p>If you do not want to try it, or it does not work, give this a shot:</p>
<pre><code>{% cycle 'white' 'black' as divcolors %}
{% for o in something %}
{% for c in o %}
<div class="{% cycle divcolors %}"></div>
{% endfor %}
{% endfor %}
</code></pre>
<p>As I understand it, the cycle would start at white, and then loop through the values each time inside the loop (meaning you won't restart at white every time).</p>
| 4 | 2010-09-22T02:03:26Z | [
"python",
"django",
"django-templates"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 861,869 | <p>The pypy project offers sandboxing features, see <a href="http://codespeak.net/pypy/dist/pypy/doc/sandbox.html" rel="nofollow">http://codespeak.net/pypy/dist/pypy/doc/sandbox.html</a> .</p>
| 3 | 2009-05-14T06:41:01Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 861,875 | <p>No there is no production ready subset of Python that is "safe". Python has had a few sand box modules which were deprecated due to deficiencies.</p>
<p>Your best bet is to either create your own parser, or isolate the python process with syscall hooks and a jailed account.</p>
<p>Some people might point you to PyPy, but it is slow and unfinished.</p>
| 3 | 2009-05-14T06:42:57Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 861,947 | <p>AFAIK, some attempts were made in standard python library, but they were not successful. See <a href="http://docs.python.org/library/restricted.html" rel="nofollow">Restricted Execution</a> for details.</p>
<blockquote>
<p>Warning</p>
<p>In Python 2.3 these modules have been
disabled due to various known and not
readily fixable security holes. The
modules are still documented here to
help in reading old code that uses the
rexec and Bastion modules.</p>
</blockquote>
| 1 | 2009-05-14T07:09:14Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 861,961 | <p>Here are a couple of links to give you an idea on what you're up against:</p>
<ul>
<li><a href="https://wiki.python.org/moin/Asking%20for%20Help/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20%28i.e.%20Sandbox%29" rel="nofollow">How can I run an untrusted Python script safely (i.e. Sandbox)</a></li>
<li><a href="http://neopythonic.blogspot.com/2009/03/capabilities-for-python.html" rel="nofollow">Capabilities for Python?</a> by Guido himself</li>
</ul>
<p>There is also a dead google code project at <a href="http://code.google.com/p/sandbox-python/" rel="nofollow">http://code.google.com/p/sandbox-python/</a></p>
| 8 | 2009-05-14T07:12:56Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 861,969 | <blockquote>
<p>I'd be wary about releasing such
applications into the wild for fear of
someone either accidentally, or
maliciously, adding destructive code
to the file.</p>
</blockquote>
<p>Your native code that's "in the wild" is equally vulnerable to this attack; that it is in machine code is just a speed bump, and no security.</p>
<p>If you are extremely paranoid and want a higher speedbump, you could make your native app that hosts the script instance check a hash of the content. Then accidential changes are impossible; only deliberate changes would go to the trouble of updating the checksum. You could go further and check they were signed with a public key too; then only hacking your native app could let new scripts in.</p>
<p>But the sandboxing? Don't worry about it!</p>
| 1 | 2009-05-14T07:15:18Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 862,025 | <p>You might try IronPython on Silverlight/Moonlight, as <a href="http://www.trypython.org/" rel="nofollow">these guys</a> impressively seem to be doing. There is a lot of great information on these types of IronPython applications from the Resolver One developers <a href="http://www.voidspace.org.uk/ironpython/silverlight/index.shtml#python-interactive-interpreter-in-a-browser" rel="nofollow">here</a>.</p>
| 1 | 2009-05-14T07:35:37Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 862,030 | <p>I don't really know much about exactly what security capabilities you get within the Java Virtual Machine or .NET runtimes, but you might want to consider if running your python code with <a href="http://www.jython.org/Project/" rel="nofollow">Jython</a> or <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython" rel="nofollow">IronPython</a> might allow you to get added security.</p>
| 1 | 2009-05-14T07:37:09Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 866,612 | <p>For some discussion on issues previously met with the <code>rexec</code> module:</p>
<ul>
<li><a href="http://mail.python.org/pipermail/python-dev/2002-December/031160.html" rel="nofollow">http://mail.python.org/pipermail/python-dev/2002-December/031160.html</a></li>
<li><a href="http://mail.python.org/pipermail/python-dev/2003-January/031848.html" rel="nofollow">http://mail.python.org/pipermail/python-dev/2003-January/031848.html</a></li>
</ul>
<p>These came from <a href="http://www.amk.ca/python/howto/rexec/" rel="nofollow">Restricted Execution HOWTO</a>.</p>
| 0 | 2009-05-15T01:03:10Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 1,000,418 | <p>It's a little hard to understand what you're trying to do -- not enough details.</p>
<p>Are you hosting the native app and allowing the users to write plugins? Consider using an OS-level solution by running the Python application as a separate runtime process inside a jail/chroot/similar, and communicating over sockets.</p>
<p>Are you expecting your customers to host the native app and let "untrusted parties" write plugins? Is there a reason the solution above won't work? (E.g., the customer would like to deploy on weird OSs without such options...)</p>
<p>Are you expecting the same people to host the native app and the "untrusted script" and want to protect them from themselves? In the sense of protecting them from writing "os.remove" and having it do what they wrote? Can you explain why?</p>
<p>Note that sandboxing alone is often not enough without stricter constraints (maximum CPU cycles, maximum memory, memory ownership issues...)? What kind of maliciousness do you want to stop? Note that here, too, OSs have wonderful capabilities (priorities, killing processes, ulimits) that not all sandboxing environments replicate -- and are certainly less security-tested than the things in OSs. (I'd trust Linux not to have breakable ulimits before I'd trust PyPy not to enable a malicious coder to take up unbounded amounts of memory, simply because Linux has been attacked in the wild more.)</p>
| 1 | 2009-06-16T09:27:19Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 1,036,090 | <p>tinypy (<a href="http://tinypy.org" rel="nofollow">tinypy.org</a>) was made to be a small, embed-able Python subset written in the style of Lua. And as lua has a manner to create a sandbox, I estimate that tinypy could be hacked along the same vein. Since tinypy's code base is so small, it's pretty easy to learn and figure out how to change things around to fit your needs.</p>
| 2 | 2009-06-24T01:49:19Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 1,134,995 | <p>The <a href="http://pythononachip.org" rel="nofollow">PyMite VM</a> fits the bill if all you need to do is set simple variables, loops, conditionals and functions. PyMite is tiny, written in C, uses a static memory pool and can be embedded. It has an extremely limited set of builtin functions that is easy to configure. Similarly, the only standard libraries are partial implementations of string, dict, list and sys. The PyMite VM is part of the python-on-a-chip project, so it was designed to run on microcontrollers, but can run on posix-style desktop systems. The downside is that PyMite is not as extensively de-bugged as other Python implementations.</p>
| 3 | 2009-07-16T01:30:08Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | <p>In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.</p>
<p>While this works great for internal applications, I'd be wary about releasing such applications into the wild for fear of someone either accidentally, or maliciously, adding destructive code to the file. The same would hold true for using Python as an embedded scripting language.</p>
<p>Is there a subset of Python that is deemed "safe" for embedding? I realize how safe it can be considered is fairly subjective. However, Java Applets and Flash both have their security sandbox well defined. I'm wondering if there's a version of Python that has similar rules?</p>
<p><strong>EDIT:</strong> I'm asking not so much because of the config file approach, but because I'm interested in implementing some scripting/plugin mechanisms into a newer app and don't want a plugin or script to be able to, say, delete files. That goes beyond the scope of what the application should be able to do.</p>
| 7 | 2009-05-14T06:37:43Z | 1,135,067 | <p>This sounds like what you want: <a href="http://lwn.net/Articles/321872/" rel="nofollow">Reviving Python restricted mode</a>.</p>
<p>The Python interpreter has a built-in "restricted" mode, enabled by changing the <code>__builtins__</code> magic variable. The article <a href="http://tav.espians.com/paving-the-way-to-securing-the-python-interpreter.html" rel="nofollow">Paving the Way to Securing the Python Interpreter</a> explains the trick in more detail. Note that to work completely, it needs a patch to the Python intrepreter; I do not know if it has already been applied.</p>
<p>For a pure python proof-of-concept, see his previous post <a href="http://tav.espians.com/a-challenge-to-break-python-security.html" rel="nofollow">A Challenge To Break Python Security</a>.</p>
| 0 | 2009-07-16T02:00:45Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] |
Get a unique list/tuple element given a condition in python | 862,158 | <p>How do I get a tuple/list element given a condition in python?
This occurs pretty often and I am looking for a nice-few-lines-pythonic way of doing this.</p>
<p>here could be an example:</p>
<p>Consider a tuple containing 2D points coordinates like this:</p>
<pre><code>points = [[x1, y1],[x2, y2],[x3, y3], ...]
</code></pre>
<p>And I would like to get <b>the</b> point that minimizes the euclidean distance given an arbitrary point (say [X, Y] for instance, my point is : it is not contained in the list!)</p>
<pre><code>def dist(p1, p2):
return sqrt((p2[0]-p1[0])**2+(p2[1]-p1[1])**2)
pointToCompare2 = [X, Y]
</code></pre>
<p>Anyone having a freaky one liner(or not) for that?
Thanks!</p>
| 2 | 2009-05-14T08:18:22Z | 862,191 | <pre><code>min(points, key=lambda x: dist(pointToCompare2, x))
</code></pre>
<p><a href="http://docs.python.org/library/functions.html#min">min is a built-in function</a>.</p>
| 11 | 2009-05-14T08:27:07Z | [
"python",
"list",
"tuples",
"condition"
] |
Get a unique list/tuple element given a condition in python | 862,158 | <p>How do I get a tuple/list element given a condition in python?
This occurs pretty often and I am looking for a nice-few-lines-pythonic way of doing this.</p>
<p>here could be an example:</p>
<p>Consider a tuple containing 2D points coordinates like this:</p>
<pre><code>points = [[x1, y1],[x2, y2],[x3, y3], ...]
</code></pre>
<p>And I would like to get <b>the</b> point that minimizes the euclidean distance given an arbitrary point (say [X, Y] for instance, my point is : it is not contained in the list!)</p>
<pre><code>def dist(p1, p2):
return sqrt((p2[0]-p1[0])**2+(p2[1]-p1[1])**2)
pointToCompare2 = [X, Y]
</code></pre>
<p>Anyone having a freaky one liner(or not) for that?
Thanks!</p>
| 2 | 2009-05-14T08:18:22Z | 17,235,561 | <pre><code>v = [1,3,2,4,7,3,3,4,5,11]
def get_num_uniques(v):
count = []
dup = []
tmp = []
for i in v:
if i not in count:
count.append(i)
else:
dup.append(i)
count.remove(i)
for j in count:
if j not in dup:
tmp.append(j)
return tmp
#Call the function
print get_num_uniques(v)
</code></pre>
| 0 | 2013-06-21T12:44:11Z | [
"python",
"list",
"tuples",
"condition"
] |
How to download a file using python in a 'smarter' way? | 862,173 | <p>I need to download several files via http in Python.</p>
<p>The most obvious way to do it is just using urllib2:</p>
<pre><code>import urllib2
u = urllib2.urlopen('http://server.com/file.html')
localFile = open('file.html', 'w')
localFile.write(u.read())
localFile.close()
</code></pre>
<p>But I'll have to deal with the URLs that are nasty in some way, say like this: <code>http://server.com/!Run.aspx/someoddtext/somemore?id=121&m=pdf</code>. When downloaded via the browser, the file has a human-readable name, ie. <code>accounts.pdf</code>. </p>
<p>Is there any way to handle that in python, so I don't need to know the file names and hardcode them into my script?</p>
| 63 | 2009-05-14T08:21:42Z | 862,198 | <p>Download scripts like that tend to push a header telling the user-agent what to name the file:</p>
<pre><code>Content-Disposition: attachment; filename="the filename.ext"
</code></pre>
<p>If you can grab that header, you can get the proper filename.</p>
<p>There's <a href="http://stackoverflow.com/questions/163009/urllib2-file-name">another thread</a> that has a little bit of code to offer up for <code>Content-Disposition</code>-grabbing.</p>
<pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip')
remotefile.info()['Content-Disposition']
</code></pre>
| 38 | 2009-05-14T08:28:43Z | [
"python",
"http",
"download"
] |
How to download a file using python in a 'smarter' way? | 862,173 | <p>I need to download several files via http in Python.</p>
<p>The most obvious way to do it is just using urllib2:</p>
<pre><code>import urllib2
u = urllib2.urlopen('http://server.com/file.html')
localFile = open('file.html', 'w')
localFile.write(u.read())
localFile.close()
</code></pre>
<p>But I'll have to deal with the URLs that are nasty in some way, say like this: <code>http://server.com/!Run.aspx/someoddtext/somemore?id=121&m=pdf</code>. When downloaded via the browser, the file has a human-readable name, ie. <code>accounts.pdf</code>. </p>
<p>Is there any way to handle that in python, so I don't need to know the file names and hardcode them into my script?</p>
| 63 | 2009-05-14T08:21:42Z | 863,017 | <p>Based on comments and @Oli's anwser, I made a solution like this:</p>
<pre><code>from os.path import basename
from urlparse import urlsplit
def url2name(url):
return basename(urlsplit(url)[2])
def download(url, localFileName = None):
localName = url2name(url)
req = urllib2.Request(url)
r = urllib2.urlopen(req)
if r.info().has_key('Content-Disposition'):
# If the response has Content-Disposition, we take file name from it
localName = r.info()['Content-Disposition'].split('filename=')[1]
if localName[0] == '"' or localName[0] == "'":
localName = localName[1:-1]
elif r.url != url:
# if we were redirected, the real file name we take from the final URL
localName = url2name(r.url)
if localFileName:
# we can force to save the file as specified name
localName = localFileName
f = open(localName, 'wb')
f.write(r.read())
f.close()
</code></pre>
<p>It takes file name from Content-Disposition; if it's not present, uses filename from the URL (if redirection happened, the final URL is taken into account). </p>
| 33 | 2009-05-14T12:23:12Z | [
"python",
"http",
"download"
] |
How to download a file using python in a 'smarter' way? | 862,173 | <p>I need to download several files via http in Python.</p>
<p>The most obvious way to do it is just using urllib2:</p>
<pre><code>import urllib2
u = urllib2.urlopen('http://server.com/file.html')
localFile = open('file.html', 'w')
localFile.write(u.read())
localFile.close()
</code></pre>
<p>But I'll have to deal with the URLs that are nasty in some way, say like this: <code>http://server.com/!Run.aspx/someoddtext/somemore?id=121&m=pdf</code>. When downloaded via the browser, the file has a human-readable name, ie. <code>accounts.pdf</code>. </p>
<p>Is there any way to handle that in python, so I don't need to know the file names and hardcode them into my script?</p>
| 63 | 2009-05-14T08:21:42Z | 2,067,142 | <p>Combining much of the above, here is a more pythonic solution:</p>
<pre><code>import urllib2
import shutil
import urlparse
import os
def download(url, fileName=None):
def getFileName(url,openUrl):
if 'Content-Disposition' in openUrl.info():
# If the response has Content-Disposition, try to get filename from it
cd = dict(map(
lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),
openUrl.info()['Content-Disposition'].split(';')))
if 'filename' in cd:
filename = cd['filename'].strip("\"'")
if filename: return filename
# if no filename was found above, parse it out of the final URL.
return os.path.basename(urlparse.urlsplit(openUrl.url)[2])
r = urllib2.urlopen(urllib2.Request(url))
try:
fileName = fileName or getFileName(url,r)
with open(fileName, 'wb') as f:
shutil.copyfileobj(r,f)
finally:
r.close()
</code></pre>
| 22 | 2010-01-14T19:54:30Z | [
"python",
"http",
"download"
] |
How to download a file using python in a 'smarter' way? | 862,173 | <p>I need to download several files via http in Python.</p>
<p>The most obvious way to do it is just using urllib2:</p>
<pre><code>import urllib2
u = urllib2.urlopen('http://server.com/file.html')
localFile = open('file.html', 'w')
localFile.write(u.read())
localFile.close()
</code></pre>
<p>But I'll have to deal with the URLs that are nasty in some way, say like this: <code>http://server.com/!Run.aspx/someoddtext/somemore?id=121&m=pdf</code>. When downloaded via the browser, the file has a human-readable name, ie. <code>accounts.pdf</code>. </p>
<p>Is there any way to handle that in python, so I don't need to know the file names and hardcode them into my script?</p>
| 63 | 2009-05-14T08:21:42Z | 2,503,668 | <p><strong>2 Kender</strong>:</p>
<pre><code>if localName[0] == '"' or localName[0] == "'":
localName = localName[1:-1]
</code></pre>
<p>it is not safe -- web server can pass wrong formatted name as ["file.ext] or [file.ext'] or even be empty and <strong>localName[0]</strong> will raise exception.
Correct code can looks like this:</p>
<pre><code>localName = localName.replace('"', '').replace("'", "")
if localName == '':
localName = SOME_DEFAULT_FILE_NAME
</code></pre>
| 1 | 2010-03-23T21:12:58Z | [
"python",
"http",
"download"
] |
How to download a file using python in a 'smarter' way? | 862,173 | <p>I need to download several files via http in Python.</p>
<p>The most obvious way to do it is just using urllib2:</p>
<pre><code>import urllib2
u = urllib2.urlopen('http://server.com/file.html')
localFile = open('file.html', 'w')
localFile.write(u.read())
localFile.close()
</code></pre>
<p>But I'll have to deal with the URLs that are nasty in some way, say like this: <code>http://server.com/!Run.aspx/someoddtext/somemore?id=121&m=pdf</code>. When downloaded via the browser, the file has a human-readable name, ie. <code>accounts.pdf</code>. </p>
<p>Is there any way to handle that in python, so I don't need to know the file names and hardcode them into my script?</p>
| 63 | 2009-05-14T08:21:42Z | 39,573,403 | <p>Using <code>wget</code>:</p>
<pre><code>custom_file_name = "/custom/path/custom_name.ext"
wget.download(url, custom_file_name)
</code></pre>
<p>Using urlretrieve: </p>
<pre><code>urllib.urlretrieve(url, custom_file_name)
</code></pre>
<p>urlretrieve also creates the directory structure if not exists. </p>
| 0 | 2016-09-19T12:37:58Z | [
"python",
"http",
"download"
] |
Txt file parse to get a list of .o file names | 862,203 | <p>I have a txt file like :</p>
<p>test.txt </p>
<pre><code>Symbols from __ctype_tab.o:
Name Value Class Type Size Line Section
__ctype |00000000| D | OBJECT|00000004| |.data
__ctype_tab |00000000| r | OBJECT|00000101| |.rodata
Symbols from _ashldi3.o:
Name Value Class Type Size Line Section
__ashldi3 |00000000| T | FUNC|00000050| |.text
Symbols from _ashrdi3.o:
Name Value Class Type Size Line Section
__ashrdi3 |00000000| T | FUNC|00000058| |.text
Symbols from _fixdfdi.o:
Name Value Class Type Size Line Section
__fixdfdi |00000000| T | FUNC|0000004c| |.text
__fixunsdfdi | | U | NOTYPE| | |*UND*
Symbols from _fixsfdi.o:
Name Value Class Type Size Line Section
__fixsfdi |00000000| T | FUNC|0000004c| |.text
__fixunssfdi | | U | NOTYPE| | |*UND*
Symbols from _fixunssfdi.o:
Name Value Class Type Size Line Section
__cmpdi2 | | U | NOTYPE| | |*UND*
__fixunssfdi |00000000| T | FUNC|00000228| |.text
__floatdidf | | U | NOTYPE| | |*UND*
</code></pre>
<p>What i want to do is , i will be given a function whose type is NOTYPE . i need to search the txt and find under which .o it's defined(ie;with type FUNC).When i get the .o file,i may see other functions as NOTYPE. Then i have to search where those are defined.it goes on. Finally i want to return a list of names of all .o files which contained the functions.</p>
<p>My piece of code:</p>
<pre><code>notypeDict , funcDict = {} , {}
notypeList , funcList = [] , []
currObj , prevObj = '' , ''
fp = open(r'C:\test.txt','r') # file path cms here
fileList = fp.readlines()
for line in fileList:
if '.o' in line: # line containg .o
currObj=line.split()[-1][0:-1]
if '|' not in line: # line containg |
pass
else: # other lines
dataList=[dataItem.strip() for dataItem in line.strip().split('|')] # a list of each word in line
name=dataList[0].strip() # name of the function
notypeDict[prevObj] = notypeList # notypeDict is a dictionary which contains .o as key and a list of NOTYPE function name
funcDict[prevObj] = funcList # funcDict is a dictionary which contains .o as key and a list of FUNC function names
if prevObj == currObj :
pass
if prevObj != currObj :
notypeList , funcList = [] , []
if dataList[3] == 'NOTYPE' :
notypeList.append(name)
if dataList[3] == 'FUNC' :
funcList.append(name)
prevObj = currObj
print 'notypeDict' , notypeDict
print '\n\nfuncDict' , funcDict
</code></pre>
<p>Here i will get two dictionaries, notypeDict and funcDict.</p>
<p>notypeDict has .o as key and a list of NOTYPE functions as value
funcDict has .o as key and a list of FUNC functions as value.</p>
<p><strong>I reached till here.</strong></p>
<p>But don't getting ideas how to proceed to achieve my target.</p>
<p>I think my question is clear.</p>
<p><strong>Please help me out.</strong></p>
| 0 | 2009-05-14T08:30:49Z | 862,401 | <p>I would use regular expressions with capture groups for the different kinds of interesting lines in your file; I'd go through the file line by line, and as I found an interesting line (i.e. matched the regex), I'd process the captured data from the regex appropriately.</p>
<p>After having built up dictionaries etc., answering questions based on the data is easy.</p>
| 1 | 2009-05-14T09:28:52Z | [
"python",
"parsing"
] |
Txt file parse to get a list of .o file names | 862,203 | <p>I have a txt file like :</p>
<p>test.txt </p>
<pre><code>Symbols from __ctype_tab.o:
Name Value Class Type Size Line Section
__ctype |00000000| D | OBJECT|00000004| |.data
__ctype_tab |00000000| r | OBJECT|00000101| |.rodata
Symbols from _ashldi3.o:
Name Value Class Type Size Line Section
__ashldi3 |00000000| T | FUNC|00000050| |.text
Symbols from _ashrdi3.o:
Name Value Class Type Size Line Section
__ashrdi3 |00000000| T | FUNC|00000058| |.text
Symbols from _fixdfdi.o:
Name Value Class Type Size Line Section
__fixdfdi |00000000| T | FUNC|0000004c| |.text
__fixunsdfdi | | U | NOTYPE| | |*UND*
Symbols from _fixsfdi.o:
Name Value Class Type Size Line Section
__fixsfdi |00000000| T | FUNC|0000004c| |.text
__fixunssfdi | | U | NOTYPE| | |*UND*
Symbols from _fixunssfdi.o:
Name Value Class Type Size Line Section
__cmpdi2 | | U | NOTYPE| | |*UND*
__fixunssfdi |00000000| T | FUNC|00000228| |.text
__floatdidf | | U | NOTYPE| | |*UND*
</code></pre>
<p>What i want to do is , i will be given a function whose type is NOTYPE . i need to search the txt and find under which .o it's defined(ie;with type FUNC).When i get the .o file,i may see other functions as NOTYPE. Then i have to search where those are defined.it goes on. Finally i want to return a list of names of all .o files which contained the functions.</p>
<p>My piece of code:</p>
<pre><code>notypeDict , funcDict = {} , {}
notypeList , funcList = [] , []
currObj , prevObj = '' , ''
fp = open(r'C:\test.txt','r') # file path cms here
fileList = fp.readlines()
for line in fileList:
if '.o' in line: # line containg .o
currObj=line.split()[-1][0:-1]
if '|' not in line: # line containg |
pass
else: # other lines
dataList=[dataItem.strip() for dataItem in line.strip().split('|')] # a list of each word in line
name=dataList[0].strip() # name of the function
notypeDict[prevObj] = notypeList # notypeDict is a dictionary which contains .o as key and a list of NOTYPE function name
funcDict[prevObj] = funcList # funcDict is a dictionary which contains .o as key and a list of FUNC function names
if prevObj == currObj :
pass
if prevObj != currObj :
notypeList , funcList = [] , []
if dataList[3] == 'NOTYPE' :
notypeList.append(name)
if dataList[3] == 'FUNC' :
funcList.append(name)
prevObj = currObj
print 'notypeDict' , notypeDict
print '\n\nfuncDict' , funcDict
</code></pre>
<p>Here i will get two dictionaries, notypeDict and funcDict.</p>
<p>notypeDict has .o as key and a list of NOTYPE functions as value
funcDict has .o as key and a list of FUNC functions as value.</p>
<p><strong>I reached till here.</strong></p>
<p>But don't getting ideas how to proceed to achieve my target.</p>
<p>I think my question is clear.</p>
<p><strong>Please help me out.</strong></p>
| 0 | 2009-05-14T08:30:49Z | 862,616 | <p>What do you think the following does?</p>
<pre><code> if '.o' in line: # line containg .o
currObj=line.split()[-1][0:-1]
if '|' not in line: # line containg |
pass
else: # other lines
</code></pre>
<p>Does it find lines with '.o' or '|' or other?</p>
<p>No. Actually, it doesn't.</p>
<p>It finds lines that contain '.o'. And does something with them.</p>
<p>Then it checks that line again for '|' or "other". All of your '.o' lines are processed two times.</p>
<p>Once as a '.o', then again as a "not |".</p>
<p>You might mean <code>elif</code> instead of <code>if</code>.</p>
<p><hr /></p>
<p>This code</p>
<pre><code> if prevObj == currObj :
pass
if prevObj != currObj :
notypeList , funcList = [] , []
</code></pre>
<p>Is rather more complex than it needs to be. Doesn't cause a problem, <em>per se</em>, but it is silly-looking.</p>
<p><hr /></p>
<p>This code </p>
<pre><code> if dataList[3] == 'NOTYPE' :
notypeList.append(name)
if dataList[3] == 'FUNC' :
funcList.append(name)
</code></pre>
<p>is probably good. However, it looks bad because the conditions are exclusive and would look better as <code>elif</code>. </p>
| 1 | 2009-05-14T10:28:12Z | [
"python",
"parsing"
] |
Txt file parse to get a list of .o file names | 862,203 | <p>I have a txt file like :</p>
<p>test.txt </p>
<pre><code>Symbols from __ctype_tab.o:
Name Value Class Type Size Line Section
__ctype |00000000| D | OBJECT|00000004| |.data
__ctype_tab |00000000| r | OBJECT|00000101| |.rodata
Symbols from _ashldi3.o:
Name Value Class Type Size Line Section
__ashldi3 |00000000| T | FUNC|00000050| |.text
Symbols from _ashrdi3.o:
Name Value Class Type Size Line Section
__ashrdi3 |00000000| T | FUNC|00000058| |.text
Symbols from _fixdfdi.o:
Name Value Class Type Size Line Section
__fixdfdi |00000000| T | FUNC|0000004c| |.text
__fixunsdfdi | | U | NOTYPE| | |*UND*
Symbols from _fixsfdi.o:
Name Value Class Type Size Line Section
__fixsfdi |00000000| T | FUNC|0000004c| |.text
__fixunssfdi | | U | NOTYPE| | |*UND*
Symbols from _fixunssfdi.o:
Name Value Class Type Size Line Section
__cmpdi2 | | U | NOTYPE| | |*UND*
__fixunssfdi |00000000| T | FUNC|00000228| |.text
__floatdidf | | U | NOTYPE| | |*UND*
</code></pre>
<p>What i want to do is , i will be given a function whose type is NOTYPE . i need to search the txt and find under which .o it's defined(ie;with type FUNC).When i get the .o file,i may see other functions as NOTYPE. Then i have to search where those are defined.it goes on. Finally i want to return a list of names of all .o files which contained the functions.</p>
<p>My piece of code:</p>
<pre><code>notypeDict , funcDict = {} , {}
notypeList , funcList = [] , []
currObj , prevObj = '' , ''
fp = open(r'C:\test.txt','r') # file path cms here
fileList = fp.readlines()
for line in fileList:
if '.o' in line: # line containg .o
currObj=line.split()[-1][0:-1]
if '|' not in line: # line containg |
pass
else: # other lines
dataList=[dataItem.strip() for dataItem in line.strip().split('|')] # a list of each word in line
name=dataList[0].strip() # name of the function
notypeDict[prevObj] = notypeList # notypeDict is a dictionary which contains .o as key and a list of NOTYPE function name
funcDict[prevObj] = funcList # funcDict is a dictionary which contains .o as key and a list of FUNC function names
if prevObj == currObj :
pass
if prevObj != currObj :
notypeList , funcList = [] , []
if dataList[3] == 'NOTYPE' :
notypeList.append(name)
if dataList[3] == 'FUNC' :
funcList.append(name)
prevObj = currObj
print 'notypeDict' , notypeDict
print '\n\nfuncDict' , funcDict
</code></pre>
<p>Here i will get two dictionaries, notypeDict and funcDict.</p>
<p>notypeDict has .o as key and a list of NOTYPE functions as value
funcDict has .o as key and a list of FUNC functions as value.</p>
<p><strong>I reached till here.</strong></p>
<p>But don't getting ideas how to proceed to achieve my target.</p>
<p>I think my question is clear.</p>
<p><strong>Please help me out.</strong></p>
| 0 | 2009-05-14T08:30:49Z | 863,018 | <p>What about this code? It is based on your two dictionaries. Just call <code>find_dep_for_func(notype_funcname)</code>.</p>
<pre><code>def find_ofile(funcname):
"""This will find .o file for given function."""
for ofile, fns in funcDict.iteritems():
if funcname in fns:
return ofile
raise Exception("Cannot find function "+funcname)
def find_dependencies(ofile, deps = None):
"""This will find dependent .o files for given .o file."""
olist = deps if deps else set([])
for fn in notypeDict[ofile]:
ofile = find_ofile(fn)
if not ofile in olist:
olist.add(ofile)
olist = find_dependencies(ofile, olist)
return olist
def find_dep_for_func(notype_funcname):
return find_dependencies(find_ofile(funcname))
</code></pre>
| 1 | 2009-05-14T12:23:14Z | [
"python",
"parsing"
] |
Delete all files/directories except two specific directories | 862,388 | <p>So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.</p>
<p>For example, here is an example directory tree:</p>
<pre><code>.
|-- coke
| |-- diet
| |-- regular
| `-- vanilla
|-- icecream
| |-- chocolate
| |-- cookiedough
| |-- cupcake
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- vanilla
|-- lol.txt
|-- mtndew
| |-- classic
| |-- codered
| |-- livewire
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- throwback
`-- pepsi
|-- blue
|-- classic
|-- diet
`-- throwback
</code></pre>
<p>I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.</p>
| 4 | 2009-05-14T09:25:37Z | 862,450 | <p>use <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?find" rel="nofollow"><code>find</code></a>.</p>
<p>Your command will look something like:</p>
<pre><code>find $directory \( -prune 'some pattern' \) -delete
</code></pre>
| 0 | 2009-05-14T09:43:04Z | [
"python",
"linux",
"bash"
] |
Delete all files/directories except two specific directories | 862,388 | <p>So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.</p>
<p>For example, here is an example directory tree:</p>
<pre><code>.
|-- coke
| |-- diet
| |-- regular
| `-- vanilla
|-- icecream
| |-- chocolate
| |-- cookiedough
| |-- cupcake
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- vanilla
|-- lol.txt
|-- mtndew
| |-- classic
| |-- codered
| |-- livewire
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- throwback
`-- pepsi
|-- blue
|-- classic
|-- diet
`-- throwback
</code></pre>
<p>I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.</p>
| 4 | 2009-05-14T09:25:37Z | 862,561 | <p>You could do something based on <a href="http://docs.python.org/library/os.html" rel="nofollow">Python's os.walk function</a>:</p>
<pre><code>import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
</code></pre>
<p>...just add something to ignore the paths you're interested in.</p>
| 2 | 2009-05-14T10:14:26Z | [
"python",
"linux",
"bash"
] |
Delete all files/directories except two specific directories | 862,388 | <p>So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.</p>
<p>For example, here is an example directory tree:</p>
<pre><code>.
|-- coke
| |-- diet
| |-- regular
| `-- vanilla
|-- icecream
| |-- chocolate
| |-- cookiedough
| |-- cupcake
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- vanilla
|-- lol.txt
|-- mtndew
| |-- classic
| |-- codered
| |-- livewire
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- throwback
`-- pepsi
|-- blue
|-- classic
|-- diet
`-- throwback
</code></pre>
<p>I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.</p>
| 4 | 2009-05-14T09:25:37Z | 862,589 | <p>Everything "except" is why we have if-statements; and why os.walk's list of directories is a mutable list.</p>
<pre><code>for path, dirs, files in os.walk( 'root' ):
if 'coke' in dirs:
dirs.remove('coke')
dirs.remove('pepsi')
</code></pre>
| 3 | 2009-05-14T10:20:06Z | [
"python",
"linux",
"bash"
] |
Delete all files/directories except two specific directories | 862,388 | <p>So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.</p>
<p>For example, here is an example directory tree:</p>
<pre><code>.
|-- coke
| |-- diet
| |-- regular
| `-- vanilla
|-- icecream
| |-- chocolate
| |-- cookiedough
| |-- cupcake
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- vanilla
|-- lol.txt
|-- mtndew
| |-- classic
| |-- codered
| |-- livewire
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- throwback
`-- pepsi
|-- blue
|-- classic
|-- diet
`-- throwback
</code></pre>
<p>I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.</p>
| 4 | 2009-05-14T09:25:37Z | 862,622 | <p><code>find</code>'s <code>-prune</code> comes to mind, but it's a pain to get it to work for specific paths (<code>icecream/cupcake/</code>) rather than specific directories (<code>cupcake/</code>).</p>
<p>Personally, I'd just use <code>cpio</code> and hard-link (to avoid having to copy them) the files in the directories you want to keep to a new tree and then remove the old one:</p>
<pre><code>find test -path 'test/icecream/cupcake/*' -o -path 'test/mtndew/livewire/*' | cpio -padluv test-keep
rm -rf test
</code></pre>
<p>That'll also keep your existing directory structure for the directories you intend to keep.</p>
| 3 | 2009-05-14T10:30:37Z | [
"python",
"linux",
"bash"
] |
Delete all files/directories except two specific directories | 862,388 | <p>So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.</p>
<p>For example, here is an example directory tree:</p>
<pre><code>.
|-- coke
| |-- diet
| |-- regular
| `-- vanilla
|-- icecream
| |-- chocolate
| |-- cookiedough
| |-- cupcake
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- vanilla
|-- lol.txt
|-- mtndew
| |-- classic
| |-- codered
| |-- livewire
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- throwback
`-- pepsi
|-- blue
|-- classic
|-- diet
`-- throwback
</code></pre>
<p>I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.</p>
| 4 | 2009-05-14T09:25:37Z | 862,666 | <p>Move the stuff you want to keep elsewhere, then delete what's left.</p>
| 2 | 2009-05-14T10:45:50Z | [
"python",
"linux",
"bash"
] |
Delete all files/directories except two specific directories | 862,388 | <p>So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.</p>
<p>For example, here is an example directory tree:</p>
<pre><code>.
|-- coke
| |-- diet
| |-- regular
| `-- vanilla
|-- icecream
| |-- chocolate
| |-- cookiedough
| |-- cupcake
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- vanilla
|-- lol.txt
|-- mtndew
| |-- classic
| |-- codered
| |-- livewire
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- throwback
`-- pepsi
|-- blue
|-- classic
|-- diet
`-- throwback
</code></pre>
<p>I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.</p>
| 4 | 2009-05-14T09:25:37Z | 862,680 | <p>A oneliner to solve the problem:</p>
<p><del>find . |grep -v "test/icecream/cupcake/"| grep -v "test/mtndew/livewire/"|xargs rm -r</del></p>
<p>Removed since it does not work</p>
<p>this might get you into trouble if have file names with space in them, and it might keep more files then you want if there are other trees that match the patterns.</p>
<p>A somewhat better solution:</p>
<pre><code>find . |sed "s/.*/rm '&'/"|grep -v "rm './test/icecream/cupcake/"| grep -v "rm './test/mtndew/livewire/"|sh
</code></pre>
<p>Not actually tested, if it breaks you get to keep both parts. </p>
<p>Edit: As Dennis points its not only two parts that it breaks into :-) corrected the typos in the second example and removed the first</p>
| 0 | 2009-05-14T10:50:51Z | [
"python",
"linux",
"bash"
] |
Delete all files/directories except two specific directories | 862,388 | <p>So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.</p>
<p>For example, here is an example directory tree:</p>
<pre><code>.
|-- coke
| |-- diet
| |-- regular
| `-- vanilla
|-- icecream
| |-- chocolate
| |-- cookiedough
| |-- cupcake
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- vanilla
|-- lol.txt
|-- mtndew
| |-- classic
| |-- codered
| |-- livewire
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- throwback
`-- pepsi
|-- blue
|-- classic
|-- diet
`-- throwback
</code></pre>
<p>I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.</p>
| 4 | 2009-05-14T09:25:37Z | 863,294 | <p>This command will leave only the desired files in their original directories:</p>
<pre><code>find test \( ! -path "test/mtndew/livewire/*" ! -path "test/icecream/cupcake/*" \) -delete
</code></pre>
<p>No need for cpio. It works on Ubuntu, Debian 5, and Mac OS X.</p>
<p>On Linux, it will report that it cannot delete non-empty directories, which is exactly the desired result. On Mac OS X, it will quietly do the right thing.</p>
| 4 | 2009-05-14T13:18:39Z | [
"python",
"linux",
"bash"
] |
Delete all files/directories except two specific directories | 862,388 | <p>So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.</p>
<p>For example, here is an example directory tree:</p>
<pre><code>.
|-- coke
| |-- diet
| |-- regular
| `-- vanilla
|-- icecream
| |-- chocolate
| |-- cookiedough
| |-- cupcake
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- vanilla
|-- lol.txt
|-- mtndew
| |-- classic
| |-- codered
| |-- livewire
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- throwback
`-- pepsi
|-- blue
|-- classic
|-- diet
`-- throwback
</code></pre>
<p>I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.</p>
| 4 | 2009-05-14T09:25:37Z | 863,762 | <p>It works for me with find using two steps: first delete the files allowed, then their empty directories! </p>
<pre><code>find -x -E ~/Desktop/test -not \( -type d -regex '.*/(cupcake|livewire)/*.*' -prune \) -print0 | xargs -0 ls -1 -dG
# delete the files first
# Mac OS X 10.4
find -x -E ~/Desktop/test -not \( -type d -regex '.*/(cupcake|livewire)/*.*' -prune \) -type f -exec /bin/rm -fv '{}' \;
# Mac OS X 10.5
find -x -E ~/Desktop/test -not \( -type d -regex '.*/(cupcake|livewire)/*.*' -prune \) -type f -exec /bin/rm -fv '{}' +
# delete empty directories
find -x ~/Desktop/test -type d -empty -delete
</code></pre>
| 0 | 2009-05-14T14:49:48Z | [
"python",
"linux",
"bash"
] |
Delete all files/directories except two specific directories | 862,388 | <p>So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.</p>
<p>For example, here is an example directory tree:</p>
<pre><code>.
|-- coke
| |-- diet
| |-- regular
| `-- vanilla
|-- icecream
| |-- chocolate
| |-- cookiedough
| |-- cupcake
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- vanilla
|-- lol.txt
|-- mtndew
| |-- classic
| |-- codered
| |-- livewire
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- throwback
`-- pepsi
|-- blue
|-- classic
|-- diet
`-- throwback
</code></pre>
<p>I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.</p>
| 4 | 2009-05-14T09:25:37Z | 866,793 | <p>Like others I have used os.walk and os.path.join to build the list of files to delete, with fnmatch.fnmatch to select files that must be included or excluded:</p>
<pre><code>#-------------------------------#
# make list of files to display #
#-------------------------------#
displayList = []
for imageDir in args :
for root,dirs,files in os.walk(imageDir) :
for filename in files :
pathname = os.path.join( root, filename )
if fnmatch.fnmatch( pathname, options.includePattern ) :
displayList.append( pathname )
#----# now filter out excluded patterns #----#
try :
if len(options.excludePattern) > 0 :
for pattern in options.excludePattern :
displayList = [pathname for pathname in displayList if not fnmatch.fnmatch( pathname, pattern ) ]
except ( AttributeError, TypeError ) :
pass
</code></pre>
<p>If fnmatch isn't enough, you can use the re module to test patterns.</p>
<p>Here I have built the file list before I do anything with it, but you could process the files as they are generated. </p>
<p>The try/except block...is there in case my options class instance doesn't have an exclude pattern, or if it causes an exception in fnmatch because it is the wrong type.</p>
<p>A limitation of this method is that it first <em>includes</em> files matching a pattern, <em>then excludes</em>. If you need more flexibility than this (include matching pattern a, but not pattern b unless pattern c...) well, then the fragment above isn't up to it. In fact, working through this exercise, you start to see why the find command syntax is the way it is. Seems clunky, but in fact it is exactly the way to do this.</p>
<p>But if you generate a list, you can filter it according to whatever inclusion/exclusion rules you need. </p>
<p>One nice thing about generating a list is you can check it before you go ahead with the deletion. This is sort of a '--dryrun' option. You can do this interactively in the python interpreter, print the list to see how it looks, apply the next filter, see if it has removed too much or too little and so on.</p>
| 0 | 2009-05-15T02:52:00Z | [
"python",
"linux",
"bash"
] |
Delete all files/directories except two specific directories | 862,388 | <p>So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.</p>
<p>For example, here is an example directory tree:</p>
<pre><code>.
|-- coke
| |-- diet
| |-- regular
| `-- vanilla
|-- icecream
| |-- chocolate
| |-- cookiedough
| |-- cupcake
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- vanilla
|-- lol.txt
|-- mtndew
| |-- classic
| |-- codered
| |-- livewire
| | |-- file1.txt
| | |-- file2.txt
| | |-- file3.txt
| | |-- file4.txt
| | `-- file5.txt
| `-- throwback
`-- pepsi
|-- blue
|-- classic
|-- diet
`-- throwback
</code></pre>
<p>I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.</p>
| 4 | 2009-05-14T09:25:37Z | 3,583,448 | <pre><code>find /path/to/test/ -depth -mindepth 1 \
! -path "/path/to/test/icecream/cupcake/*" \
! -path "/path/to/test/icecream/cupcake" \
! -path "/path/to/test/icecream" \
! -path "/path/to/test/mtndew/livewire/*" \
! -path "/path/to/test/mtndew/livewire" \
! -path "/path/to/test/mtndew"
-delete -print
</code></pre>
<p>It's a bit tedious to write all the paths to preserve but thi is the only way to use find alone.</p>
| 1 | 2010-08-27T10:53:07Z | [
"python",
"linux",
"bash"
] |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | <p>I am a python newbie trying to achieve the following:</p>
<p>I have a list of lists:</p>
<pre><code>lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
</code></pre>
<p>I want map lst into another list containing only the second smallest number from each sublist. So the result should be:</p>
<pre><code>[345, 465, 333]
</code></pre>
<p>For example if I were just interested in the smallest number, I could do:</p>
<pre><code>map(lambda x: min(x),lst)
</code></pre>
<p>I wish I could do this:</p>
<pre><code>map(lambda x: sort(x)[1],lst)
</code></pre>
<p>but sort does not chain. (returns None)</p>
<p>neither is something like this allowed:</p>
<pre><code>map(lambda x: sort(x); x[1],lst) #hence the multiple statement question
</code></pre>
<p>Is there a way to do this with map in python but <em>without defining a named function</em>? (it is easy with anonymous blocks in ruby, for example)</p>
| 45 | 2009-05-14T09:31:34Z | 862,430 | <p>Use <a href="http://docs.python.org/library/functions.html#sorted">sorted function</a>, like this:</p>
<pre><code>map(lambda x: sorted(x)[1],lst)
</code></pre>
| 5 | 2009-05-14T09:37:14Z | [
"python"
] |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | <p>I am a python newbie trying to achieve the following:</p>
<p>I have a list of lists:</p>
<pre><code>lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
</code></pre>
<p>I want map lst into another list containing only the second smallest number from each sublist. So the result should be:</p>
<pre><code>[345, 465, 333]
</code></pre>
<p>For example if I were just interested in the smallest number, I could do:</p>
<pre><code>map(lambda x: min(x),lst)
</code></pre>
<p>I wish I could do this:</p>
<pre><code>map(lambda x: sort(x)[1],lst)
</code></pre>
<p>but sort does not chain. (returns None)</p>
<p>neither is something like this allowed:</p>
<pre><code>map(lambda x: sort(x); x[1],lst) #hence the multiple statement question
</code></pre>
<p>Is there a way to do this with map in python but <em>without defining a named function</em>? (it is easy with anonymous blocks in ruby, for example)</p>
| 45 | 2009-05-14T09:31:34Z | 862,457 | <p>Or if you want to avoid lambda and have a generator instead of a list:</p>
<p>(sorted(col)[1] for col in lst)</p>
| 3 | 2009-05-14T09:44:08Z | [
"python"
] |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | <p>I am a python newbie trying to achieve the following:</p>
<p>I have a list of lists:</p>
<pre><code>lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
</code></pre>
<p>I want map lst into another list containing only the second smallest number from each sublist. So the result should be:</p>
<pre><code>[345, 465, 333]
</code></pre>
<p>For example if I were just interested in the smallest number, I could do:</p>
<pre><code>map(lambda x: min(x),lst)
</code></pre>
<p>I wish I could do this:</p>
<pre><code>map(lambda x: sort(x)[1],lst)
</code></pre>
<p>but sort does not chain. (returns None)</p>
<p>neither is something like this allowed:</p>
<pre><code>map(lambda x: sort(x); x[1],lst) #hence the multiple statement question
</code></pre>
<p>Is there a way to do this with map in python but <em>without defining a named function</em>? (it is easy with anonymous blocks in ruby, for example)</p>
| 45 | 2009-05-14T09:31:34Z | 862,498 | <p>There are several different answers I can give here, from your specific question to more general concerns. so from most specific to most general:</p>
<p><strong>Q.</strong> Can you put multiple statements in a lambda?</p>
<p><strong>A.</strong> No. But you don't actually need to use a lambda. You can put the statements in a <code>def</code> instead. ie:</p>
<pre><code>def second_lowest(l):
l.sort()
return l[1]
map(second_lowest, lst)
</code></pre>
<p><strong>Q.</strong> Can you get the second lowest item from a lambda by sorting the list?</p>
<p><strong>A.</strong> Yes. As <a href="http://stackoverflow.com/questions/862412/is-it-possible-to-have-multiple-statements-in-a-python-lambda-expression/862430#862430">alex's answer</a> poinst out, <code>sorted()</code> is a version of sort that creates a new list, rather than sorting in-place, and can be chained. Note that this is probably what you should be using - it's bad practice for your map to have side effects on the original list.</p>
<p><strong>Q.</strong> How should I get the second lowest item from each list in a sequence of lists.</p>
<p><strong>A.</strong> <code>sorted(l)[1]</code> is not actually the best way for this. It has O(N log(N)) complexity, while an O(n) solution exists. This can be found in the heapq module.</p>
<pre><code>>>> import heapq
>>> l = [5,2,6,8,3,5]
>>> heapq.nsmallest(l, 2)
[2, 3]
</code></pre>
<p>So just use:</p>
<pre><code>map(lambda x: heapq.nsmallest(x,2)[1], list_of_lists)
</code></pre>
<p>It's also usually considered clearer to use a list comprehension, which avoids the lambda altogether:</p>
<pre><code>[heapq.nsmallest(x,2)[1] for x in list_of_lists]
</code></pre>
| 67 | 2009-05-14T09:55:37Z | [
"python"
] |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | <p>I am a python newbie trying to achieve the following:</p>
<p>I have a list of lists:</p>
<pre><code>lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
</code></pre>
<p>I want map lst into another list containing only the second smallest number from each sublist. So the result should be:</p>
<pre><code>[345, 465, 333]
</code></pre>
<p>For example if I were just interested in the smallest number, I could do:</p>
<pre><code>map(lambda x: min(x),lst)
</code></pre>
<p>I wish I could do this:</p>
<pre><code>map(lambda x: sort(x)[1],lst)
</code></pre>
<p>but sort does not chain. (returns None)</p>
<p>neither is something like this allowed:</p>
<pre><code>map(lambda x: sort(x); x[1],lst) #hence the multiple statement question
</code></pre>
<p>Is there a way to do this with map in python but <em>without defining a named function</em>? (it is easy with anonymous blocks in ruby, for example)</p>
| 45 | 2009-05-14T09:31:34Z | 6,205,270 | <p>Using begin() from here: <a href="http://www.reddit.com/r/Python/comments/hms4z/ask_pyreddit_if_you_were_making_your_own/c1wycci" rel="nofollow">http://www.reddit.com/r/Python/comments/hms4z/ask_pyreddit_if_you_were_making_your_own/c1wycci</a></p>
<pre><code>Python 3.2 (r32:88445, Mar 25 2011, 19:28:28)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
>>> begin = lambda *args: args[-1]
>>> list(map(lambda x: begin(x.sort(), x[1]), lst))
[345, 465, 333]
</code></pre>
| 2 | 2011-06-01T17:27:51Z | [
"python"
] |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | <p>I am a python newbie trying to achieve the following:</p>
<p>I have a list of lists:</p>
<pre><code>lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
</code></pre>
<p>I want map lst into another list containing only the second smallest number from each sublist. So the result should be:</p>
<pre><code>[345, 465, 333]
</code></pre>
<p>For example if I were just interested in the smallest number, I could do:</p>
<pre><code>map(lambda x: min(x),lst)
</code></pre>
<p>I wish I could do this:</p>
<pre><code>map(lambda x: sort(x)[1],lst)
</code></pre>
<p>but sort does not chain. (returns None)</p>
<p>neither is something like this allowed:</p>
<pre><code>map(lambda x: sort(x); x[1],lst) #hence the multiple statement question
</code></pre>
<p>Is there a way to do this with map in python but <em>without defining a named function</em>? (it is easy with anonymous blocks in ruby, for example)</p>
| 45 | 2009-05-14T09:31:34Z | 17,604,249 | <p>Time traveler here. If you generally want to have multiple statements within a lambda, you can pass other lambdas as arguments to that lambda.</p>
<pre><code>(lambda x, f: list((y[1] for y in f(x))))(lst, lambda x: (sorted(y) for y in x))
</code></pre>
<p>You can't actually have multiple statements, but you can simulate that by passing lambdas to lambdas.</p>
<p><em>Edit:</em> The time traveler returns! You can also abuse the behavior of boolean expressions (keeping in mind short-circuiting rules and truthiness) to chain operations. Using the ternary operator gives you even more power. Again, you can't have multiple <em>statements</em>, but you can of course have many function calls. This example does some arbitrary junk with a bunch of data, but, it shows that you can do some funny stuff. The print statements are examples of functions which return <code>None</code> (as does the <code>.sort()</code> method) but they also help show what the <code>lambda</code> is doing.</p>
<pre><code>>>> (lambda x: print(x) or x+1)(10)
10
11
>>> f = (lambda x: x[::2] if print(x) or x.sort() else print(enumerate(x[::-1]) if print(x) else filter(lambda (i, y): print((i, y)) or (i % 3 and y % 2), enumerate(x[::-1]))))
>>> from random import shuffle
>>> l = list(range(100))
>>> shuffle(l)
>>> f(l)
[84, 58, 7, 99, 17, 14, 60, 35, 12, 56, 26, 48, 55, 40, 28, 52, 31, 39, 43, 96, 64, 63, 54, 37, 79, 25, 46, 72, 10, 59, 24, 68, 23, 13, 34, 41, 94, 29, 62, 2, 50, 32, 11, 97, 98, 3, 70, 93, 1, 36, 87, 47, 20, 73, 45, 0, 65, 57, 6, 76, 16, 85, 95, 61, 4, 77, 21, 81, 82, 30, 53, 51, 42, 67, 74, 8, 15, 83, 5, 9, 78, 66, 44, 27, 19, 91, 90, 18, 49, 86, 22, 75, 71, 88, 92, 33, 89, 69, 80, 38]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
(0, 99)
(1, 98)
(2, 97)
(3, 96)
(4, 95)
(5, 94)
(6, 93)
(7, 92)
(8, 91)
(9, 90)
(10, 89)
(11, 88)
(12, 87)
(13, 86)
(14, 85)
(15, 84)
(16, 83)
(17, 82)
(18, 81)
(19, 80)
(20, 79)
(21, 78)
(22, 77)
(23, 76)
(24, 75)
(25, 74)
(26, 73)
(27, 72)
(28, 71)
(29, 70)
(30, 69)
(31, 68)
(32, 67)
(33, 66)
(34, 65)
(35, 64)
(36, 63)
(37, 62)
(38, 61)
(39, 60)
(40, 59)
(41, 58)
(42, 57)
(43, 56)
(44, 55)
(45, 54)
(46, 53)
(47, 52)
(48, 51)
(49, 50)
(50, 49)
(51, 48)
(52, 47)
(53, 46)
(54, 45)
(55, 44)
(56, 43)
(57, 42)
(58, 41)
(59, 40)
(60, 39)
(61, 38)
(62, 37)
(63, 36)
(64, 35)
(65, 34)
(66, 33)
(67, 32)
(68, 31)
(69, 30)
(70, 29)
(71, 28)
(72, 27)
(73, 26)
(74, 25)
(75, 24)
(76, 23)
(77, 22)
(78, 21)
(79, 20)
(80, 19)
(81, 18)
(82, 17)
(83, 16)
(84, 15)
(85, 14)
(86, 13)
(87, 12)
(88, 11)
(89, 10)
(90, 9)
(91, 8)
(92, 7)
(93, 6)
(94, 5)
(95, 4)
(96, 3)
(97, 2)
(98, 1)
(99, 0)
[(2, 97), (4, 95), (8, 91), (10, 89), (14, 85), (16, 83), (20, 79), (22, 77), (26, 73), (28, 71), (32, 67), (34, 65), (38, 61), (40, 59), (44, 55), (46, 53), (50, 49), (52, 47), (56, 43), (58, 41), (62, 37), (64, 35), (68, 31), (70, 29), (74, 25), (76, 23), (80, 19), (82, 17), (86, 13), (88, 11), (92, 7), (94, 5), (98, 1)]
</code></pre>
| 15 | 2013-07-11T21:59:36Z | [
"python"
] |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | <p>I am a python newbie trying to achieve the following:</p>
<p>I have a list of lists:</p>
<pre><code>lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
</code></pre>
<p>I want map lst into another list containing only the second smallest number from each sublist. So the result should be:</p>
<pre><code>[345, 465, 333]
</code></pre>
<p>For example if I were just interested in the smallest number, I could do:</p>
<pre><code>map(lambda x: min(x),lst)
</code></pre>
<p>I wish I could do this:</p>
<pre><code>map(lambda x: sort(x)[1],lst)
</code></pre>
<p>but sort does not chain. (returns None)</p>
<p>neither is something like this allowed:</p>
<pre><code>map(lambda x: sort(x); x[1],lst) #hence the multiple statement question
</code></pre>
<p>Is there a way to do this with map in python but <em>without defining a named function</em>? (it is easy with anonymous blocks in ruby, for example)</p>
| 45 | 2009-05-14T09:31:34Z | 18,528,195 | <p>Putting the statements in a list may simulate multiple statements:</p>
<p>E.g.:</p>
<pre><code>lambda x: [f1(x), f2(x), f3(x), x+1]
</code></pre>
| 35 | 2013-08-30T08:20:18Z | [
"python"
] |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | <p>I am a python newbie trying to achieve the following:</p>
<p>I have a list of lists:</p>
<pre><code>lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
</code></pre>
<p>I want map lst into another list containing only the second smallest number from each sublist. So the result should be:</p>
<pre><code>[345, 465, 333]
</code></pre>
<p>For example if I were just interested in the smallest number, I could do:</p>
<pre><code>map(lambda x: min(x),lst)
</code></pre>
<p>I wish I could do this:</p>
<pre><code>map(lambda x: sort(x)[1],lst)
</code></pre>
<p>but sort does not chain. (returns None)</p>
<p>neither is something like this allowed:</p>
<pre><code>map(lambda x: sort(x); x[1],lst) #hence the multiple statement question
</code></pre>
<p>Is there a way to do this with map in python but <em>without defining a named function</em>? (it is easy with anonymous blocks in ruby, for example)</p>
| 45 | 2009-05-14T09:31:34Z | 18,696,789 | <p>You can do it in O(n) time using min and index instead of using sort or heapq.</p>
<p>First create new list of everything except the min value of the original list:</p>
<pre><code>new_list = lst[:lst.index(min(lst))] + lst[lst.index(min(lst))+1:]
</code></pre>
<p>Then take the min value of the new list:</p>
<pre><code>second_smallest = min(new_list)
</code></pre>
<p>Now all together in a single lambda:</p>
<pre><code>map(lambda x: min(x[:x.index(min(x))] + x[x.index(min(x))+1:]), lst)
</code></pre>
<p>Yes it is really ugly, but it should be algorithmically cheap. Also since some folks in this thread want to see list comprehensions:</p>
<pre><code>[min(x[:x.index(min(x))] + x[x.index(min(x))+1:]) for x in lst]
</code></pre>
| 1 | 2013-09-09T11:03:17Z | [
"python"
] |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | <p>I am a python newbie trying to achieve the following:</p>
<p>I have a list of lists:</p>
<pre><code>lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
</code></pre>
<p>I want map lst into another list containing only the second smallest number from each sublist. So the result should be:</p>
<pre><code>[345, 465, 333]
</code></pre>
<p>For example if I were just interested in the smallest number, I could do:</p>
<pre><code>map(lambda x: min(x),lst)
</code></pre>
<p>I wish I could do this:</p>
<pre><code>map(lambda x: sort(x)[1],lst)
</code></pre>
<p>but sort does not chain. (returns None)</p>
<p>neither is something like this allowed:</p>
<pre><code>map(lambda x: sort(x); x[1],lst) #hence the multiple statement question
</code></pre>
<p>Is there a way to do this with map in python but <em>without defining a named function</em>? (it is easy with anonymous blocks in ruby, for example)</p>
| 45 | 2009-05-14T09:31:34Z | 33,296,719 | <p>This is exactly what the <code>bind</code> function in a <a href="http://www.dustingetz.com/2012/04/07/dustins-awesome-monad-tutorial-for-humans-in-python.html" rel="nofollow">Monad</a> is used for. </p>
<p>With the <code>bind</code> function you can combine multiple lambda's into one lambda, each lambda representing a statement. </p>
| 1 | 2015-10-23T07:13:45Z | [
"python"
] |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | <p>I am a python newbie trying to achieve the following:</p>
<p>I have a list of lists:</p>
<pre><code>lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
</code></pre>
<p>I want map lst into another list containing only the second smallest number from each sublist. So the result should be:</p>
<pre><code>[345, 465, 333]
</code></pre>
<p>For example if I were just interested in the smallest number, I could do:</p>
<pre><code>map(lambda x: min(x),lst)
</code></pre>
<p>I wish I could do this:</p>
<pre><code>map(lambda x: sort(x)[1],lst)
</code></pre>
<p>but sort does not chain. (returns None)</p>
<p>neither is something like this allowed:</p>
<pre><code>map(lambda x: sort(x); x[1],lst) #hence the multiple statement question
</code></pre>
<p>Is there a way to do this with map in python but <em>without defining a named function</em>? (it is easy with anonymous blocks in ruby, for example)</p>
| 45 | 2009-05-14T09:31:34Z | 40,133,069 | <p>You can in fact have multiple statements in a lambda expression in python. It is not entirely trivial but in your example, the following works:</p>
<pre><code>map(lambda x: x.sort() or x[1],lst)
</code></pre>
<p>You have to make sure that each statement does not return anything or if it does wrap it in (.. and False). The result is what is returned by the last evaluation.</p>
<p>Example: </p>
<pre><code>>>> f = (lambda : (print(1) and False) or (print(2) and False) or (print(3) and False))
>>> f()
1
2
3
</code></pre>
| 0 | 2016-10-19T13:40:44Z | [
"python"
] |
Extracting bitmap from a file | 862,487 | <p><br />
given a somewhat complex file of unknown specification that among other things contains an uncompressed bitmap file (.BMP), how would you extract it in Python?<br />
Scan for the "BM" tag and see if the following bytes "resemble" a BMP header?</p>
| 2 | 2009-05-14T09:50:43Z | 862,493 | <p>I'd use the <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library</a> PIL and have it a go at the data. If it can parse it, then it's a valid image. When it throws an exception, then it isn't.</p>
<p>You need to search for the begining of the image; if you're lucky, the image reader will ignore garbage after the image data. When it doesn't, use a binary search to locate the end of the image.</p>
| 4 | 2009-05-14T09:53:26Z | [
"python",
"heuristics"
] |
Extracting bitmap from a file | 862,487 | <p><br />
given a somewhat complex file of unknown specification that among other things contains an uncompressed bitmap file (.BMP), how would you extract it in Python?<br />
Scan for the "BM" tag and see if the following bytes "resemble" a BMP header?</p>
| 2 | 2009-05-14T09:50:43Z | 862,588 | <p>Yes, about the only thing you can do is search through the file for the 'BM' marker, pull out the following data into a <a href="http://msdn.microsoft.com/en-us/library/dd183374%28VS.85%29.aspx" rel="nofollow">BITMAPFILEHEADER</a> and corresponding BITMAPINFO, and see if the values in it look valid (i.e. that the dimensions are sensible, colour depth is reasonable, etc).</p>
<p>Once you have found something that looks reasonable, pull that data out and pass it to the library mentioned in another answer.</p>
| 4 | 2009-05-14T10:19:51Z | [
"python",
"heuristics"
] |
Pointers in Python on variables with None value | 862,652 | <p>I have a method that creates a new node in a tree - either left or right. If the value is lower than my current value it is inserted on the left, otherwise on the right side.</p>
<p>I want to refactor this code, so that I first see on which side I have to insert my element, and then insert it. Before I implemented this twice: Once for the left side and once for the right side.</p>
<p>It currently looks like this:</p>
<pre><code>def neu(self, sortByValue, secondValue):
child = self.left if(sortByValue.lower() < self.value[0].lower()) else self.right
if(child == None):
child = MyTree(sortByValue,secondValue)
else: child.neu(sortByValue,secondValue)
</code></pre>
<p>My problem is, though, that self.left is None, and self.right is None. So when I create child as a variable and set it to MyTree(...), self.left and self.right are not receiving the value.</p>
<p>Is there anything I can do to improve this? Thanks!</p>
| 0 | 2009-05-14T10:42:40Z | 862,714 | <p>In Python variables are names not locations. For example:</p>
<pre><code>>>> a = 1
>>> b = a
>>> a = 2
>>> print b
1
</code></pre>
<p>In your code you're simply rebinding the name <code>child</code> to a different value (your new node) and that has no affect on the previously bound value (None).</p>
<p>Here's a reworking of your code that should do what you want (untested):</p>
<pre><code>def neu(self, sortByValue, secondValue):
def child(node):
if(node is None):
return MyTree(sortByValue, secondValue)
else:
child.neu(sortByValue, secondValue)
return node
if(sortByValue.lower() < self.value[0].lower()):
self.left = child(self.left)
else:
self.right = child(self.right)
</code></pre>
| 2 | 2009-05-14T10:59:14Z | [
"python",
"reference"
] |
Pointers in Python on variables with None value | 862,652 | <p>I have a method that creates a new node in a tree - either left or right. If the value is lower than my current value it is inserted on the left, otherwise on the right side.</p>
<p>I want to refactor this code, so that I first see on which side I have to insert my element, and then insert it. Before I implemented this twice: Once for the left side and once for the right side.</p>
<p>It currently looks like this:</p>
<pre><code>def neu(self, sortByValue, secondValue):
child = self.left if(sortByValue.lower() < self.value[0].lower()) else self.right
if(child == None):
child = MyTree(sortByValue,secondValue)
else: child.neu(sortByValue,secondValue)
</code></pre>
<p>My problem is, though, that self.left is None, and self.right is None. So when I create child as a variable and set it to MyTree(...), self.left and self.right are not receiving the value.</p>
<p>Is there anything I can do to improve this? Thanks!</p>
| 0 | 2009-05-14T10:42:40Z | 862,724 | <p>Hallo ;-)</p>
<p><code>self.left</code> or <code>self.right</code> don't receive the value because you assign to <code>child</code> which just holds a copy of the destination value and no reference to it.</p>
<p>You want to have a pointer- This doesn't exist directly in Python.</p>
<p>You could express this using a class wrapper, but I think it's more comprehensible when you just write both possibilities in the if clause.</p>
| 0 | 2009-05-14T11:01:27Z | [
"python",
"reference"
] |
Pointers in Python on variables with None value | 862,652 | <p>I have a method that creates a new node in a tree - either left or right. If the value is lower than my current value it is inserted on the left, otherwise on the right side.</p>
<p>I want to refactor this code, so that I first see on which side I have to insert my element, and then insert it. Before I implemented this twice: Once for the left side and once for the right side.</p>
<p>It currently looks like this:</p>
<pre><code>def neu(self, sortByValue, secondValue):
child = self.left if(sortByValue.lower() < self.value[0].lower()) else self.right
if(child == None):
child = MyTree(sortByValue,secondValue)
else: child.neu(sortByValue,secondValue)
</code></pre>
<p>My problem is, though, that self.left is None, and self.right is None. So when I create child as a variable and set it to MyTree(...), self.left and self.right are not receiving the value.</p>
<p>Is there anything I can do to improve this? Thanks!</p>
| 0 | 2009-05-14T10:42:40Z | 862,740 | <p>Why are you using a tree?</p>
<p>I would use a dictionary:</p>
<p>Initialization:</p>
<blockquote>
<p>tree = {}</p>
</blockquote>
<p>Adding new node:</p>
<blockquote>
<p>tree[sortByValue] = secondValue</p>
</blockquote>
<p>Extracting things</p>
<blockquote>
<p>print tree[sortByValue]</p>
</blockquote>
<p>Not the straight answer but a more pythonic way of doing it</p>
| 0 | 2009-05-14T11:04:23Z | [
"python",
"reference"
] |
How would you write a @debuggable decorator in python? | 862,807 | <p>When debugging, I like to print out all the inputs and outputs of a function (I know I need a better IDE, but humour me, this could be used for error reporting). So, I'd ideally like to have:</p>
<pre><code>@debuggable
def myfunc(argA,argB,argC):
return argB+1
</code></pre>
<p>and use a global variable to switch on or off debugging. No, you don't like globals either, I guessed.</p>
<p>The best I can come up with is:</p>
<pre><code>DEBUG = True
def debuggable(func):
if DEBUG:
def decorated(*args):
print "Entering ",func.func_name
print " args ",args
ret = func(*args)
print ret
return ret
return decorated
else:
return func
@debuggable
def myfunc(this,that):
return this+that
</code></pre>
<p>And running:</p>
<pre><code>>>> myfunc(1,3)
Entering myfunc
args (1, 3)
4
</code></pre>
<p>How can I improve that?</p>
| 7 | 2009-05-14T11:26:37Z | 862,899 | <p>Use a debugger. Seriously. Decorating every function you want to keep track is a bad idea.</p>
<p>Python <a href="http://docs.python.org/library/pdb.html">has a debugger included</a>, so you don't need a good IDE.</p>
<p>If you don't want to use a debugger, you can use the <a href="http://docs.python.org/library/sys.html#sys.settrace">trace function</a>.</p>
<pre><code>import sys
@sys.settrace
def trace_debug(frame, event, arg):
if event == 'call':
print ("calling %r on line %d, vars: %r" %
(frame.f_code.co_name,
frame.f_lineno,
frame.f_locals))
return trace_debug
elif event == "return":
print "returning", arg
def fun1(a, b):
return a + b
print fun1(1, 2)
</code></pre>
<p>That prints:</p>
<pre><code>calling 'fun1' on line 14, vars: {'a': 1, 'b': 2}
returning 3
3
</code></pre>
<p>Even easier would be to use <a href="http://winpdb.org/">Winpdb</a>:</p>
<p>It is a <strong>platform independent</strong> graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.</p>
<p>Features:</p>
<ul>
<li>GPL license. Winpdb is Free Software.</li>
<li>Compatible with CPython 2.3 or later.</li>
<li>Compatible with wxPython 2.6 or later.</li>
<li>Platform independent, and tested on Ubuntu Gutsy and Windows XP.</li>
<li>User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.</li>
</ul>
<p><img src="http://winpdb.org/images/screenshot_winpdb_small.jpg" alt="Screenshot"></p>
| 19 | 2009-05-14T11:52:07Z | [
"python",
"decorator"
] |
How would you write a @debuggable decorator in python? | 862,807 | <p>When debugging, I like to print out all the inputs and outputs of a function (I know I need a better IDE, but humour me, this could be used for error reporting). So, I'd ideally like to have:</p>
<pre><code>@debuggable
def myfunc(argA,argB,argC):
return argB+1
</code></pre>
<p>and use a global variable to switch on or off debugging. No, you don't like globals either, I guessed.</p>
<p>The best I can come up with is:</p>
<pre><code>DEBUG = True
def debuggable(func):
if DEBUG:
def decorated(*args):
print "Entering ",func.func_name
print " args ",args
ret = func(*args)
print ret
return ret
return decorated
else:
return func
@debuggable
def myfunc(this,that):
return this+that
</code></pre>
<p>And running:</p>
<pre><code>>>> myfunc(1,3)
Entering myfunc
args (1, 3)
4
</code></pre>
<p>How can I improve that?</p>
| 7 | 2009-05-14T11:26:37Z | 862,915 | <p>I agree with nosklo using a debugger is much better than writing your own. I'll post an improvement to your code. But I still think you should follow nosklo's advice.</p>
<p>Use decorator classes to make your debugger neater:</p>
<pre><code>class Debugger(object):
enabled = False
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
if self.enabled:
print 'Entering', self.func.func_name
print ' args:', args, kwargs
return self.func(*args, **kwargs)
Debugger.enabled = True
@Debugger
def myfunc(a, b, c, d):
pass
</code></pre>
| 4 | 2009-05-14T11:56:27Z | [
"python",
"decorator"
] |
How would you write a @debuggable decorator in python? | 862,807 | <p>When debugging, I like to print out all the inputs and outputs of a function (I know I need a better IDE, but humour me, this could be used for error reporting). So, I'd ideally like to have:</p>
<pre><code>@debuggable
def myfunc(argA,argB,argC):
return argB+1
</code></pre>
<p>and use a global variable to switch on or off debugging. No, you don't like globals either, I guessed.</p>
<p>The best I can come up with is:</p>
<pre><code>DEBUG = True
def debuggable(func):
if DEBUG:
def decorated(*args):
print "Entering ",func.func_name
print " args ",args
ret = func(*args)
print ret
return ret
return decorated
else:
return func
@debuggable
def myfunc(this,that):
return this+that
</code></pre>
<p>And running:</p>
<pre><code>>>> myfunc(1,3)
Entering myfunc
args (1, 3)
4
</code></pre>
<p>How can I improve that?</p>
| 7 | 2009-05-14T11:26:37Z | 862,963 | <p>I second what nosklo said.</p>
<p>Another thing to notice is that your function is a bit dangerous:</p>
<pre><code>b = myfunc(1,3)
</code></pre>
<p>In this case, "b" is <code>None</code>, because the decorated function doesn't return anything.</p>
| 0 | 2009-05-14T12:09:28Z | [
"python",
"decorator"
] |
How would you write a @debuggable decorator in python? | 862,807 | <p>When debugging, I like to print out all the inputs and outputs of a function (I know I need a better IDE, but humour me, this could be used for error reporting). So, I'd ideally like to have:</p>
<pre><code>@debuggable
def myfunc(argA,argB,argC):
return argB+1
</code></pre>
<p>and use a global variable to switch on or off debugging. No, you don't like globals either, I guessed.</p>
<p>The best I can come up with is:</p>
<pre><code>DEBUG = True
def debuggable(func):
if DEBUG:
def decorated(*args):
print "Entering ",func.func_name
print " args ",args
ret = func(*args)
print ret
return ret
return decorated
else:
return func
@debuggable
def myfunc(this,that):
return this+that
</code></pre>
<p>And running:</p>
<pre><code>>>> myfunc(1,3)
Entering myfunc
args (1, 3)
4
</code></pre>
<p>How can I improve that?</p>
| 7 | 2009-05-14T11:26:37Z | 863,036 | <p>I think what you're after isn't really a debugging decorator, but more of a logging decorator.</p>
<p>It might make sense to use <a href="http://docs.python.org/library/logging.html">Python's logging module</a> so you can have more fine grained control over the logging itself. For example you would be able to output to a file for later analysing the output.</p>
<p>The decorator might then look something more like:</p>
<pre>
<code>
import logging
logger = logging.getLogger('TraceLog')
# TODO configure logger to write to file/stdout etc, it's level etc
def logthis(level):
def _decorator(fn):
def _decorated(*arg,**kwargs):
logger.log(level, "calling '%s'(%r,%r)", fn.func_name, arg, kwargs)
ret=fn(*arg,**kwargs)
logger.log(level, "called '%s'(%r,%r) got return value: %r", fn.func_name, arg, kwargs, ret)
return ret
return _decorated
return _decorator
@logthis(logging.INFO)
def myfunc(this,that):
return this+that
</code>
</pre>
<p>Then if you configure the logger to output to stderr you'd see:</p>
<pre>
<code>
>>> logger.setLevel(logging.INFO)
>>> handler=logging.StreamHandler()
>>> logger.addHandler(handler)
>>> myfunc(1,2)
calling 'myfunc'((1, 2),{})
called 'myfunc'((1, 2),{}) got return value: 3
</code>
</pre>
| 6 | 2009-05-14T12:27:37Z | [
"python",
"decorator"
] |
How would you write a @debuggable decorator in python? | 862,807 | <p>When debugging, I like to print out all the inputs and outputs of a function (I know I need a better IDE, but humour me, this could be used for error reporting). So, I'd ideally like to have:</p>
<pre><code>@debuggable
def myfunc(argA,argB,argC):
return argB+1
</code></pre>
<p>and use a global variable to switch on or off debugging. No, you don't like globals either, I guessed.</p>
<p>The best I can come up with is:</p>
<pre><code>DEBUG = True
def debuggable(func):
if DEBUG:
def decorated(*args):
print "Entering ",func.func_name
print " args ",args
ret = func(*args)
print ret
return ret
return decorated
else:
return func
@debuggable
def myfunc(this,that):
return this+that
</code></pre>
<p>And running:</p>
<pre><code>>>> myfunc(1,3)
Entering myfunc
args (1, 3)
4
</code></pre>
<p>How can I improve that?</p>
| 7 | 2009-05-14T11:26:37Z | 864,558 | <p>There's a fairly long blog post on the subject of tracing decorators at <a href="http://wordaligned.org/articles/echo" rel="nofollow">Word Aligned</a>.</p>
| 1 | 2009-05-14T17:08:04Z | [
"python",
"decorator"
] |
url method of ImageField returns a non-Url value - Django | 862,860 | <p>I'm developing using Django on Windows. I have a model with an imagefield, and use a form to fill it. Images get uploaded without problem. The problem occurs when I attempt to show an uploaded image inside a template by coding this:</p>
<pre><code><img src ='{{object.image.url}}'/>
</code></pre>
<p>(object is an instance of the relevant model, and image is the name of the image field)</p>
<p>However, the image is not displayed, as the url method returns not a URL but a path like this:</p>
<p>c:/pp/pm/static/image/xyz.png</p>
<p>What should I do to make it a real URL?</p>
<p>edit: </p>
<p>MEDIA_ROOT and MEDIA_URL settings are below:</p>
<pre><code>MEDIA_ROOT = 'C:/pp/pm/static/'
MEDIA_URL = '/static/'
</code></pre>
| 1 | 2009-05-14T11:40:47Z | 6,240,232 | <p>I had the same problem. At model declaration, I changed "upload_to" argument value from absolute path to relative, this fixes the problem.</p>
| 2 | 2011-06-05T00:25:10Z | [
"python",
"django",
"url",
"django-models"
] |
Python: adding namespaces in lxml | 863,183 | <p>I'm trying to specify a namespace using <em>lxml</em> similar to this example (taken from <a href="http://www.maconstateit.net/tutorials/XML/XML03/xml03-01.htm" rel="nofollow">here</a>):</p>
<pre class="lang-xml prettyprint-override"><code><TreeInventory xsi:noNamespaceSchemaLocation="Trees.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</TreeInventory>
</code></pre>
<p>I'm not sure how to add the Schema instance to use and also the Schema location.
The <a href="http://codespeak.net/lxml/tutorial.html#namespaces" rel="nofollow">documentation</a> got me started, by doing something like:</p>
<pre class="lang-py prettyprint-override"><code>>>> NS = 'http://www.w3.org/2001/XMLSchema-instance'
>>> TREE = '{%s}' % NS
>>> NSMAP = {None: NS}
>>> tree = etree.Element(TREE + 'TreeInventory', nsmap=NSMAP)
>>> etree.tostring(tree, pretty_print=True)
'<TreeInventory xmlns="http://www.w3.org/2001/XMLSchema-instance"/>\n'
</code></pre>
<p>I'm not sure how to specify it an instance though, and then also specify a location. It seems like this can be done with the <code>nsmap</code> keyword-arg in <code>etree.Element</code>, but I don't see how.</p>
| 6 | 2009-05-14T12:58:32Z | 863,834 | <p>In some more steps, for clarity:</p>
<pre><code>>>> NS = 'http://www.w3.org/2001/XMLSchema-instance'
</code></pre>
<p>As far as I can see, it is the attribute <code>noNameSpaceSchemaLocation</code> that you want namespaced, not the <code>TreeInventory</code> element. So:</p>
<pre><code>>>> location_attribute = '{%s}noNameSpaceSchemaLocation' % NS
>>> elem = etree.Element('TreeInventory', attrib={location_attribute: 'Trees.xsd'})
>>> etree.tostring(elem, pretty_print=True)
'<TreeInventory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Trees.xsd"/>\n'
</code></pre>
<p>This looks like what you wanted...
You could of course also create the element first, without attributes, and then set the attribute, like this:</p>
<pre><code>>>> elem = etree.Element('TreeInventory')
>>> elem.set(location_attribute, 'Trees.xsd')
</code></pre>
<p>As for the <code>nsmap</code> parameter: I believe it is only used to define which prefixes to use on serialization. In this case, it is not needed, because lxml knows the commonly used prefix for the namespace in question is "xsi". If it were not some well-known namespace, you would probably see prefixes like "ns0", "ns1" etc..., unless you specified which prefix you preferred. (remember: the prefix is not supposed to matter)</p>
| 8 | 2009-05-14T14:59:28Z | [
"python",
"lxml",
"xml-namespaces"
] |
Python Module by Path | 863,234 | <p>I am writing a minimal replacement for mod_python's publisher.py</p>
<p>The basic premise is that it is loading modules based on a URL scheme:</p>
<pre><code>/foo/bar/a/b/c/d
</code></pre>
<p>Whereby /foo/ might be a directory and 'bar' is a method ExposedBar in a publishable class in /foo/index.py. Likewise /foo might map to /foo.py and bar is a method in the exposed class. The semantics of this aren't really important. I have a line:</p>
<pre><code>sys.path.insert(0, path_to_file) # /var/www/html/{bar|foo}
mod_obj = __import__(module_name)
mod_obj.__name__ = req.filename
</code></pre>
<p>Then the module is inspected for the appropriate class/functions/methods. When the process gets as far as it can the remaining URI data, /a/b/c is passed to that method or function.</p>
<p>This was working fine until I had /var/www/html/foo/index.py and /var/www/html/bar/index.py</p>
<p>When viewing in the browser, it is fairly random which 'index.py' gets selected, even though I set the first search path to '/var/www/html/foo' or '/var/www/html/bar' and then loaded __import__('index'). I have no idea why it is finding either by seemingly random choice. This is shown by:</p>
<pre><code>__name__ is "/var/www/html/foo/index.py"
req.filename is "/var/www/html/foo/index.py"
__file__ is "/var/www/html/bar/index.py"
</code></pre>
<p>This question then is, why would the __import__ be randomly selecting either index. I would understand this if the path was '/var/www/html' but it isn't. Secondly:</p>
<p>Can I load a module by it's absolute path into a module object? Without modification of sys.path. I can't find any docs on __import__ or new.module() for this.</p>
| 1 | 2009-05-14T13:07:27Z | 863,324 | <blockquote>
<p>Can I load a module by it's absolute
path into a module object? Without
modification of sys.path. I can't find
any docs on <code>__import__</code> or new.module()
for this.</p>
</blockquote>
<pre><code>import imp
import os
def module_from_path(path):
filename = os.path.basename(path)
modulename = os.path.splitext(filename)[0]
with open(path) as f:
return imp.load_module(modulename, f, path, ('py', 'U', imp.PY_SOURCE))
</code></pre>
| 2 | 2009-05-14T13:23:56Z | [
"python",
"mod-python"
] |
Python and Collective Intelligence | 863,253 | <p>I'm currently reading a great book called 'Programming Collective Intelligence' by Toby Segaran (which i highly recommend)</p>
<p>The code examples are all written in Python, and as I have already learnt one new language this year (graduating from VB.net to C#) i'm not keen to jump on another learning curve.</p>
<p>This leaves my with the issue of translating the python examples into C#. </p>
<p>Question is: How critical is it that the code stay in python? Are there thing in python that I can't do in a normal managed statically typed language?</p>
| 1 | 2009-05-14T13:11:53Z | 863,292 | <p>One challenge you'll find is that not only are the algorithms implemented in Python, but the book makes extensive use of Python libraries like BeautifulSoup, Numpy, PIL, and others (see appendix A).</p>
<p>I doubt there are any specifics of the algorithms that you couldn't port to another language, but you'll have trouble working through the exercises. Also, to translate the code, you'll have to learn Python at least a little bit, no? </p>
<p>I suggest you just dive in and learn Python. You can use IronPython if you have any concern about interoperability with your C# projects.</p>
| 19 | 2009-05-14T13:18:10Z | [
"python",
"collective-intelligence"
] |
Python and Collective Intelligence | 863,253 | <p>I'm currently reading a great book called 'Programming Collective Intelligence' by Toby Segaran (which i highly recommend)</p>
<p>The code examples are all written in Python, and as I have already learnt one new language this year (graduating from VB.net to C#) i'm not keen to jump on another learning curve.</p>
<p>This leaves my with the issue of translating the python examples into C#. </p>
<p>Question is: How critical is it that the code stay in python? Are there thing in python that I can't do in a normal managed statically typed language?</p>
| 1 | 2009-05-14T13:11:53Z | 863,328 | <p>Obligatory XKCD: <a href="http://xkcd.com/353/" rel="nofollow">http://xkcd.com/353/</a></p>
<p>I know you explicitly say you don't want to learn Python (this year), but translating the Python examples to C# will definitely be a much steeper curve. Just <a href="http://www.diveintopython.org/" rel="nofollow">dive in!</a></p>
| 1 | 2009-05-14T13:24:33Z | [
"python",
"collective-intelligence"
] |
Python and Collective Intelligence | 863,253 | <p>I'm currently reading a great book called 'Programming Collective Intelligence' by Toby Segaran (which i highly recommend)</p>
<p>The code examples are all written in Python, and as I have already learnt one new language this year (graduating from VB.net to C#) i'm not keen to jump on another learning curve.</p>
<p>This leaves my with the issue of translating the python examples into C#. </p>
<p>Question is: How critical is it that the code stay in python? Are there thing in python that I can't do in a normal managed statically typed language?</p>
| 1 | 2009-05-14T13:11:53Z | 863,331 | <p>You can do the same things in all Turing-complete languages. <a href="http://thedailywtf.com/articles/stupid-coding-tricks-the-tsql-madlebrot.aspx" rel="nofollow">Here is an example</a> for rendering a Mandelbrot fractal in SQL. The example shows: Even if you can use any language, the effort will be different.</p>
<p>So my guess is that the code will become much longer since Python is so flexible and open.</p>
| 2 | 2009-05-14T13:24:45Z | [
"python",
"collective-intelligence"
] |
Python and Collective Intelligence | 863,253 | <p>I'm currently reading a great book called 'Programming Collective Intelligence' by Toby Segaran (which i highly recommend)</p>
<p>The code examples are all written in Python, and as I have already learnt one new language this year (graduating from VB.net to C#) i'm not keen to jump on another learning curve.</p>
<p>This leaves my with the issue of translating the python examples into C#. </p>
<p>Question is: How critical is it that the code stay in python? Are there thing in python that I can't do in a normal managed statically typed language?</p>
| 1 | 2009-05-14T13:11:53Z | 863,568 | <p>The book is about algorithms, not the details of programming, and the language of choice is just to make the examples concrete. As the author says, "The code examples in this book are written in Python... but I provide explanations of all the algorithms so that programmers of other languages can follow." (p. xv)</p>
<p>Python is a great language and easy to learn, but I suspect the difficulties in applying ideas from the book will not be in the translating of the code to another language or set of libraries, but in understanding the ideas and modifying the code to suite your needs. I think there are two main reasons to stay with a language you're familiar with: 1) when your code doesn't work, if you're writing in an unfamiliar language, you won't know where to start looking for errors, e.g. if you're like most people you'll even start wondering if it's due to a bug in Python, which it won't be, but you'll wonder and it will distract. 2) There are just natural limits to how much you can remember in a certain length of time; and learning a language at the same time will give you twice as much to remember.</p>
<p>It depends though how well you know C#, and what you lose by leaving it.</p>
| 1 | 2009-05-14T14:14:51Z | [
"python",
"collective-intelligence"
] |
Python and Collective Intelligence | 863,253 | <p>I'm currently reading a great book called 'Programming Collective Intelligence' by Toby Segaran (which i highly recommend)</p>
<p>The code examples are all written in Python, and as I have already learnt one new language this year (graduating from VB.net to C#) i'm not keen to jump on another learning curve.</p>
<p>This leaves my with the issue of translating the python examples into C#. </p>
<p>Question is: How critical is it that the code stay in python? Are there thing in python that I can't do in a normal managed statically typed language?</p>
| 1 | 2009-05-14T13:11:53Z | 863,626 | <p>Python seems to be to AI programming what LISP was for for many decades. Russel/Norvig's famous book <a href="http://aima.cs.berkeley.edu/" rel="nofollow">AI: A Modern Approach</a> also provides lots of <a href="http://aima.cs.berkeley.edu/python/readme.html" rel="nofollow">examples in Python</a>.</p>
| 0 | 2009-05-14T14:23:12Z | [
"python",
"collective-intelligence"
] |
Python and Collective Intelligence | 863,253 | <p>I'm currently reading a great book called 'Programming Collective Intelligence' by Toby Segaran (which i highly recommend)</p>
<p>The code examples are all written in Python, and as I have already learnt one new language this year (graduating from VB.net to C#) i'm not keen to jump on another learning curve.</p>
<p>This leaves my with the issue of translating the python examples into C#. </p>
<p>Question is: How critical is it that the code stay in python? Are there thing in python that I can't do in a normal managed statically typed language?</p>
| 1 | 2009-05-14T13:11:53Z | 986,107 | <p>I suggest translating them to C#. I have been porting chapter 2 "Recommendations" to VB.Net. Along the way I'm learning Python as a side-effect. Toby does some amazing things with Python lists.</p>
<p>Dealing with the the extra Python libraries is another story. Ndelicious is a close match to pyDelicious, but it is missing a few key features (popular posts!).</p>
| 2 | 2009-06-12T11:04:40Z | [
"python",
"collective-intelligence"
] |
Which PEP governs the ordering of dict.values()? | 863,446 | <p>When you call dict.values() the order of the returned items is dependent on the has value of the keys. This seems to be very consistent in all versions of cPython, however the python manual for dict <a href="http://docs.python.org/library/stdtypes.html#dict.items" rel="nofollow">simply states that the ordering is "arbitrary"</a>.</p>
<p>I remember reading somewhere that there is actually a PEP which specifically states the expected ordering of the items() and values() methods. </p>
<p>FYI, if this behavior is indeed a guaranteed behavior of a class I am working on I could greatly simplify and speed up a class I am working on. On the other hand if this is merely an accidental and undocumented feature of cPython then it's probably best not to trust it. </p>
| 1 | 2009-05-14T13:53:06Z | 863,464 | <p>From <a href="http://docs.python.org/library/stdtypes.html" rel="nofollow">http://docs.python.org/library/stdtypes.html</a>:</p>
<blockquote>
<p>Keys and values are listed in an
arbitrary order which is non-random,
varies across Python implementations,
and depends on the dictionaryâs
history of insertions and deletions.</p>
</blockquote>
| 7 | 2009-05-14T13:56:48Z | [
"python",
"dictionary"
] |
Which PEP governs the ordering of dict.values()? | 863,446 | <p>When you call dict.values() the order of the returned items is dependent on the has value of the keys. This seems to be very consistent in all versions of cPython, however the python manual for dict <a href="http://docs.python.org/library/stdtypes.html#dict.items" rel="nofollow">simply states that the ordering is "arbitrary"</a>.</p>
<p>I remember reading somewhere that there is actually a PEP which specifically states the expected ordering of the items() and values() methods. </p>
<p>FYI, if this behavior is indeed a guaranteed behavior of a class I am working on I could greatly simplify and speed up a class I am working on. On the other hand if this is merely an accidental and undocumented feature of cPython then it's probably best not to trust it. </p>
| 1 | 2009-05-14T13:53:06Z | 863,488 | <p>"arbitrary" is not the same as "accidental". </p>
<p>But it is the same as "undocumented". Since the dictionary is based on hashes, you can't -- really -- guarantee ordering based on the hashing algorithm and collisions which occur.</p>
<p>To guarantee an order, you use the <code>sorted</code> function. </p>
<p>Or you can find a good <a href="http://code.activestate.com/recipes/107747/" rel="nofollow">ordered dictionary</a> implementation that you want to use instead of a dict.</p>
| 2 | 2009-05-14T13:59:32Z | [
"python",
"dictionary"
] |
Which PEP governs the ordering of dict.values()? | 863,446 | <p>When you call dict.values() the order of the returned items is dependent on the has value of the keys. This seems to be very consistent in all versions of cPython, however the python manual for dict <a href="http://docs.python.org/library/stdtypes.html#dict.items" rel="nofollow">simply states that the ordering is "arbitrary"</a>.</p>
<p>I remember reading somewhere that there is actually a PEP which specifically states the expected ordering of the items() and values() methods. </p>
<p>FYI, if this behavior is indeed a guaranteed behavior of a class I am working on I could greatly simplify and speed up a class I am working on. On the other hand if this is merely an accidental and undocumented feature of cPython then it's probably best not to trust it. </p>
| 1 | 2009-05-14T13:53:06Z | 863,494 | <p>I suppose <a href="http://www.python.org/dev/peps/pep-3106/" rel="nofollow">PEP-3106</a> is as close as it gets:</p>
<blockquote>
<p>The specification implies that the order in which items are returned by
.keys(), .values() and .items() is the
same (just as it was in Python 2.x),
because the order is all derived from
the dict iterator (which is presumably
arbitrary but stable as long as a dict
isn't modified). This can be expressed
by the following invariant:</p>
<p><code>list(d.items()) == list(zip(d.keys(),
d.values()))</code></p>
</blockquote>
| 6 | 2009-05-14T14:00:30Z | [
"python",
"dictionary"
] |
How to generate XML documents with namespaces in Python | 863,774 | <p>I'm trying to generate an XML document with namespaces, currently with Python's xml.dom.minidom:</p>
<pre><code>import xml.dom.minidom
doc = xml.dom.minidom.Document()
el = doc.createElementNS('http://example.net/ns', 'el')
doc.appendChild(el)
print(doc.toprettyxml())
</code></pre>
<p>The namespace is saved (<code>doc.childNodes[0].namespaceURI</code> is <code>'<a href="http://example.net/ns">http://example.net/ns</a>'</code>), but why is it missing in the output?</p>
<pre><code><?xml version="1.0" ?>
<el/>
</code></pre>
<p>I expect:</p>
<pre><code><?xml version="1.0" ?>
<el xmlns="http://example.net/ns" />
</code></pre>
<p>or</p>
<pre><code><?xml version="1.0" ?>
<randomid:el xmlns:randomid="http://example.net/ns" />
</code></pre>
| 22 | 2009-05-14T14:51:01Z | 864,030 | <p><code>createElementNS()</code> is defined as:</p>
<pre class="lang-py prettyprint-override"><code>def createElementNS(self, namespaceURI, qualifiedName):
prefix, localName = _nssplit(qualifiedName)
e = Element(qualifiedName, namespaceURI, prefix)
e.ownerDocument = self
return e
</code></pre>
<p>soâ¦</p>
<pre class="lang-py prettyprint-override"><code>import xml.dom.minidom
doc = xml.dom.minidom.Document()
el = doc.createElementNS('http://example.net/ns', 'ex:el')
#--------------------------------------------------^^^^^
doc.appendChild(el)
print(doc.toprettyxml())
</code></pre>
<p>yields:</p>
<pre><code><?xml version="1.0" ?>
<ex:el/>
</code></pre>
<p>â¦not quite thereâ¦</p>
<pre class="lang-py prettyprint-override"><code>import xml.dom.minidom
doc = xml.dom.minidom.Document()
el = doc.createElementNS('http://example.net/ns', 'ex:el')
el.setAttribute("xmlns:ex", "http://example.net/ns")
doc.appendChild(el)
print(doc.toprettyxml())
</code></pre>
<p>yields:</p>
<pre><code><?xml version="1.0" ?>
<ex:el xmlns:ex="http://example.net/ns"/>
</code></pre>
<p>alternatively:</p>
<pre class="lang-py prettyprint-override"><code>import xml.dom.minidom
doc = xml.dom.minidom.Document()
el = doc.createElementNS('http://example.net/ns', 'el')
el.setAttribute("xmlns", "http://example.net/ns")
doc.appendChild(el)
print(doc.toprettyxml())
</code></pre>
<p>wich produces:</p>
<pre><code><?xml version="1.0" ?>
<el xmlns="http://example.net/ns"/>
</code></pre>
<p>It looks like you'd have to do it manually. <code>Element.writexml()</code> shows no indication that namespaces would get any special treatment.</p>
<p>EDIT: This answer is targeted at <code>xml.dom.minidom</code> only, since the OP used it in the question. I do not indicate that it was impossible to use XML namespaces in Python generally. ;-)</p>
| 19 | 2009-05-14T15:26:47Z | [
"python",
"xml",
"dom",
"namespaces"
] |
How to generate XML documents with namespaces in Python | 863,774 | <p>I'm trying to generate an XML document with namespaces, currently with Python's xml.dom.minidom:</p>
<pre><code>import xml.dom.minidom
doc = xml.dom.minidom.Document()
el = doc.createElementNS('http://example.net/ns', 'el')
doc.appendChild(el)
print(doc.toprettyxml())
</code></pre>
<p>The namespace is saved (<code>doc.childNodes[0].namespaceURI</code> is <code>'<a href="http://example.net/ns">http://example.net/ns</a>'</code>), but why is it missing in the output?</p>
<pre><code><?xml version="1.0" ?>
<el/>
</code></pre>
<p>I expect:</p>
<pre><code><?xml version="1.0" ?>
<el xmlns="http://example.net/ns" />
</code></pre>
<p>or</p>
<pre><code><?xml version="1.0" ?>
<randomid:el xmlns:randomid="http://example.net/ns" />
</code></pre>
| 22 | 2009-05-14T14:51:01Z | 866,412 | <p>This feature is already proposed; a patch is <a href="http://bugs.python.org/issue1621421">slumbering in the Python bug database</a>. See Tomalak's answer (in short: Manually add the <code>xmlns</code> attribute) for a workaround.</p>
| 5 | 2009-05-14T23:39:29Z | [
"python",
"xml",
"dom",
"namespaces"
] |
A data-structure for 1:1 mappings in python? | 863,935 | <p>I have a problem which requires a reversable 1:1 mapping of keys to values. </p>
<p>That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. </p>
<pre><code>x = D[y]
y == D.inverse[x]
</code></pre>
<p>The obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, <a href="http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833">there's a recipe here but for a large dictionary it can be very slow</a>.</p>
<p>The other alternative is to make a new class which unites two dictionaries, one for each kind of lookup. That would most likely be fast but would use up twice as much memory as a single dict. </p>
<p>So is there a better structure I can use?</p>
<ul>
<li>My application requires that this should be very fast and use as little as possible memory.</li>
<li>The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index)</li>
<li>We can guarantee that either the key or the value (or both) will be an integer</li>
<li>It's likely that the structure will be needed to store thousands or possibly millions of items.</li>
<li>Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]</li>
</ul>
| 24 | 2009-05-14T15:14:18Z | 863,974 | <blockquote>
<p>The other alternative is to make a new class which unites two dictionaries, one for each > kind of lookup. That would most likely use up twice as much memory as a single dict.</p>
</blockquote>
<p>Not really, since they would just be holding two references to the same data. In my mind, this is not a bad solution. </p>
<p>Have you considered an in-memory database lookup? I am not sure how it will compare in speed, but lookups in relational databases can be <em>very</em> fast.</p>
| 5 | 2009-05-14T15:19:29Z | [
"python",
"data-structures"
] |
A data-structure for 1:1 mappings in python? | 863,935 | <p>I have a problem which requires a reversable 1:1 mapping of keys to values. </p>
<p>That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. </p>
<pre><code>x = D[y]
y == D.inverse[x]
</code></pre>
<p>The obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, <a href="http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833">there's a recipe here but for a large dictionary it can be very slow</a>.</p>
<p>The other alternative is to make a new class which unites two dictionaries, one for each kind of lookup. That would most likely be fast but would use up twice as much memory as a single dict. </p>
<p>So is there a better structure I can use?</p>
<ul>
<li>My application requires that this should be very fast and use as little as possible memory.</li>
<li>The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index)</li>
<li>We can guarantee that either the key or the value (or both) will be an integer</li>
<li>It's likely that the structure will be needed to store thousands or possibly millions of items.</li>
<li>Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]</li>
</ul>
| 24 | 2009-05-14T15:14:18Z | 863,983 | <p>Assuming that you have a key with which you look up a more complex mutable object, just make the key a property of that object. It does seem you might be better off thinking about the data model a bit.</p>
| 1 | 2009-05-14T15:20:47Z | [
"python",
"data-structures"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.