title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
Best Django 'CMS' component for integration into existing site
302,983
<p>So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms. </p> <p>Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface? </p>
13
2008-11-19T19:04:55Z
489,695
<p>There is also this one that is quite nice as well:</p> <p><a href="http://code.google.com/p/django-page-cms/" rel="nofollow">Django CMS page</a></p>
5
2009-01-28T22:29:10Z
[ "python", "django", "content-management-system" ]
Best Django 'CMS' component for integration into existing site
302,983
<p>So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms. </p> <p>Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface? </p>
13
2008-11-19T19:04:55Z
1,257,116
<p>If you do not necessarily want a finished CMS with a fixed feature set, but rather tools on top of Django to build your own CMS I recommend looking into FeinCMS. It follows a toolkit philosophy instead of trying to solve everything and (too) often failing to do so.</p> <p><a href="http://github.com/matthiask/feincms/tree/master" rel="nofollow">http://github.com/matthiask/feincms/tree/master</a></p> <p>Disclaimer: It is my brainchild, and the result of too many frustrating experiences trying to customize another CMS for the needs of my customers.</p>
7
2009-08-10T20:46:34Z
[ "python", "django", "content-management-system" ]
Best Django 'CMS' component for integration into existing site
302,983
<p>So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms. </p> <p>Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface? </p>
13
2008-11-19T19:04:55Z
1,392,910
<p>If you need some more features then the simple django-page-cms just checkout django-blocks (<a href="http://code.google.com/p/django-blocks/" rel="nofollow">http://code.google.com/p/django-blocks/</a>). Has multi-language Menu, Flatpages and even has a simple Shopping Cart!!</p>
4
2009-09-08T09:16:59Z
[ "python", "django", "content-management-system" ]
Best Django 'CMS' component for integration into existing site
302,983
<p>So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms. </p> <p>Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface? </p>
13
2008-11-19T19:04:55Z
1,504,327
<p>There is a very nice overview of Django CMS apps on the Django wiki!</p> <p><a href="http://code.djangoproject.com/wiki/CMSAppsComparison" rel="nofollow">http://code.djangoproject.com/wiki/CMSAppsComparison</a></p>
3
2009-10-01T14:33:08Z
[ "python", "django", "content-management-system" ]
Best Django 'CMS' component for integration into existing site
302,983
<p>So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms. </p> <p>Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface? </p>
13
2008-11-19T19:04:55Z
3,892,818
<p>I have worked with all three (and more) and they are all built for different use cases IMHO. I would agree that these are the top-teir choices.</p> <p>The grid comparison at djangopluggables.com certainly can make evaluating each of these easier.</p> <p><strong>django-cms</strong> is the most full-featured and is something you could actually hand over to clients without being irresponsible. Even though it has features for integrating other apps, it doesn't have the extensibility/integration of FeinCMS or the simplicity of django-page-cms. That being said, I think the consensus is that this is the best Open Source CMS for Django. However, it's docs are a little lacking. <strong><em>update</em></strong>: <em>I have been told that integrating apps into DjangoCMS 2.1 has been improved.</em></p> <p><strong>FeinCMS</strong> - Is a great set of tools for combining and building CMS functionality into your own apps. It's not "out of the box" at all, which means that you can integrate it however you want. It doesn't want to take over your urls.py or control how you route pages. It's probably a prototype for the next-generation of truly pluggable apps in Django. - We are moving from django-page-cms to FeinCMS because our primary models is high volume eCommerce and I have custom content-types I want to integrate that aren't blogs or flash. Good documentation and support as well.</p> <p><strong>Django-page-cms</strong> - Is great if you want to just have some "About Us" pages around your principle application. Its menu system is not truly hierarchical and building your page presentation is up to you. But it's very simple, unobtrusive, and very easy to slap into your app and get a navigation going that clients can manage, or even for yourself. It has no docs that I know of, but you won't really need any. Read the code and you will get it all in 30 minutes or less.</p> <p><em>update</em></p> <p><strong>Mezzanine</strong> - Is a very well designed CMS and one that I have finally settled on for most of my client work, mostly because it has an integrated eCommerce portion. But beyond that it has very extensible page models, and a custom admin interface that a client might be willing to use. It also has the best "out of the box" experience i.e. You can have a full fledged site up with one command.</p>
25
2010-10-08T17:16:32Z
[ "python", "django", "content-management-system" ]
How do I remove/delete a folder that is not empty with Python?
303,200
<p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p> <p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p>
484
2008-11-19T20:15:38Z
303,225
<pre><code>import shutil shutil.rmtree('/folder_name') </code></pre> <p><a href="http://docs.python.org/library/shutil.html#shutil.rmtree">Standard Library Reference: shutil.rmtree</a>.</p>
770
2008-11-19T20:23:16Z
[ "python", "file" ]
How do I remove/delete a folder that is not empty with Python?
303,200
<p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p> <p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p>
484
2008-11-19T20:15:38Z
303,228
<p>From <a href="http://docs.python.org/library/os.html#os.walk">the python docs</a> on <code>os.walk()</code>:</p> <pre><code># Delete everything reachable from the directory named in 'top', # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. 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>
90
2008-11-19T20:23:41Z
[ "python", "file" ]
How do I remove/delete a folder that is not empty with Python?
303,200
<p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p> <p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p>
484
2008-11-19T20:15:38Z
4,507,228
<p>if you are sure, that you want to delete the entire dir tree, and are no more interested in contents of dir, then crawling for entire dir tree is stupidness... just call native OS command from python to do that. It will be faster, efficient and less memory consuming. </p> <pre><code>RMDIR c:\blah /s /q </code></pre> <p>or *nix </p> <pre><code>rm -rf /home/whatever </code></pre> <p>In python, the code will look like..</p> <pre><code>import sys import os mswindows = (sys.platform == "win32") def getstatusoutput(cmd): """Return (status, output) of executing cmd in a shell.""" if not mswindows: return commands.getstatusoutput(cmd) pipe = os.popen(cmd + ' 2&gt;&amp;1', 'r') text = pipe.read() sts = pipe.close() if sts is None: sts = 0 if text[-1:] == '\n': text = text[:-1] return sts, text def deleteDir(path): """deletes the path entirely""" if mswindows: cmd = "RMDIR "+ path +" /s /q" else: cmd = "rm -rf "+path result = getstatusoutput(cmd) if(result[0]!=0): raise RuntimeError(result[1]) </code></pre>
4
2010-12-22T08:00:23Z
[ "python", "file" ]
How do I remove/delete a folder that is not empty with Python?
303,200
<p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p> <p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p>
484
2008-11-19T20:15:38Z
25,172,642
<pre><code>import shutil shutil.rmtree(dest, ignore_errors=True) </code></pre>
40
2014-08-07T00:59:15Z
[ "python", "file" ]
How do I remove/delete a folder that is not empty with Python?
303,200
<p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p> <p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p>
484
2008-11-19T20:15:38Z
28,476,881
<pre><code>shutil.rmtree(path,ignore_errors=False,onerror=errorRemoveReadonly) def errorRemoveReadonly(func, path, exc): excvalue = exc[1] if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES: # change the file to be readable,writable,executable: 0777 os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # retry func(path) else: raiseenter code here </code></pre> <p>If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised.enter code here</p>
5
2015-02-12T11:58:43Z
[ "python", "file" ]
How do I remove/delete a folder that is not empty with Python?
303,200
<p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p> <p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p>
484
2008-11-19T20:15:38Z
28,834,214
<p>from python 3.4 you may use :</p> <pre><code>import pathlib def delete_folder(pth) : for sub in pth.iterdir() : if sub.is_dir() : delete_folder(sub) else : sub.unlink() pth.rmdir() # if you just want to delete dir content, remove this line </code></pre> <p>where <code>pth</code> is a <code>pathlib.Path</code> instance. Nice, but may not be the fastest.</p>
5
2015-03-03T14:23:53Z
[ "python", "file" ]
How do I remove/delete a folder that is not empty with Python?
303,200
<p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p> <p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p>
484
2008-11-19T20:15:38Z
32,979,686
<p>Base on kkubasik's answer, check if folder exists before remove, more robust</p> <pre><code>import shutil def remove_folder(path): # check if folder exists if os.path.exists(path): # remove if exists shutil.rmtree(path) remove_folder("/folder_name") </code></pre>
5
2015-10-06T21:02:15Z
[ "python", "file" ]
How do I remove/delete a folder that is not empty with Python?
303,200
<p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p> <p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p>
484
2008-11-19T20:15:38Z
34,714,324
<p>You can use os.system command for simplicity:</p> <pre><code>import os os.system("rm -rf dirname") </code></pre> <p>As obvious, it actually invokes system terminal to accomplish this task.</p>
1
2016-01-11T04:46:15Z
[ "python", "file" ]
Is there a better StringCollection editor for use in PropertyGrids?
303,360
<p>I'm making heavy use of PropertySheets in my application framework's configuration editor. I like them a lot because it's pretty easy to work with them (once you learn how) and make the editing bulletproof.</p> <p>One of the things that I'm storing in my configuration are Python scripts. It's possible to edit a Python script in a StringCollection editor, which is what I've been using, but there's a long distance between "possible" and "useable." I'd like to have an editor that actually supported resizeable and monospace fonts, preserved blank lines, and - hey, let's go crazy with the wishlist - did syntax coloring.</p> <p>I can certainly write this if I really have to, but I'd prefer not to.</p> <p>I've poked around on the Google and can't find anything like what I'm describing, so I thought I'd ask here. Is this a solved problem? Has anyone out there already taken a crack at building a better editor?</p>
4
2008-11-19T21:04:15Z
303,408
<p>You would need to write your own type editor. You can think of this as a user control, in that when you write your own type editor you are providing the UI controls that appear when the property grid edits the property. As such, you can create a type editor that does anything, which means if you have a third-party editor control you can include it as part of type editor.</p> <p>Some resources to get you started:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms171839.aspx" rel="nofollow">User Interface Type Editors Overview</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms171840.aspx" rel="nofollow">Walkthrough: Implementing a UI Type Editor</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.drawing.design.uitypeeditor.aspx" rel="nofollow">UITypeEditor Class</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/53c49eck.aspx" rel="nofollow">How to: Implement a UI Type Editor</a></li> <li><a href="http://www.codeproject.com/KB/miscctrl/UITypeEditorsDemo.aspx" rel="nofollow">Rich Design Time Editing with UITypeEditors (VB.NET)</a></li> <li><a href="http://www.codeproject.com/KB/cpp/DropDownPropertyEditor.aspx" rel="nofollow">Creating Property Editors in DesignTime for VS.Net Easily (UITypeEditor Helper)</a></li> <li><a href="http://www.codeproject.com/KB/tabs/PropertyGrid.aspx" rel="nofollow">Using PropertyGrid</a></li> </ul>
1
2008-11-19T21:23:46Z
[ "c#", ".net", "python", "editor", "propertygrid" ]
Is there a better StringCollection editor for use in PropertyGrids?
303,360
<p>I'm making heavy use of PropertySheets in my application framework's configuration editor. I like them a lot because it's pretty easy to work with them (once you learn how) and make the editing bulletproof.</p> <p>One of the things that I'm storing in my configuration are Python scripts. It's possible to edit a Python script in a StringCollection editor, which is what I've been using, but there's a long distance between "possible" and "useable." I'd like to have an editor that actually supported resizeable and monospace fonts, preserved blank lines, and - hey, let's go crazy with the wishlist - did syntax coloring.</p> <p>I can certainly write this if I really have to, but I'd prefer not to.</p> <p>I've poked around on the Google and can't find anything like what I'm describing, so I thought I'd ask here. Is this a solved problem? Has anyone out there already taken a crack at building a better editor?</p>
4
2008-11-19T21:04:15Z
16,244,797
<p>You can create your own string collection editor easily, following these simple steps. <em>This example uses C#.</em></p> <p>1) You must create an editor control and derive it from <code>System.Drawing.Design.UITypeEditor</code>. I called mine <code>StringArrayEditor</code>. Thus my class starts with</p> <pre><code>public class StringArrayEditor : System.Drawing.Design.UITypeEditor </code></pre> <p>The <code>PropertyGrid</code> control needs to know that the editor is modal and it will show the ellipses button when the property in question is selected. So you must override <code>GetEditStyle</code> as follows:</p> <pre><code> public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } </code></pre> <p>Lastly the editor control must override the <code>EditValue</code> operation so that it knows how you want to proceed when the user clicks on the ellipses button for your property. Here is the full code for the override:</p> <pre><code> public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { var editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; if (editorService != null) { var selectionControl = new TextArrayPropertyForm((string[])value, "Edit the lines of text", "Label Editor"); editorService.ShowDialog(selectionControl); if (selectionControl.DialogResult == DialogResult.OK) value = selectionControl.Value; } return value ?? new string[] {}; } </code></pre> <p>So what is happening? When the user clicks on the ellipses, this override is called. <code>editorService</code> is set as the interface for our editing form. It is set to the form which we haven't yet created that I call <code>TextArrayPropertyForm</code>. <code>TextArrayPropertyForm</code> is instantiated, passing the value to be edited. For good measure I am also passing 2 strings, one for the form title and the other for a label at the top explaining what the user should do. It is shown modally and if the OK button was clicked then the value is updated with whatever the value was set in <code>selectionControl.Value</code> from the form we will create. Finally this value is returned at the end of the override.</p> <p>Step 2) Create the editor form. In my case I created a form with 2 Buttons (<code>buttonOK</code> and <code>buttonCancel</code>) a Label (<code>labelInstructions</code>) and a TextBox (<code>textValue</code>) to mimic the default StringCollection editor. The code is pretty straight-forward, but in case you're interested, here it is.</p> <pre><code>using System; using System.Windows.Forms; namespace MyNamespace { /// &lt;summary&gt; /// Alternate form for editing string arrays in PropertyGrid control /// &lt;/summary&gt; public partial class TextArrayPropertyForm : Form { public TextArrayPropertyForm(string[] value, string instructions = "Enter the strings in the collection (one per line):", string title = "String Collection Editor") { InitializeComponent(); Value = value; textValue.Text = string.Join("\r\n", value); labelInstructions.Text = instructions; Text = title; } public string[] Value; private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } private void buttonOK_Click(object sender, EventArgs e) { Value = textValue.Text.Split(new[] { "\r\n" }, StringSplitOptions.None); DialogResult = DialogResult.OK; } } } </code></pre> <p>Step 3)Tell the PropertyGrid to use the alternate editor. The change between this property and any other that is used in the PropertyGrid control is the [Editor] line.</p> <pre><code> [Description("The name or text to appear on the layout.")] [DisplayName("Text"), Browsable(true), Category("Design")] [Editor(typeof(StringArrayEditor), typeof(System.Drawing.Design.UITypeEditor))] public string[] Text {get; set;} </code></pre> <p>Now when you create a PropertyGrid on a form and set to the class containing this Text property it will edit in your custom made form. There are countless opportunities to change your custom form in ways you choose. With modifications this will work for editing any type you like. The important thing is that the editor control returns the same type as is the property in the overridden <code>EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)</code></p> <p>Hope this helps!</p>
3
2013-04-26T20:35:17Z
[ "c#", ".net", "python", "editor", "propertygrid" ]
Newbie Python Question about tuples
303,664
<p>I am new to Python, and I'm working on writing some database code using the <code>cx_Oracle</code> module. In the <a href="http://cx-oracle.sourceforge.net/html/module.html" rel="nofollow">cx_Oracle documentation</a> they have a code example like this:</p> <pre><code>import sys import cx_Oracle connection = cx_Oracle.Connection("user/pw@tns") cursor = connection.cursor() try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: error, = exc.args print &gt;&gt; sys.stderr, "Oracle-Error-Code:", error.code print &gt;&gt; sys.stderr, "Oracle-Error-Message:", error.message </code></pre> <p>My question has to do with where the "error" object is created. What does the "<code>, =</code>" do? I tried searching Python documentation, and search engines don't work very well when you're searching for operators. :-)</p> <p>I know that the exc.args is a singleton tuple, but I just don't understand the "<code>, =</code>" syntax. If I remove the comma, I get the error message, "<code>AttributeError: 'tuple' object has no attribute 'code'</code>". </p> <p>Can someone point me to where this is documented? Thanks!</p> <p><strong>EDIT:</strong></p> <p>This works without having to unpack the tuple:</p> <pre><code>import sys import cx_Oracle connection = cx_Oracle.Connection("user/pw@tns") cursor = connection.cursor() try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: print &gt;&gt; sys.stderr, "Oracle-Error-Code:", exc.args[0].code print &gt;&gt; sys.stderr, "Oracle-Error-Message:", exc.args[0].message </code></pre>
5
2008-11-19T22:36:37Z
303,673
<p><a href="http://www.python.org/doc/2.5.2/tut/node7.html#SECTION007300000000000000000" rel="nofollow">http://www.python.org/doc/2.5.2/tut/node7.html</a></p> <p>Look for "sequence unpacking" in section 5.3.</p>
5
2008-11-19T22:40:42Z
[ "python", "tuples", "cx-oracle" ]
Newbie Python Question about tuples
303,664
<p>I am new to Python, and I'm working on writing some database code using the <code>cx_Oracle</code> module. In the <a href="http://cx-oracle.sourceforge.net/html/module.html" rel="nofollow">cx_Oracle documentation</a> they have a code example like this:</p> <pre><code>import sys import cx_Oracle connection = cx_Oracle.Connection("user/pw@tns") cursor = connection.cursor() try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: error, = exc.args print &gt;&gt; sys.stderr, "Oracle-Error-Code:", error.code print &gt;&gt; sys.stderr, "Oracle-Error-Message:", error.message </code></pre> <p>My question has to do with where the "error" object is created. What does the "<code>, =</code>" do? I tried searching Python documentation, and search engines don't work very well when you're searching for operators. :-)</p> <p>I know that the exc.args is a singleton tuple, but I just don't understand the "<code>, =</code>" syntax. If I remove the comma, I get the error message, "<code>AttributeError: 'tuple' object has no attribute 'code'</code>". </p> <p>Can someone point me to where this is documented? Thanks!</p> <p><strong>EDIT:</strong></p> <p>This works without having to unpack the tuple:</p> <pre><code>import sys import cx_Oracle connection = cx_Oracle.Connection("user/pw@tns") cursor = connection.cursor() try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: print &gt;&gt; sys.stderr, "Oracle-Error-Code:", exc.args[0].code print &gt;&gt; sys.stderr, "Oracle-Error-Message:", exc.args[0].message </code></pre>
5
2008-11-19T22:36:37Z
303,693
<p>The comma serves to unpack the tuple, i.e. it extracts the single item of the tuple, and binds it to <code>error</code>. Without the comma, you would bind the tuple itself, rather than its content.</p>
4
2008-11-19T22:49:00Z
[ "python", "tuples", "cx-oracle" ]
Newbie Python Question about tuples
303,664
<p>I am new to Python, and I'm working on writing some database code using the <code>cx_Oracle</code> module. In the <a href="http://cx-oracle.sourceforge.net/html/module.html" rel="nofollow">cx_Oracle documentation</a> they have a code example like this:</p> <pre><code>import sys import cx_Oracle connection = cx_Oracle.Connection("user/pw@tns") cursor = connection.cursor() try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: error, = exc.args print &gt;&gt; sys.stderr, "Oracle-Error-Code:", error.code print &gt;&gt; sys.stderr, "Oracle-Error-Message:", error.message </code></pre> <p>My question has to do with where the "error" object is created. What does the "<code>, =</code>" do? I tried searching Python documentation, and search engines don't work very well when you're searching for operators. :-)</p> <p>I know that the exc.args is a singleton tuple, but I just don't understand the "<code>, =</code>" syntax. If I remove the comma, I get the error message, "<code>AttributeError: 'tuple' object has no attribute 'code'</code>". </p> <p>Can someone point me to where this is documented? Thanks!</p> <p><strong>EDIT:</strong></p> <p>This works without having to unpack the tuple:</p> <pre><code>import sys import cx_Oracle connection = cx_Oracle.Connection("user/pw@tns") cursor = connection.cursor() try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: print &gt;&gt; sys.stderr, "Oracle-Error-Code:", exc.args[0].code print &gt;&gt; sys.stderr, "Oracle-Error-Message:", exc.args[0].message </code></pre>
5
2008-11-19T22:36:37Z
303,697
<pre><code>error, = exc.args </code></pre> <p>This is a case of <a href="http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">sequence unpacking</a>.</p> <p>A more readable way to write the same, and the style I personally favor, is:</p> <pre><code>[error] = exc.args </code></pre> <p>There are two bits required to understand the previous example:</p> <ol> <li>When the left hand side of an assignment is a recursive sequence of names, the value of the right hand side must be a sequence with the same length, and each item of the RHS value is assigned to the corresponding name in the LHS.</li> <li>A one-item tuple in python is written <code>(foo,)</code>. In most contexts, the parenthesis can be ommitted. In particular, they can be omitted next to the assignment operator.</li> </ol>
9
2008-11-19T22:51:00Z
[ "python", "tuples", "cx-oracle" ]
(Python) socket.gaierror on every addres...except http://www.reddit.com?
303,726
<p>I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code:</p> <pre><code>import sys import socket import re from urlparse import urlsplit url = urlsplit(sys.argv[1]) sock = socket.socket() sock.connect((url[0] + '://' + url[1],80)) path = url[2] if not path: path = '/' print path sock.send('GET ' + path + ' HTTP/1.1\r\n' + 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.3.154.9 Safari/525.19\r\n' + 'Accept: */*\r\n' + 'Accept-Language: en-US,en\r\n' + 'Accept-Charset: ISO-8859-1,*,utf-8\r\n' + 'Host: 68.33.143.182\r\n' + 'Connection: Keep-alive\r\n' + '\r\n') </code></pre> <p>I get the following error:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "D:\Development\Python\PyCrawler\PyCrawler.py", line 10, in sock.connect((url[0] + '://' + url[1],80)) File "", line 1, in connect socket.gaierror: (11001, 'getaddrinfo failed')</p> </blockquote> <p>The only time I do not get an error is if the url passed is <a href="http://www.reddit.com" rel="nofollow">http://www.reddit.com</a>. Every other url I have tried comes up with the socket.gaierror. Can anyone explain this? And possibly give a solution?</p>
0
2008-11-19T23:00:57Z
303,747
<p>you forgot to resolve the hostname:</p> <pre><code>addr = socket.gethostbyname(url[1]) ... sock.connect((addr,80)) </code></pre>
1
2008-11-19T23:08:52Z
[ "python", "http", "sockets" ]
(Python) socket.gaierror on every addres...except http://www.reddit.com?
303,726
<p>I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code:</p> <pre><code>import sys import socket import re from urlparse import urlsplit url = urlsplit(sys.argv[1]) sock = socket.socket() sock.connect((url[0] + '://' + url[1],80)) path = url[2] if not path: path = '/' print path sock.send('GET ' + path + ' HTTP/1.1\r\n' + 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.3.154.9 Safari/525.19\r\n' + 'Accept: */*\r\n' + 'Accept-Language: en-US,en\r\n' + 'Accept-Charset: ISO-8859-1,*,utf-8\r\n' + 'Host: 68.33.143.182\r\n' + 'Connection: Keep-alive\r\n' + '\r\n') </code></pre> <p>I get the following error:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "D:\Development\Python\PyCrawler\PyCrawler.py", line 10, in sock.connect((url[0] + '://' + url[1],80)) File "", line 1, in connect socket.gaierror: (11001, 'getaddrinfo failed')</p> </blockquote> <p>The only time I do not get an error is if the url passed is <a href="http://www.reddit.com" rel="nofollow">http://www.reddit.com</a>. Every other url I have tried comes up with the socket.gaierror. Can anyone explain this? And possibly give a solution?</p>
0
2008-11-19T23:00:57Z
303,749
<blockquote> <pre><code>sock.connect((url[0] + '://' + url[1],80)) </code></pre> </blockquote> <p>Do not do that, instead do this:</p> <pre><code>sock.connect((url[1], 80)) </code></pre> <p><code>connect</code> expects a hostname, not a URL.</p> <p>Actually, you should probably use something higher-level than sockets to do HTTP. Maybe <a href="http://docs.python.org/library/httplib.html" rel="nofollow">httplib</a>.</p>
3
2008-11-19T23:09:00Z
[ "python", "http", "sockets" ]
(Python) socket.gaierror on every addres...except http://www.reddit.com?
303,726
<p>I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code:</p> <pre><code>import sys import socket import re from urlparse import urlsplit url = urlsplit(sys.argv[1]) sock = socket.socket() sock.connect((url[0] + '://' + url[1],80)) path = url[2] if not path: path = '/' print path sock.send('GET ' + path + ' HTTP/1.1\r\n' + 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.3.154.9 Safari/525.19\r\n' + 'Accept: */*\r\n' + 'Accept-Language: en-US,en\r\n' + 'Accept-Charset: ISO-8859-1,*,utf-8\r\n' + 'Host: 68.33.143.182\r\n' + 'Connection: Keep-alive\r\n' + '\r\n') </code></pre> <p>I get the following error:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "D:\Development\Python\PyCrawler\PyCrawler.py", line 10, in sock.connect((url[0] + '://' + url[1],80)) File "", line 1, in connect socket.gaierror: (11001, 'getaddrinfo failed')</p> </blockquote> <p>The only time I do not get an error is if the url passed is <a href="http://www.reddit.com" rel="nofollow">http://www.reddit.com</a>. Every other url I have tried comes up with the socket.gaierror. Can anyone explain this? And possibly give a solution?</p>
0
2008-11-19T23:00:57Z
303,897
<p>Please please please please please please please don't do this.</p> <p>urllib and urllib2 are your friends.</p> <p>Read <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml" rel="nofollow">the "missing" urllib2 manual</a> if you are having trouble with it.</p>
3
2008-11-20T00:02:29Z
[ "python", "http", "sockets" ]
(Python) socket.gaierror on every addres...except http://www.reddit.com?
303,726
<p>I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code:</p> <pre><code>import sys import socket import re from urlparse import urlsplit url = urlsplit(sys.argv[1]) sock = socket.socket() sock.connect((url[0] + '://' + url[1],80)) path = url[2] if not path: path = '/' print path sock.send('GET ' + path + ' HTTP/1.1\r\n' + 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.3.154.9 Safari/525.19\r\n' + 'Accept: */*\r\n' + 'Accept-Language: en-US,en\r\n' + 'Accept-Charset: ISO-8859-1,*,utf-8\r\n' + 'Host: 68.33.143.182\r\n' + 'Connection: Keep-alive\r\n' + '\r\n') </code></pre> <p>I get the following error:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "D:\Development\Python\PyCrawler\PyCrawler.py", line 10, in sock.connect((url[0] + '://' + url[1],80)) File "", line 1, in connect socket.gaierror: (11001, 'getaddrinfo failed')</p> </blockquote> <p>The only time I do not get an error is if the url passed is <a href="http://www.reddit.com" rel="nofollow">http://www.reddit.com</a>. Every other url I have tried comes up with the socket.gaierror. Can anyone explain this? And possibly give a solution?</p>
0
2008-11-19T23:00:57Z
619,479
<p>Have you ever altered your <a href="http://en.wikipedia.org/wiki/Hosts_file" rel="nofollow">Hosts file</a>? If it has an entry for Reddit but not much else, that might explain that site's unique result.</p>
2
2009-03-06T16:32:59Z
[ "python", "http", "sockets" ]
(Python) socket.gaierror on every addres...except http://www.reddit.com?
303,726
<p>I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code:</p> <pre><code>import sys import socket import re from urlparse import urlsplit url = urlsplit(sys.argv[1]) sock = socket.socket() sock.connect((url[0] + '://' + url[1],80)) path = url[2] if not path: path = '/' print path sock.send('GET ' + path + ' HTTP/1.1\r\n' + 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.3.154.9 Safari/525.19\r\n' + 'Accept: */*\r\n' + 'Accept-Language: en-US,en\r\n' + 'Accept-Charset: ISO-8859-1,*,utf-8\r\n' + 'Host: 68.33.143.182\r\n' + 'Connection: Keep-alive\r\n' + '\r\n') </code></pre> <p>I get the following error:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "D:\Development\Python\PyCrawler\PyCrawler.py", line 10, in sock.connect((url[0] + '://' + url[1],80)) File "", line 1, in connect socket.gaierror: (11001, 'getaddrinfo failed')</p> </blockquote> <p>The only time I do not get an error is if the url passed is <a href="http://www.reddit.com" rel="nofollow">http://www.reddit.com</a>. Every other url I have tried comes up with the socket.gaierror. Can anyone explain this? And possibly give a solution?</p>
0
2008-11-19T23:00:57Z
619,536
<p>Use urllib2. Or <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>.</p>
0
2009-03-06T16:44:05Z
[ "python", "http", "sockets" ]
Emacs 23 and iPython
304,049
<p>Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?</p>
24
2008-11-20T01:12:16Z
304,202
<p>never used it myself, but I do follow the ipython mailing list, and there was a <a href="http://lists.ipython.scipy.org/pipermail/ipython-user/2008-September/thread.html" rel="nofollow">thread</a> a couple months back.</p> <p>maybe this will help</p> <p><a href="http://lists.ipython.scipy.org/pipermail/ipython-user/2008-September/005791.html" rel="nofollow">http://lists.ipython.scipy.org/pipermail/ipython-user/2008-September/005791.html</a></p> <p>It's also a very responsive mailing list if you run into trouble.</p>
2
2008-11-20T02:50:33Z
[ "python", "emacs", "ipython", "emacs23" ]
Emacs 23 and iPython
304,049
<p>Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?</p>
24
2008-11-20T01:12:16Z
312,741
<p>I got it working quite well with emacs 23. The only open issue is the focus not returning to the python buffer after sending the buffer to the iPython interpreter.</p> <p><a href="http://www.emacswiki.org/emacs/PythonMode#toc10" rel="nofollow">http://www.emacswiki.org/emacs/PythonMode#toc10</a></p> <pre><code>(setq load-path (append (list nil "~/.emacs.d/python-mode-1.0/" "~/.emacs.d/pymacs/" "~/.emacs.d/ropemacs-0.6" ) load-path)) (setq py-shell-name "ipython") (defadvice py-execute-buffer (around python-keep-focus activate) "return focus to python code buffer" (save-excursion ad-do-it)) (setenv "PYMACS_PYTHON" "python2.5") (require 'pymacs) (pymacs-load "ropemacs" "rope-") (provide 'python-programming) </code></pre>
8
2008-11-23T17:26:07Z
[ "python", "emacs", "ipython", "emacs23" ]
Emacs 23 and iPython
304,049
<p>Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?</p>
24
2008-11-20T01:12:16Z
492,173
<p>I've used ipython with emacs cvs (which has been emacs 23 for some time now) in my python development. I, however, use it the other way around: I call emacs from the ipython promt through the $EDITOR environment variable. I tried it the other way around, but got a bit tired of all the process buffers and what not.</p> <p>Emacs is great, but a command-line far more versatile.</p>
0
2009-01-29T15:50:21Z
[ "python", "emacs", "ipython", "emacs23" ]
Data Modelling Advice for Blog Tagging system on Google App Engine
304,117
<p>Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitfalls. It's my understanding that a basic principal is that "storage is cheap, don't worry about data duplication" as you might in a normalized RDBMS. </p> <p>What I'd like to model is:</p> <p>A blog article which can be given 0-n tags. Many blog articles can share the same tag. When retrieving data would like to allow retrieval of all articles matching a tag. In many ways very similar to the approach taken here at stackoverflow.</p> <p>My normal mindset would be to create a many-to-may relationship between tags and blog articles. However, I'm thinking in the context of GAE that this would be expensive, although I have seen examples of it being done. </p> <p>Perhaps using a ListProperty containing each tag as part of the article entities, and a second data model to track tags as they're added and deleted? This way no need for any relationships and the ListProperty still allows queries where any list element matching will return results.</p> <p>Any suggestions on the most efficient way to approach this on GAE?</p>
8
2008-11-20T01:56:32Z
304,170
<p>Many-to-many sounds reasonable. Perhaps you should try it first to see if it is actually expensive.</p> <p>Good thing about G.A.E. is that it will tell you when you are using too many cycles. Profiling for free!</p>
1
2008-11-20T02:31:29Z
[ "python", "google-app-engine", "bigtable", "data-modeling" ]
Data Modelling Advice for Blog Tagging system on Google App Engine
304,117
<p>Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitfalls. It's my understanding that a basic principal is that "storage is cheap, don't worry about data duplication" as you might in a normalized RDBMS. </p> <p>What I'd like to model is:</p> <p>A blog article which can be given 0-n tags. Many blog articles can share the same tag. When retrieving data would like to allow retrieval of all articles matching a tag. In many ways very similar to the approach taken here at stackoverflow.</p> <p>My normal mindset would be to create a many-to-may relationship between tags and blog articles. However, I'm thinking in the context of GAE that this would be expensive, although I have seen examples of it being done. </p> <p>Perhaps using a ListProperty containing each tag as part of the article entities, and a second data model to track tags as they're added and deleted? This way no need for any relationships and the ListProperty still allows queries where any list element matching will return results.</p> <p>Any suggestions on the most efficient way to approach this on GAE?</p>
8
2008-11-20T01:56:32Z
307,312
<p>One possible way is with <code>Expando</code>, where you'd add a tag like:</p> <pre><code>setattr(entity, 'tag_'+tag_name, True) </code></pre> <p>Then you could query all the entities with a tag like:</p> <pre><code>def get_all_with_tag(model_class, tag): return model_class.all().filter('tag_%s =' % tag, True) </code></pre> <p>Of course you have to clean up your tags to be proper Python identifiers. I haven't tried this, so I'm not sure if it's really a good solution.</p>
1
2008-11-20T23:43:15Z
[ "python", "google-app-engine", "bigtable", "data-modeling" ]
Data Modelling Advice for Blog Tagging system on Google App Engine
304,117
<p>Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitfalls. It's my understanding that a basic principal is that "storage is cheap, don't worry about data duplication" as you might in a normalized RDBMS. </p> <p>What I'd like to model is:</p> <p>A blog article which can be given 0-n tags. Many blog articles can share the same tag. When retrieving data would like to allow retrieval of all articles matching a tag. In many ways very similar to the approach taken here at stackoverflow.</p> <p>My normal mindset would be to create a many-to-may relationship between tags and blog articles. However, I'm thinking in the context of GAE that this would be expensive, although I have seen examples of it being done. </p> <p>Perhaps using a ListProperty containing each tag as part of the article entities, and a second data model to track tags as they're added and deleted? This way no need for any relationships and the ListProperty still allows queries where any list element matching will return results.</p> <p>Any suggestions on the most efficient way to approach this on GAE?</p>
8
2008-11-20T01:56:32Z
307,727
<p>Thanks to both of you for your suggestions. I've implemented (first iteration) as follows. Not sure if it's the best approach, but it's working.</p> <p>Class A = Articles. Has a StringListProperty which can be queried on it's list elements</p> <p>Class B = Tags. One entity per tag, also keeps a running count of the total number of articles using each tag.</p> <p>Data modifications to A are accompanied by maintenance work on B. Thinking that counts being pre-computed is a good approach in a read-heavy environment.</p>
7
2008-11-21T03:22:38Z
[ "python", "google-app-engine", "bigtable", "data-modeling" ]
Data Modelling Advice for Blog Tagging system on Google App Engine
304,117
<p>Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitfalls. It's my understanding that a basic principal is that "storage is cheap, don't worry about data duplication" as you might in a normalized RDBMS. </p> <p>What I'd like to model is:</p> <p>A blog article which can be given 0-n tags. Many blog articles can share the same tag. When retrieving data would like to allow retrieval of all articles matching a tag. In many ways very similar to the approach taken here at stackoverflow.</p> <p>My normal mindset would be to create a many-to-may relationship between tags and blog articles. However, I'm thinking in the context of GAE that this would be expensive, although I have seen examples of it being done. </p> <p>Perhaps using a ListProperty containing each tag as part of the article entities, and a second data model to track tags as they're added and deleted? This way no need for any relationships and the ListProperty still allows queries where any list element matching will return results.</p> <p>Any suggestions on the most efficient way to approach this on GAE?</p>
8
2008-11-20T01:56:32Z
723,351
<p>counts being pre-computed is <strike>not only</strike> practical<strike>, but also necessary because the count() function returns a maximum of 1000</strike>. if write-contention might be an issue, make sure to check out the sharded counter example.</p> <p><a href="http://code.google.com/appengine/articles/sharding_counters.html" rel="nofollow">http://code.google.com/appengine/articles/sharding_counters.html</a></p>
2
2009-04-06T21:41:10Z
[ "python", "google-app-engine", "bigtable", "data-modeling" ]
Twisted FTPFileListProtocol and file names with spaces
304,152
<p>I am using Python and the <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> framework to connect to an FTP site to perform various automated tasks. Our FTP server happens to be Pure-FTPd, if that's relevant.</p> <p>When connecting and calling the <strong>list</strong> method on an <strong>FTPClient</strong>, the resulting <strong>FTPFileListProtocol</strong>'s <strong>files</strong> collection does not contain any directories or file names that contain a space (' ').</p> <p>Has anyone else seen this? Is the only solution to create a sub-class of FTPFileListProtocol and override its <strong>unknownLine</strong> method, parsing the file/directory names manually?</p>
2
2008-11-20T02:16:38Z
311,236
<p>Firstly, if you're performing automated tasks on a retrieived FTP listing then you should probably be looking at <code>NLST</code> rather than <code>LIST</code> as noted in <a href="http://tools.ietf.org/html/rfc959#page-33" rel="nofollow">RFC 959 section 4.1.3</a>:</p> <pre> NAME LIST (NLST) ... This command is intended to return information that can be used by a program to further process the files automatically. </pre> <p>The <a href="http://twistedmatrix.com/documents/current/api/twisted.protocols.ftp.FTPClient.html#list" rel="nofollow">Twisted documentation</a> for <code>LIST</code> says:</p> <pre> It can cope with most common file listing formats. </pre> <p>This make me suspicious; I do not like solutions that "cope". <code>LIST</code> was intended for human consumption not machine processing.</p> <p>If your target server supports them then you should prefer <code>MLST</code> and <code>MLSD</code> as defined in <a href="http://tools.ietf.org/html/rfc3659#section-7" rel="nofollow">RFC 3659 section 7</a>:</p> <pre> 7. Listings for Machine Processing (MLST and MLSD) The MLST and MLSD commands are intended to standardize the file and directory information returned by the server-FTP process. These commands differ from the LIST command in that the format of the replies is strictly defined although extensible. </pre> <p>However, these newer commands may not be available on your target server and I don't see them in Twisted. Therefore <code>NLST</code> is probably your best bet.</p> <p>As to the nub of your problem, there are three likely causes:</p> <ol> <li>The processing of the returned results is incorrect (Twisted may be at fault, as you suggest, or perhaps elsewhere)</li> <li>The server is buggy and not sending a correct (complete) response</li> <li>The wrong command is being sent (unlikely with straight <code>NLST</code>/<code>LIST</code>, but some servers react differently if arguments are supplied to these commands)</li> </ol> <p>You can eliminate (2) and (3) and prove that the cause is (1) by looking at what is sent over the wire. If this option is not available to you as part of the Twisted API or the Pure-FTPD server logging configuration, then you may need to break out a network sniffer such as tcpdump, snoop or WireShark (assuming you're allowed to do this in your environment). Note that you will need to trace not only the control connection (port 21) but also the data connection (since that carries the results of the <code>LIST</code>/<code>NLST</code> command). WireShark is nice since it will perform the protocol-level analysis for you.</p> <p>Good luck.</p>
2
2008-11-22T11:33:06Z
[ "python", "ftp", "twisted" ]
Twisted FTPFileListProtocol and file names with spaces
304,152
<p>I am using Python and the <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> framework to connect to an FTP site to perform various automated tasks. Our FTP server happens to be Pure-FTPd, if that's relevant.</p> <p>When connecting and calling the <strong>list</strong> method on an <strong>FTPClient</strong>, the resulting <strong>FTPFileListProtocol</strong>'s <strong>files</strong> collection does not contain any directories or file names that contain a space (' ').</p> <p>Has anyone else seen this? Is the only solution to create a sub-class of FTPFileListProtocol and override its <strong>unknownLine</strong> method, parsing the file/directory names manually?</p>
2
2008-11-20T02:16:38Z
316,811
<p>This is somehow expected. FTPFileListProtocol isn't able to understand every FTP output, because, well, some are wacky. As explained in the docstring:</p> <p>If you need different evil for a wacky FTP server, you can override either C{fileLinePattern} or C{parseDirectoryLine()}.</p> <p>In this case, it may be a bug: maybe you can improve fileLinePattern and makes it understand filename with spaces. If so, you're welcome to open a bug in the Twisted tracker.</p>
0
2008-11-25T09:26:35Z
[ "python", "ftp", "twisted" ]
Find all nodes from an XML using cElementTree
304,216
<p>Is there a way to find all nodes in a xml tree using cElementTree? The findall method works only for specified tags.</p>
1
2008-11-20T03:06:00Z
304,220
<p>You can use <a href="http://effbot.org/zone/element-xpath.htm" rel="nofollow">XPath paths</a> on the findall method:</p> <blockquote> <p>The 1.2 release supports simple element location paths. In its simplest form, a location path is one or more tag names, separated by slashes (/).</p> <p>You can also use an asterisk (*) instead of a tag name, to match all elements at that level. For example, */subtag returns all subtag grandchildren.</p> <p>An empty tag (//) is used to search on all levels of the tree, beneath the current level. The empty tag must always be followed by a tag name or an asterisk.</p> </blockquote> <pre><code>etree.findall('.//*') </code></pre>
2
2008-11-20T03:13:16Z
[ "python", "xml", "search", "celementtree" ]
Find all nodes from an XML using cElementTree
304,216
<p>Is there a way to find all nodes in a xml tree using cElementTree? The findall method works only for specified tags.</p>
1
2008-11-20T03:06:00Z
304,221
<p>Have you looked at node.getiterator()?</p>
1
2008-11-20T03:13:17Z
[ "python", "xml", "search", "celementtree" ]
What's the best way to find the inverse of datetime.isocalendar()?
304,256
<p>The Python <a href="http://www.python.org/doc/2.5.2/lib/datetime-datetime.html"><code>datetime.isocalendar()</code></a> method returns a tuple <code>(ISO_year, ISO_week_number, ISO_weekday)</code> for the given <code>datetime</code> object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?</p>
36
2008-11-20T03:38:52Z
304,288
<p><em>EDIT: ignore this, the edge cases are a pain. Go with Ben's solution.</em></p> <p>Ok, on closer inspection I noticed that <code>strptime</code> has <code>%W</code> and <code>%w</code> parameters, so the following works:</p> <pre><code>def fromisocalendar(y,w,d): return datetime.strptime( "%04dW%02d-%d"%(y,w-1,d), "%YW%W-%w") </code></pre> <p>A couple of gotchas: The ISO week number starts at <code>1</code>, while <code>%W</code> starts at <code>0</code>. The ISO week day starts at <code>1</code> (Monday), which is the same as <code>%w</code>, so Sunday would probably have to be <code>0</code>, not <code>7</code>...</p>
-1
2008-11-20T03:56:10Z
[ "python", "datetime" ]
What's the best way to find the inverse of datetime.isocalendar()?
304,256
<p>The Python <a href="http://www.python.org/doc/2.5.2/lib/datetime-datetime.html"><code>datetime.isocalendar()</code></a> method returns a tuple <code>(ISO_year, ISO_week_number, ISO_weekday)</code> for the given <code>datetime</code> object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?</p>
36
2008-11-20T03:38:52Z
382,549
<p>Note that %W is the week # (0-53) which is NOT THE SAME as the ISO week (1-53). There will be edge cases where %W will not work.</p>
0
2008-12-19T23:21:07Z
[ "python", "datetime" ]
What's the best way to find the inverse of datetime.isocalendar()?
304,256
<p>The Python <a href="http://www.python.org/doc/2.5.2/lib/datetime-datetime.html"><code>datetime.isocalendar()</code></a> method returns a tuple <code>(ISO_year, ISO_week_number, ISO_weekday)</code> for the given <code>datetime</code> object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?</p>
36
2008-11-20T03:38:52Z
1,700,069
<p>I recently had to solve this problem myself, and came up with this solution:</p> <pre><code>import datetime def iso_year_start(iso_year): "The gregorian calendar date of the first day of the given ISO year" fourth_jan = datetime.date(iso_year, 1, 4) delta = datetime.timedelta(fourth_jan.isoweekday()-1) return fourth_jan - delta def iso_to_gregorian(iso_year, iso_week, iso_day): "Gregorian calendar date for the given ISO year, week and day" year_start = iso_year_start(iso_year) return year_start + datetime.timedelta(days=iso_day-1, weeks=iso_week-1) </code></pre> <p>A few test cases:</p> <pre><code>&gt;&gt;&gt; iso = datetime.date(2005, 1, 1).isocalendar() &gt;&gt;&gt; iso (2004, 53, 6) &gt;&gt;&gt; iso_to_gregorian(*iso) datetime.date(2005, 1, 1) &gt;&gt;&gt; iso = datetime.date(2010, 1, 4).isocalendar() &gt;&gt;&gt; iso (2010, 1, 1) &gt;&gt;&gt; iso_to_gregorian(*iso) datetime.date(2010, 1, 4) &gt;&gt;&gt; iso = datetime.date(2010, 1, 3).isocalendar() &gt;&gt;&gt; iso (2009, 53, 7) &gt;&gt;&gt; iso_to_gregorian(*iso) datetime.date(2010, 1, 3) </code></pre>
53
2009-11-09T09:57:08Z
[ "python", "datetime" ]
What's the best way to find the inverse of datetime.isocalendar()?
304,256
<p>The Python <a href="http://www.python.org/doc/2.5.2/lib/datetime-datetime.html"><code>datetime.isocalendar()</code></a> method returns a tuple <code>(ISO_year, ISO_week_number, ISO_weekday)</code> for the given <code>datetime</code> object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?</p>
36
2008-11-20T03:38:52Z
33,101,215
<pre><code>import datetime def iso_to_gregorian(iso_year, iso_week, iso_day): "Gregorian calendar date for the given ISO year, week and day" fourth_jan = datetime.date(iso_year, 1, 4) _, fourth_jan_week, fourth_jan_day = fourth_jan.isocalendar() return fourth_jan + datetime.timedelta(days=iso_day-fourth_jan_day, weeks=iso_week-fourth_jan_week) </code></pre> <p>This was adapted from @BenJames's very good answer. You don't have to know the first day of the year. You just have to know an example of a date which is certainly in the same ISO year, and the ISO calendar week and day of that date.</p> <p>The 4th of Jan is simply one example, because, as Ben pointed out, the 4th of Jan always belongs to the same ISO year and Gregorian year, and is the first day of the year to do so.</p> <p>Since weeks are all the same length, you can simply subtract the days and weeks between the ISO of the date you want, and the ISO of the date which you know in both forms, and add on that number of days and weeks. (It doesn't matter whether these numbers are positive or negative, so you could choose some other 'fixed day' such as Dec 28th.)</p> <h1>Edit</h1> <p>I corrected this because, as was helpfully pointed by @JoSo, the first day of the Gregorian year which also belongs to the ISO year is Jan 4th not Jan 5th. As the explanation says, it doesn't matter which date is chosen as a reference point, but choosing the Jan 4th makes this choice less 'magic'.</p>
5
2015-10-13T11:14:57Z
[ "python", "datetime" ]
What's the best way to find the inverse of datetime.isocalendar()?
304,256
<p>The Python <a href="http://www.python.org/doc/2.5.2/lib/datetime-datetime.html"><code>datetime.isocalendar()</code></a> method returns a tuple <code>(ISO_year, ISO_week_number, ISO_weekday)</code> for the given <code>datetime</code> object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?</p>
36
2008-11-20T03:38:52Z
35,167,439
<p>Starting in Python 3.6, <code>datetime.strptime()</code> will support the <code>%G</code>, <code>%V</code> and <code>%u</code> directives, so you can simply do <code>datetime.strptime('2015 1 2', '%G %V %u').date()</code>. See: <a href="https://hg.python.org/cpython/rev/acdebfbfbdcf" rel="nofollow">https://hg.python.org/cpython/rev/acdebfbfbdcf</a></p>
0
2016-02-03T02:23:42Z
[ "python", "datetime" ]
What's the best way to find the inverse of datetime.isocalendar()?
304,256
<p>The Python <a href="http://www.python.org/doc/2.5.2/lib/datetime-datetime.html"><code>datetime.isocalendar()</code></a> method returns a tuple <code>(ISO_year, ISO_week_number, ISO_weekday)</code> for the given <code>datetime</code> object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?</p>
36
2008-11-20T03:38:52Z
35,891,060
<p>As of Python 3.6 (currently <a href="https://www.python.org/dev/peps/pep-0494/" rel="nofollow">in development</a>), you can use the new <code>%G</code>, <code>%u</code> and <code>%V</code> directives. See <a href="http://bugs.python.org/issue12006" rel="nofollow">issue 12006</a> and the <a href="https://docs.python.org/3.6/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">updated documentation</a>:</p> <blockquote> <p><code>%G</code><br> ISO 8601 year with century representing the year that contains the greater part of the ISO week (<code>%V</code>).</p> <p><code>%u</code><br> ISO 8601 weekday as a decimal number where 1 is Monday.</p> <p><code>%V</code><br> ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4.</p> </blockquote> <p>Given a string with year, weeknumber and weekday number, it is easy to parse those out to a date with:</p> <pre><code>from datetime import date date.strptime('2002 01 1', '%G %V %u') </code></pre> <p>or as a function with integer inputs:</p> <pre><code>from datetime import date def date_from_isoweek(iso_year, iso_weeknumber, iso_weekday): return date.strptime( '{:04d} {:02d} {:d}'.format(iso_year, iso_weeknumber, iso_weekday) '%G %V %u') </code></pre>
2
2016-03-09T12:02:00Z
[ "python", "datetime" ]
What's the best way to find the inverse of datetime.isocalendar()?
304,256
<p>The Python <a href="http://www.python.org/doc/2.5.2/lib/datetime-datetime.html"><code>datetime.isocalendar()</code></a> method returns a tuple <code>(ISO_year, ISO_week_number, ISO_weekday)</code> for the given <code>datetime</code> object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?</p>
36
2008-11-20T03:38:52Z
38,283,685
<p>For the next people coming here, a shorter, single-def, version of Ben's good solution:</p> <pre><code>def iso_to_gregorian(iso_year, iso_week, iso_day): jan4 = datetime.date(iso_year, 1, 4) start = jan4 - datetime.timedelta(days=jan4.isoweekday()-1) return start + datetime.timedelta(weeks=iso_week-1, days=iso_day-1) </code></pre>
2
2016-07-09T16:02:46Z
[ "python", "datetime" ]
Getting TRAC to run on IIS7
304,567
<p>Im trying to get Trac upp and running on my IIS/w2008 server using this FAQ: <a href="http://trac.edgewall.org/wiki/TracOnWindowsIisAjp" rel="nofollow">TracOnWindowsIisAjp</a></p> <p>Everything upp until "3. Install Tomcat AJP Connector for IIS" works ok. I then define my directories as : C:\wwwroot\trac.evju.biz\AJP\, in the bin catalog I place the dll file, and 3 config files with this content:</p> <p>isapi_redirect-1.2.26.properties # Configuration file for the ISAPI Redirector</p> <pre><code># The path to the ISAPI Redirector Extension, relative to the website # This must be in a virtual directory with execute privileges extension_uri=/AJP/isapi_redirect-1.2.26.dll # Full path to the log file for the ISAPI Redirector log_file=C:\wwwroot\trac.evju.biz\AJP\logs\isapi_redirect.log # Log level (debug, info, warn, error or trace) log_level=info # Full path to the workers.properties file worker_file=C:\wwwroot\trac.evju.biz\AJP\conf\workers.properties # Full path to the uriworkermap.properties file worker_mount_file=C:\wwwroot\trac.evju.biz\AJP\conf\uriworkermap.properties </code></pre> <p>workers.properties</p> <pre><code># Define 1 real worker worker.list=trac # Set properties for trac (ajp13) worker.trac.type=ajp13 worker.trac.host=localhost worker.trac.port=8009 worker.trac.socket_keepalive=0 </code></pre> <p>uriworkermap.properties</p> <pre><code>/C:\wwwroot\trac.evju.biz\irm\*=trac </code></pre> <p>Then I run into problems : </p> <ul> <li>Define a virtual directory named AJP-Connector, pointing to your bin subdirectory, with permissions to execute executables (not only scripts).</li> </ul> <p>I defined a virtual directory named AJP, pointing it to the bin subdirectory, but I can't find any way of give it execute permissions</p> <p>And the rest of the instructions obviously don't quite apply to IIS7</p> <ul> <li>Allow execution of the DLL as Web Service Extension</li> <li>In the IIS Manager, open Web Service Extensions.</li> <li>Define a new Web Service Extension called AJP-Connector (or whatever you want).</li> <li>Add C:\AJP-Connector\bin\isapi_redirect-1.2.26.dll to the required files (replace "C:\AJP-Connector" with your actual directory).</li> <li>Set extension status to Allowed. </li> </ul> <p>I tried adding the dll as a ISAPI extension, this resulted in a web.config file in the bin catalog with the following content: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;system.webServer&gt; &lt;handlers accessPolicy="Read, Execute, Script"&gt; &lt;remove name="ISAPI-dll" /&gt; &lt;add name="AJP" path="*.ajp" verb="*" modules="IsapiModule" scriptProcessor="C:\wwwroot\trac.evju.biz\AJP\bin\isapi_redirect-1.2.26.dll" resourceType="Unspecified" requireAccess="Execute" /&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>Any help appreciated. </p>
1
2008-11-20T07:33:39Z
370,488
<p>Just stumbled upon this question from an unrelated Google search. Odd how that happens... IIS7 supports FastCGI natively, I'd highly recommend using that over AJP. If you're still watching this question leave a comment and I'll follow up with details of how to install.</p>
0
2008-12-16T04:58:07Z
[ "python", "iis", "trac" ]
Getting TRAC to run on IIS7
304,567
<p>Im trying to get Trac upp and running on my IIS/w2008 server using this FAQ: <a href="http://trac.edgewall.org/wiki/TracOnWindowsIisAjp" rel="nofollow">TracOnWindowsIisAjp</a></p> <p>Everything upp until "3. Install Tomcat AJP Connector for IIS" works ok. I then define my directories as : C:\wwwroot\trac.evju.biz\AJP\, in the bin catalog I place the dll file, and 3 config files with this content:</p> <p>isapi_redirect-1.2.26.properties # Configuration file for the ISAPI Redirector</p> <pre><code># The path to the ISAPI Redirector Extension, relative to the website # This must be in a virtual directory with execute privileges extension_uri=/AJP/isapi_redirect-1.2.26.dll # Full path to the log file for the ISAPI Redirector log_file=C:\wwwroot\trac.evju.biz\AJP\logs\isapi_redirect.log # Log level (debug, info, warn, error or trace) log_level=info # Full path to the workers.properties file worker_file=C:\wwwroot\trac.evju.biz\AJP\conf\workers.properties # Full path to the uriworkermap.properties file worker_mount_file=C:\wwwroot\trac.evju.biz\AJP\conf\uriworkermap.properties </code></pre> <p>workers.properties</p> <pre><code># Define 1 real worker worker.list=trac # Set properties for trac (ajp13) worker.trac.type=ajp13 worker.trac.host=localhost worker.trac.port=8009 worker.trac.socket_keepalive=0 </code></pre> <p>uriworkermap.properties</p> <pre><code>/C:\wwwroot\trac.evju.biz\irm\*=trac </code></pre> <p>Then I run into problems : </p> <ul> <li>Define a virtual directory named AJP-Connector, pointing to your bin subdirectory, with permissions to execute executables (not only scripts).</li> </ul> <p>I defined a virtual directory named AJP, pointing it to the bin subdirectory, but I can't find any way of give it execute permissions</p> <p>And the rest of the instructions obviously don't quite apply to IIS7</p> <ul> <li>Allow execution of the DLL as Web Service Extension</li> <li>In the IIS Manager, open Web Service Extensions.</li> <li>Define a new Web Service Extension called AJP-Connector (or whatever you want).</li> <li>Add C:\AJP-Connector\bin\isapi_redirect-1.2.26.dll to the required files (replace "C:\AJP-Connector" with your actual directory).</li> <li>Set extension status to Allowed. </li> </ul> <p>I tried adding the dll as a ISAPI extension, this resulted in a web.config file in the bin catalog with the following content: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;system.webServer&gt; &lt;handlers accessPolicy="Read, Execute, Script"&gt; &lt;remove name="ISAPI-dll" /&gt; &lt;add name="AJP" path="*.ajp" verb="*" modules="IsapiModule" scriptProcessor="C:\wwwroot\trac.evju.biz\AJP\bin\isapi_redirect-1.2.26.dll" resourceType="Unspecified" requireAccess="Execute" /&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>Any help appreciated. </p>
1
2008-11-20T07:33:39Z
373,497
<p>@Jeff Mc - I'm actually looking at setting trac on IIS7 and stumbled across this thread, just as you did. I would love to know the details on using FastCGI as well as any of the other gotchas with trac on IIS7.</p>
0
2008-12-17T02:30:03Z
[ "python", "iis", "trac" ]
Getting TRAC to run on IIS7
304,567
<p>Im trying to get Trac upp and running on my IIS/w2008 server using this FAQ: <a href="http://trac.edgewall.org/wiki/TracOnWindowsIisAjp" rel="nofollow">TracOnWindowsIisAjp</a></p> <p>Everything upp until "3. Install Tomcat AJP Connector for IIS" works ok. I then define my directories as : C:\wwwroot\trac.evju.biz\AJP\, in the bin catalog I place the dll file, and 3 config files with this content:</p> <p>isapi_redirect-1.2.26.properties # Configuration file for the ISAPI Redirector</p> <pre><code># The path to the ISAPI Redirector Extension, relative to the website # This must be in a virtual directory with execute privileges extension_uri=/AJP/isapi_redirect-1.2.26.dll # Full path to the log file for the ISAPI Redirector log_file=C:\wwwroot\trac.evju.biz\AJP\logs\isapi_redirect.log # Log level (debug, info, warn, error or trace) log_level=info # Full path to the workers.properties file worker_file=C:\wwwroot\trac.evju.biz\AJP\conf\workers.properties # Full path to the uriworkermap.properties file worker_mount_file=C:\wwwroot\trac.evju.biz\AJP\conf\uriworkermap.properties </code></pre> <p>workers.properties</p> <pre><code># Define 1 real worker worker.list=trac # Set properties for trac (ajp13) worker.trac.type=ajp13 worker.trac.host=localhost worker.trac.port=8009 worker.trac.socket_keepalive=0 </code></pre> <p>uriworkermap.properties</p> <pre><code>/C:\wwwroot\trac.evju.biz\irm\*=trac </code></pre> <p>Then I run into problems : </p> <ul> <li>Define a virtual directory named AJP-Connector, pointing to your bin subdirectory, with permissions to execute executables (not only scripts).</li> </ul> <p>I defined a virtual directory named AJP, pointing it to the bin subdirectory, but I can't find any way of give it execute permissions</p> <p>And the rest of the instructions obviously don't quite apply to IIS7</p> <ul> <li>Allow execution of the DLL as Web Service Extension</li> <li>In the IIS Manager, open Web Service Extensions.</li> <li>Define a new Web Service Extension called AJP-Connector (or whatever you want).</li> <li>Add C:\AJP-Connector\bin\isapi_redirect-1.2.26.dll to the required files (replace "C:\AJP-Connector" with your actual directory).</li> <li>Set extension status to Allowed. </li> </ul> <p>I tried adding the dll as a ISAPI extension, this resulted in a web.config file in the bin catalog with the following content: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;system.webServer&gt; &lt;handlers accessPolicy="Read, Execute, Script"&gt; &lt;remove name="ISAPI-dll" /&gt; &lt;add name="AJP" path="*.ajp" verb="*" modules="IsapiModule" scriptProcessor="C:\wwwroot\trac.evju.biz\AJP\bin\isapi_redirect-1.2.26.dll" resourceType="Unspecified" requireAccess="Execute" /&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>Any help appreciated. </p>
1
2008-11-20T07:33:39Z
754,863
<p>There is detailed description on IIS7 fastCGI in this article [<a href="http://er2v.wordpress.com/2009/04/15/install_trac_on_64_bit_windows_and_run_it_under_iis7_fast_cgi/" rel="nofollow">http://er2v.wordpress.com/2009/04/15/install_trac_on_64_bit_windows_and_run_it_under_iis7_fast_cgi/</a>]article [1]</p>
0
2009-04-16T05:38:39Z
[ "python", "iis", "trac" ]
Getting TRAC to run on IIS7
304,567
<p>Im trying to get Trac upp and running on my IIS/w2008 server using this FAQ: <a href="http://trac.edgewall.org/wiki/TracOnWindowsIisAjp" rel="nofollow">TracOnWindowsIisAjp</a></p> <p>Everything upp until "3. Install Tomcat AJP Connector for IIS" works ok. I then define my directories as : C:\wwwroot\trac.evju.biz\AJP\, in the bin catalog I place the dll file, and 3 config files with this content:</p> <p>isapi_redirect-1.2.26.properties # Configuration file for the ISAPI Redirector</p> <pre><code># The path to the ISAPI Redirector Extension, relative to the website # This must be in a virtual directory with execute privileges extension_uri=/AJP/isapi_redirect-1.2.26.dll # Full path to the log file for the ISAPI Redirector log_file=C:\wwwroot\trac.evju.biz\AJP\logs\isapi_redirect.log # Log level (debug, info, warn, error or trace) log_level=info # Full path to the workers.properties file worker_file=C:\wwwroot\trac.evju.biz\AJP\conf\workers.properties # Full path to the uriworkermap.properties file worker_mount_file=C:\wwwroot\trac.evju.biz\AJP\conf\uriworkermap.properties </code></pre> <p>workers.properties</p> <pre><code># Define 1 real worker worker.list=trac # Set properties for trac (ajp13) worker.trac.type=ajp13 worker.trac.host=localhost worker.trac.port=8009 worker.trac.socket_keepalive=0 </code></pre> <p>uriworkermap.properties</p> <pre><code>/C:\wwwroot\trac.evju.biz\irm\*=trac </code></pre> <p>Then I run into problems : </p> <ul> <li>Define a virtual directory named AJP-Connector, pointing to your bin subdirectory, with permissions to execute executables (not only scripts).</li> </ul> <p>I defined a virtual directory named AJP, pointing it to the bin subdirectory, but I can't find any way of give it execute permissions</p> <p>And the rest of the instructions obviously don't quite apply to IIS7</p> <ul> <li>Allow execution of the DLL as Web Service Extension</li> <li>In the IIS Manager, open Web Service Extensions.</li> <li>Define a new Web Service Extension called AJP-Connector (or whatever you want).</li> <li>Add C:\AJP-Connector\bin\isapi_redirect-1.2.26.dll to the required files (replace "C:\AJP-Connector" with your actual directory).</li> <li>Set extension status to Allowed. </li> </ul> <p>I tried adding the dll as a ISAPI extension, this resulted in a web.config file in the bin catalog with the following content: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;system.webServer&gt; &lt;handlers accessPolicy="Read, Execute, Script"&gt; &lt;remove name="ISAPI-dll" /&gt; &lt;add name="AJP" path="*.ajp" verb="*" modules="IsapiModule" scriptProcessor="C:\wwwroot\trac.evju.biz\AJP\bin\isapi_redirect-1.2.26.dll" resourceType="Unspecified" requireAccess="Execute" /&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>Any help appreciated. </p>
1
2008-11-20T07:33:39Z
845,584
<p>Have a Look on following Link: <a href="http://neosmart.net/blog/2006/configuring-jsp-for-iis/" rel="nofollow">http://neosmart.net/blog/2006/configuring-jsp-for-iis/</a></p> <p>with this I get it running.</p>
1
2009-05-10T16:09:57Z
[ "python", "iis", "trac" ]
The best way to invoke methods in Python class declarations?
304,655
<p>Say I am declaring a class <code>C</code> and a few of the declarations are very similar. I'd like to use a function <code>f</code> to reduce code repetition for these declarations. It's possible to just declare and use <code>f</code> as usual:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... w = f(42) ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.w '&lt;42&gt;' &gt;&gt;&gt; C.f(4) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unbound method f() must be called with C instance as first argument (got int instance instead) </code></pre> <p>Oops! I've inadvertently exposed <code>f</code> to the outside world, but it doesn't take a <code>self</code> argument (and can't for obvious reasons). One possibility would be to <code>del</code> the function after I use it:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... del f ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.f Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: type object 'C' has no attribute 'f' </code></pre> <p>But what if I want to use <code>f</code> again later, after the declaration? It won't do to delete the function. I could make it "private" (i.e., prefix its name with <code>__</code>) and give it the <code>@staticmethod</code> treatment, but invoking <code>staticmethod</code> objects through abnormal channels gets very funky:</p> <pre><code>&gt;&gt;&gt; class C(object): ... @staticmethod ... def __f(num): ... return '&lt;' + str(num) + '&gt;' ... v = __f.__get__(1)(9) # argument to __get__ is ignored... ... &gt;&gt;&gt; C.v '&lt;9&gt;' </code></pre> <p>I have to use the above craziness because <code>staticmethod</code> objects, which are descriptors, are not themselves callable. I need to recover the function wrapped by the <code>staticmethod</code> object before I can call it.</p> <p>There has got to be a better way to do this. How can I cleanly declare a function in a class, use it during its declaration, and also use it later from within the class? Should I even be doing this?</p>
4
2008-11-20T08:40:40Z
304,679
<p>Quite simply, the solution is that f does not need to be a member of the class. I am assuming that your thought-process has gone through a Javaish language filter causing the mental block. It goes a little something like this:</p> <pre><code>def f(n): return '&lt;' + str(num) + '&gt;' class C(object): v = f(9) w = f(42) </code></pre> <p>Then when you want to use f again, just use it</p> <pre><code>&gt;&gt;&gt; f(4) '&lt;4&gt;' </code></pre> <p>I think the moral of the tale is "In Python, you don't <em>have</em> to force everything into a class". </p>
14
2008-11-20T08:50:18Z
[ "python", "class", "declaration", "static-methods", "invocation" ]
The best way to invoke methods in Python class declarations?
304,655
<p>Say I am declaring a class <code>C</code> and a few of the declarations are very similar. I'd like to use a function <code>f</code> to reduce code repetition for these declarations. It's possible to just declare and use <code>f</code> as usual:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... w = f(42) ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.w '&lt;42&gt;' &gt;&gt;&gt; C.f(4) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unbound method f() must be called with C instance as first argument (got int instance instead) </code></pre> <p>Oops! I've inadvertently exposed <code>f</code> to the outside world, but it doesn't take a <code>self</code> argument (and can't for obvious reasons). One possibility would be to <code>del</code> the function after I use it:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... del f ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.f Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: type object 'C' has no attribute 'f' </code></pre> <p>But what if I want to use <code>f</code> again later, after the declaration? It won't do to delete the function. I could make it "private" (i.e., prefix its name with <code>__</code>) and give it the <code>@staticmethod</code> treatment, but invoking <code>staticmethod</code> objects through abnormal channels gets very funky:</p> <pre><code>&gt;&gt;&gt; class C(object): ... @staticmethod ... def __f(num): ... return '&lt;' + str(num) + '&gt;' ... v = __f.__get__(1)(9) # argument to __get__ is ignored... ... &gt;&gt;&gt; C.v '&lt;9&gt;' </code></pre> <p>I have to use the above craziness because <code>staticmethod</code> objects, which are descriptors, are not themselves callable. I need to recover the function wrapped by the <code>staticmethod</code> object before I can call it.</p> <p>There has got to be a better way to do this. How can I cleanly declare a function in a class, use it during its declaration, and also use it later from within the class? Should I even be doing this?</p>
4
2008-11-20T08:40:40Z
305,022
<p>This is one possibility:</p> <pre><code>class _C: # Do most of the function definitions in here @classmethod def f(cls): return 'boo' class C(_C): # Do the subsequent decoration in here v = _C.f() </code></pre>
2
2008-11-20T11:37:17Z
[ "python", "class", "declaration", "static-methods", "invocation" ]
The best way to invoke methods in Python class declarations?
304,655
<p>Say I am declaring a class <code>C</code> and a few of the declarations are very similar. I'd like to use a function <code>f</code> to reduce code repetition for these declarations. It's possible to just declare and use <code>f</code> as usual:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... w = f(42) ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.w '&lt;42&gt;' &gt;&gt;&gt; C.f(4) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unbound method f() must be called with C instance as first argument (got int instance instead) </code></pre> <p>Oops! I've inadvertently exposed <code>f</code> to the outside world, but it doesn't take a <code>self</code> argument (and can't for obvious reasons). One possibility would be to <code>del</code> the function after I use it:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... del f ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.f Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: type object 'C' has no attribute 'f' </code></pre> <p>But what if I want to use <code>f</code> again later, after the declaration? It won't do to delete the function. I could make it "private" (i.e., prefix its name with <code>__</code>) and give it the <code>@staticmethod</code> treatment, but invoking <code>staticmethod</code> objects through abnormal channels gets very funky:</p> <pre><code>&gt;&gt;&gt; class C(object): ... @staticmethod ... def __f(num): ... return '&lt;' + str(num) + '&gt;' ... v = __f.__get__(1)(9) # argument to __get__ is ignored... ... &gt;&gt;&gt; C.v '&lt;9&gt;' </code></pre> <p>I have to use the above craziness because <code>staticmethod</code> objects, which are descriptors, are not themselves callable. I need to recover the function wrapped by the <code>staticmethod</code> object before I can call it.</p> <p>There has got to be a better way to do this. How can I cleanly declare a function in a class, use it during its declaration, and also use it later from within the class? Should I even be doing this?</p>
4
2008-11-20T08:40:40Z
305,069
<p>Extending <a href="http://stackoverflow.com/questions/304655/the-best-way-to-invoke-methods-in-python-class-declarations#304679">Ali A</a>'s answer, if you really want to avoid f in the module namespace (and using a non-exported name like _f, or setting __all__ isn't sufficient), then you could achieve this by creating the class within a closure.</p> <pre><code>def create_C(): def f(num): return '&lt;' + str(num) + '&gt;' class C(object): v = f(9) def method_using_f(self, x): return f(x*2) return C C=create_C() del create_C </code></pre> <p>This way C has access to f within its definition and methods, but nothing else does (barring fairly involved introspection of its methods (<code>C.method_using_f.im_func.func_closure</code>))</p> <p>This is probably overkill for most purposes though - documenting that f is internal by using the "_" prefix nameing convention should generally be sufficient.</p> <p><strong>[Edit]</strong> One other option is to hold a reference to the pre-wrapped function object in the methods you wish to use it in. For example, by setting it as a default argument:</p> <pre><code>class C(object): def f(num): return '&lt;' + str(num) + '&gt;' v = f(9) def method_using_f(self, x, f=f): return f(x*2) del f </code></pre> <p>(Though I think the closure approach is probably better)</p>
3
2008-11-20T12:00:16Z
[ "python", "class", "declaration", "static-methods", "invocation" ]
The best way to invoke methods in Python class declarations?
304,655
<p>Say I am declaring a class <code>C</code> and a few of the declarations are very similar. I'd like to use a function <code>f</code> to reduce code repetition for these declarations. It's possible to just declare and use <code>f</code> as usual:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... w = f(42) ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.w '&lt;42&gt;' &gt;&gt;&gt; C.f(4) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unbound method f() must be called with C instance as first argument (got int instance instead) </code></pre> <p>Oops! I've inadvertently exposed <code>f</code> to the outside world, but it doesn't take a <code>self</code> argument (and can't for obvious reasons). One possibility would be to <code>del</code> the function after I use it:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... del f ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.f Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: type object 'C' has no attribute 'f' </code></pre> <p>But what if I want to use <code>f</code> again later, after the declaration? It won't do to delete the function. I could make it "private" (i.e., prefix its name with <code>__</code>) and give it the <code>@staticmethod</code> treatment, but invoking <code>staticmethod</code> objects through abnormal channels gets very funky:</p> <pre><code>&gt;&gt;&gt; class C(object): ... @staticmethod ... def __f(num): ... return '&lt;' + str(num) + '&gt;' ... v = __f.__get__(1)(9) # argument to __get__ is ignored... ... &gt;&gt;&gt; C.v '&lt;9&gt;' </code></pre> <p>I have to use the above craziness because <code>staticmethod</code> objects, which are descriptors, are not themselves callable. I need to recover the function wrapped by the <code>staticmethod</code> object before I can call it.</p> <p>There has got to be a better way to do this. How can I cleanly declare a function in a class, use it during its declaration, and also use it later from within the class? Should I even be doing this?</p>
4
2008-11-20T08:40:40Z
305,104
<p>Let's begin from the beginning.</p> <p>"declare a function in a class, use it during its declaration, and also use it later from within the class"</p> <p>Sorry. Can't be done. "In a class" contradicts "used during declaration".</p> <ul> <li>In a class means created as part of the declaration.</li> <li>Used during declaration means it exists outside the class. Often as a meta class. However, there are other ways.</li> </ul> <p>It's not clear what C.w and C.v are supposed to be. Are they just strings? If so, an external function <code>f</code> is the best solution. The "not clutter the namespace" is a bit specious. After all, you want to use it again.</p> <p>It's in the same module as C. That's why Python has modules. It binds the function and class together.</p> <pre><code>import myCmod myCmod.C.w myCmod.C.v myCmod.f(42) </code></pre> <p>If w and v aren't simple strings, there's a really good solution that gives a lot of flexibility.</p> <p>Generally, for class-level ("static") variables like this, we can use other classes. It's not possible to completely achieve the desired API, but this is close.</p> <pre><code>&gt;&gt;&gt; class F(object): def __init__( self, num ): self.value= num self.format= "&lt;%d&gt;" % ( num, ) &gt;&gt;&gt; class C(object): w= F(42) v= F(9) &gt;&gt;&gt; C.w &lt;__main__.F object at 0x00C58C30&gt; &gt;&gt;&gt; C.w.format '&lt;42&gt;' &gt;&gt;&gt; C.v.format '&lt;9&gt;' </code></pre> <p>The advantage of this is that F is a proper, first-class thing that can be extended. Not a "hidden" thing that we're trying to avoid exposing. It's a fact of life, so we might as well follow the Open/Closed principle and make it open to extension.</p>
0
2008-11-20T12:15:14Z
[ "python", "class", "declaration", "static-methods", "invocation" ]
The best way to invoke methods in Python class declarations?
304,655
<p>Say I am declaring a class <code>C</code> and a few of the declarations are very similar. I'd like to use a function <code>f</code> to reduce code repetition for these declarations. It's possible to just declare and use <code>f</code> as usual:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... w = f(42) ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.w '&lt;42&gt;' &gt;&gt;&gt; C.f(4) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unbound method f() must be called with C instance as first argument (got int instance instead) </code></pre> <p>Oops! I've inadvertently exposed <code>f</code> to the outside world, but it doesn't take a <code>self</code> argument (and can't for obvious reasons). One possibility would be to <code>del</code> the function after I use it:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... del f ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.f Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: type object 'C' has no attribute 'f' </code></pre> <p>But what if I want to use <code>f</code> again later, after the declaration? It won't do to delete the function. I could make it "private" (i.e., prefix its name with <code>__</code>) and give it the <code>@staticmethod</code> treatment, but invoking <code>staticmethod</code> objects through abnormal channels gets very funky:</p> <pre><code>&gt;&gt;&gt; class C(object): ... @staticmethod ... def __f(num): ... return '&lt;' + str(num) + '&gt;' ... v = __f.__get__(1)(9) # argument to __get__ is ignored... ... &gt;&gt;&gt; C.v '&lt;9&gt;' </code></pre> <p>I have to use the above craziness because <code>staticmethod</code> objects, which are descriptors, are not themselves callable. I need to recover the function wrapped by the <code>staticmethod</code> object before I can call it.</p> <p>There has got to be a better way to do this. How can I cleanly declare a function in a class, use it during its declaration, and also use it later from within the class? Should I even be doing this?</p>
4
2008-11-20T08:40:40Z
305,241
<p>I believe you are trying to do this:</p> <pre><code>class C(): ... class F(): ... def __call__(self,num): ... return "&lt;"+str(num)+"&gt;" ... f=F() ... v=f(9) &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.f(25) '&lt;25&gt;' &gt;&gt;&gt; </code></pre> <p>Maybe there is better or more pythonic solution...</p> <blockquote> <p>"declare a function in a class, use it during its declaration, and also use it later from within the class"</p> <p>Sorry. Can't be done.</p> </blockquote> <p>"Can't be done" doesn't seem to get along with Python</p>
2
2008-11-20T13:09:46Z
[ "python", "class", "declaration", "static-methods", "invocation" ]
The best way to invoke methods in Python class declarations?
304,655
<p>Say I am declaring a class <code>C</code> and a few of the declarations are very similar. I'd like to use a function <code>f</code> to reduce code repetition for these declarations. It's possible to just declare and use <code>f</code> as usual:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... w = f(42) ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.w '&lt;42&gt;' &gt;&gt;&gt; C.f(4) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unbound method f() must be called with C instance as first argument (got int instance instead) </code></pre> <p>Oops! I've inadvertently exposed <code>f</code> to the outside world, but it doesn't take a <code>self</code> argument (and can't for obvious reasons). One possibility would be to <code>del</code> the function after I use it:</p> <pre><code>&gt;&gt;&gt; class C(object): ... def f(num): ... return '&lt;' + str(num) + '&gt;' ... v = f(9) ... del f ... &gt;&gt;&gt; C.v '&lt;9&gt;' &gt;&gt;&gt; C.f Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: type object 'C' has no attribute 'f' </code></pre> <p>But what if I want to use <code>f</code> again later, after the declaration? It won't do to delete the function. I could make it "private" (i.e., prefix its name with <code>__</code>) and give it the <code>@staticmethod</code> treatment, but invoking <code>staticmethod</code> objects through abnormal channels gets very funky:</p> <pre><code>&gt;&gt;&gt; class C(object): ... @staticmethod ... def __f(num): ... return '&lt;' + str(num) + '&gt;' ... v = __f.__get__(1)(9) # argument to __get__ is ignored... ... &gt;&gt;&gt; C.v '&lt;9&gt;' </code></pre> <p>I have to use the above craziness because <code>staticmethod</code> objects, which are descriptors, are not themselves callable. I need to recover the function wrapped by the <code>staticmethod</code> object before I can call it.</p> <p>There has got to be a better way to do this. How can I cleanly declare a function in a class, use it during its declaration, and also use it later from within the class? Should I even be doing this?</p>
4
2008-11-20T08:40:40Z
307,271
<p>One option: write a better <code>staticmethod</code>:</p> <pre><code>class staticfunc(object): def __init__(self, func): self.func = func def __call__(self, *args, **kw): return self.func(*args, **kw) def __repr__(self): return 'staticfunc(%r)' % self.func </code></pre>
1
2008-11-20T23:21:16Z
[ "python", "class", "declaration", "static-methods", "invocation" ]
Adobe Flash and Python
304,779
<p>Is it possible to use <a href="http://www.python.org/" rel="nofollow">CPython</a> to develop Adobe Flash based applications?</p>
3
2008-11-20T09:33:44Z
304,817
<p>I guess it would be possible to compile the python interpreter to flash bytecode using this <a href="http://labs.adobe.com/downloads/alchemy.html" rel="nofollow">http://labs.adobe.com/downloads/alchemy.html</a> and then use it to run python programs. But apart from that the answer is no.</p>
1
2008-11-20T09:54:53Z
[ "python", "flash", "flashdevelop" ]
Adobe Flash and Python
304,779
<p>Is it possible to use <a href="http://www.python.org/" rel="nofollow">CPython</a> to develop Adobe Flash based applications?</p>
3
2008-11-20T09:33:44Z
304,905
<p>You can try <a href="http://www.libming.org/" rel="nofollow">ming</a>, a library for generating Macromedia Flash files (.swf).</p> <p>It's written in C but it has wrappers that allow it to be used in C++, PHP, Python, Ruby, and Perl. </p>
3
2008-11-20T10:36:30Z
[ "python", "flash", "flashdevelop" ]
Adobe Flash and Python
304,779
<p>Is it possible to use <a href="http://www.python.org/" rel="nofollow">CPython</a> to develop Adobe Flash based applications?</p>
3
2008-11-20T09:33:44Z
791,749
<p>take a look at Flex PyPy: <a href="http://code.google.com/p/flex-pypy/" rel="nofollow">http://code.google.com/p/flex-pypy/</a></p>
2
2009-04-26T22:43:51Z
[ "python", "flash", "flashdevelop" ]
What do I use on linux to make a python program executable
304,883
<p>I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.</p>
39
2008-11-20T10:27:57Z
304,896
<p>Just put this in the first line of your script :</p> <pre><code>#!/usr/bin/env python </code></pre> <p>Make the file executable with</p> <pre><code>chmod +x myfile.py </code></pre> <p>Execute with</p> <pre><code>./myfile.py </code></pre>
80
2008-11-20T10:32:27Z
[ "python", "linux", "file-permissions" ]
What do I use on linux to make a python program executable
304,883
<p>I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.</p>
39
2008-11-20T10:27:57Z
14,230,576
<p>Putting these lines at the starting of the code will tell your operating systems to look up the binary program needed for the execution of the python script i.e it is the python interpreter.</p> <p>So it depends on your operating system where it keeps the python interpreter. As I have Ubuntu as operating system it keeps the python interpreter in <code>/usr/bin/python</code> so I have to write this line at the starting of my python script;</p> <pre><code>#!/usr/bin/python </code></pre> <p>After completing and saving your code</p> <ol> <li><p>Start your command terminal</p></li> <li><p>Make sure the script lies in your present working directory </p></li> <li><p>Type <code>chmod +x script_name.py</code></p></li> <li><p>Now you can start the script by clicking the script. An alert box will appear; press "Run" or "Run in Terminal" in the alert box; or, at the terminal prompt, type <code>./script_name.py</code></p></li> </ol>
2
2013-01-09T07:55:36Z
[ "python", "linux", "file-permissions" ]
What do I use on linux to make a python program executable
304,883
<p>I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.</p>
39
2008-11-20T10:27:57Z
14,232,463
<p>If you want to obtain a stand-alone binary application in Python try to use a tool like py2exe or <a href="http://www.pyinstaller.org/">PyInstaller</a>.</p>
8
2013-01-09T09:53:50Z
[ "python", "linux", "file-permissions" ]
What do I use on linux to make a python program executable
304,883
<p>I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.</p>
39
2008-11-20T10:27:57Z
27,448,666
<p>You can use PyInstaller. It generates a build dist so you can execute it as a single "binary" file.</p> <p><a href="http://pythonhosted.org/PyInstaller/#using-pyinstaller" rel="nofollow">http://pythonhosted.org/PyInstaller/#using-pyinstaller</a></p> <p>Python 3 has the native option of create a build dist also:</p> <p><a href="https://docs.python.org/3/distutils/builtdist.html" rel="nofollow">https://docs.python.org/3/distutils/builtdist.html</a></p>
1
2014-12-12T17:12:12Z
[ "python", "linux", "file-permissions" ]
What do I use on linux to make a python program executable
304,883
<p>I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.</p>
39
2008-11-20T10:27:57Z
39,980,094
<p>Another way to do it could be by creating an alias. For example in terminal write:</p> <pre><code>alias printhello='python /home/hello_world.py' </code></pre> <p>Writing <code>printhello</code> will run hello_world.py, but this is only temporary. To make aliases permanent, you have to add them to bashrc, you can edit it by writing this in the terminal:</p> <pre><code>gedit ~/.bashrc </code></pre>
0
2016-10-11T14:49:37Z
[ "python", "linux", "file-permissions" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
305,388
<p>I think what I would do is check whether the object has certain methods that indicate it is a sequence. I'm not sure if there is an official definition of what makes a sequence. The best I can think of is, it must support slicing. So you could say:</p> <pre><code>is_sequence = '__getslice__' in dir(X) </code></pre> <p>You might also check for the particular functionality you're going to be using.</p> <p>As pi pointed out in the comment, one issue is that a string is a sequence, but you probably don't want to treat it as one. You could add an explicit test that the type is not str.</p>
1
2008-11-20T14:05:04Z
[ "python", "types", "sequences" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
305,397
<p>You could pass your parameter in the built-in len() function and check whether this causes an error. As others said, the string type requires special handling.</p> <p>According to the documentation the len function can accept a sequence (string, list, tuple) or a dictionary.</p> <p>You could check that an object is a string with the following code:</p> <pre><code>x.__class__ == "".__class__ </code></pre>
-1
2008-11-20T14:08:25Z
[ "python", "types", "sequences" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
305,417
<p><strong>Revised answer:</strong> </p> <p>I don't know if your idea of "sequence" matches what the Python manuals call a "<a href="https://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange" rel="nofollow">Sequence Type</a>", but in case it does, you should look for the __Contains__ method. That is the method Python uses to implement the check "if something in object:"</p> <pre><code>if hasattr(X, '__contains__'): print "X is a sequence" </code></pre> <p><strong>My original answer:</strong></p> <p>I would check if the object that you received implements an iterator interface:</p> <pre><code>if hasattr(X, '__iter__'): print "X is a sequence" </code></pre> <p>For me, that's the closest match to your definition of sequence since that would allow you to do something like:</p> <pre><code>for each in X: print each </code></pre>
1
2008-11-20T14:18:29Z
[ "python", "types", "sequences" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
305,526
<p>In cases like this, I prefer to just always take the sequence type or always take the scalar. Strings won't be the only types that would behave poorly in this setup; rather, any type that has an aggregate use and allows iteration over its parts might misbehave.</p>
3
2008-11-20T14:52:34Z
[ "python", "types", "sequences" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
305,587
<p>Sequences are described here: <a href="https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange" rel="nofollow">https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange</a></p> <p>So sequences are not the same as iterable objects. I think sequence must implement <code>__getitem__</code>, whereas iterable objects must implement <code>__iter__</code>. So for example string are sequences and don't implement <code>__iter__</code>, xrange objects are sequences and don't implement <code>__getslice__</code>.</p> <p>But from what you seen to want to do, I'm not sure you want sequences, but rather iterable objects. So go for <code>hasattr("__getitem__", X)</code> you want sequences, but go rather <code>hasattr("__iter__", X)</code> if you don't want strings for example.</p>
4
2008-11-20T15:12:49Z
[ "python", "types", "sequences" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
305,695
<p>The simplest method would be to check if you can turn it into an iterator. ie</p> <pre><code>try: it = iter(X) # Iterable except TypeError: # Not iterable </code></pre> <p>If you need to ensure that it's a restartable or random access sequence (ie not a generator etc), this approach won't be sufficient however.</p> <p>As others have noted, strings are also iterable, so if you need so exclude them (particularly important if recursing through items, as list(iter('a')) gives ['a'] again, then you may need to specifically exclude them with:</p> <pre><code> if not isinstance(X, basestring) </code></pre>
3
2008-11-20T15:39:32Z
[ "python", "types", "sequences" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
305,997
<p>You're asking the wrong question. You don't try to detect types in Python; you detect behavior.</p> <ol> <li>Write another function that handles a single value. (let's call it _use_single_val).</li> <li>Write one function that handles a sequence parameter. (let's call it _use_sequence).</li> <li>Write a third parent function that calls the two above. (call it use_seq_or_val). Surround each call with an exception handler to catch an invalid parameter (i.e. not single value or sequence).</li> <li>Write unit tests to pass correct &amp; incorrect parameters to the parent function to make sure it catches the exceptions properly.</li> </ol> <pre><code> def _use_single_val(v): print v + 1 # this will fail if v is not a value type def _use_sequence(s): print s[0] # this will fail if s is not indexable def use_seq_or_val(item): try: _use_single_val(item) except TypeError: pass try: _use_sequence(item) except TypeError: pass raise TypeError, "item not a single value or sequence" </code></pre> <p>EDIT: Revised to handle the "sequence or single value" asked about in the question. </p>
0
2008-11-20T16:46:48Z
[ "python", "types", "sequences" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
306,222
<p>As of 2.6, use <a href="http://docs.python.org/library/abc.html#module-abc">abstract base classes</a>.</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; isinstance([], collections.Sequence) True &gt;&gt;&gt; isinstance(0, collections.Sequence) False </code></pre> <p>Furthermore ABC's can be customized to account for exceptions, such as not considering strings to be sequences. Here an example:</p> <pre><code>import abc import collections class Atomic(object): __metaclass__ = abc.ABCMeta @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented Atomic.register(basestring) </code></pre> <p>After registration the <strong>Atomic</strong> class can be used with <strong>isinstance</strong> and <strong>issubclass</strong>:</p> <pre><code>assert isinstance("hello", Atomic) == True </code></pre> <p>This is still much better than a hard-coded list, because you only need to register the exceptions to the rule, and external users of the code can register their own.</p> <p>Note that in <strong>Python 3</strong> the syntax for specifying metaclasses changed and the <code>basestring</code> abstract superclass was removed, which requires something like the following to be used instead:</p> <pre><code>class Atomic(metaclass=abc.ABCMeta): @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented Atomic.register(str) </code></pre> <p>If desired, it's possible to write code which is compatible both both Python 2.6+ <em>and</em> 3.x, but doing so requires using a slightly more complicated technique which dynamically creates the needed abstract base class, thereby avoiding syntax errors due to the metaclass syntax difference. This is essentially the same as what Benjamin Peterson's <a href="http://pythonhosted.org/six/">six</a> module's<a href="http://pythonhosted.org/six/#six.with_metaclass"><code>with_metaclass()</code></a>function does.</p> <pre><code>class _AtomicBase(object): @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented class Atomic(abc.ABCMeta("NewMeta", (_AtomicBase,), {})): pass try: unicode = unicode except NameError: # 'unicode' is undefined, assume Python &gt;= 3 Atomic.register(str) # str includes unicode in Py3, make both Atomic Atomic.register(bytes) # bytes will also be considered Atomic (optional) else: # basestring is the abstract superclass of both str and unicode types Atomic.register(basestring) # make both types of strings Atomic </code></pre> <p>In versions before 2.6, there are type checkers in the<code>operator</code>module.</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; import operator &gt;&gt;&gt; operator.isSequenceType([]) True &gt;&gt;&gt; operator.isSequenceType(0) False </code></pre>
18
2008-11-20T17:52:46Z
[ "python", "types", "sequences" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
312,368
<p>I'm new here so I don't know what's the correct way to do it. I want to answer my answers:</p> <p>The problem with all of the above mentioned ways is that <strong><code>str</code></strong> is considered a sequence (it's iterable, has <code>__getitem__</code>, etc.) yet it's usually treated as a single item.</p> <p>For example, a function may accept an argument that can either be a filename or a list of filenames. What's the most Pythonic way for the function to detect the first from the latter?</p> <p>Should I post this as a new question? Edit the original one?</p>
2
2008-11-23T10:32:51Z
[ "python", "types", "sequences" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
331,826
<p>IMHO, the python way is to pass the list as *list. As in:</p> <pre><code>myfunc(item) myfunc(*items) </code></pre>
4
2008-12-01T18:59:11Z
[ "python", "types", "sequences" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
340,801
<p>If strings are the problem, detect a sequence and filter out the special case of strings:</p> <pre><code>def is_iterable(x): if type(x) == str: return False try: iter(x) return True except TypeError: return False </code></pre>
1
2008-12-04T14:43:24Z
[ "python", "types", "sequences" ]
Correct way to detect sequence parameter?
305,359
<p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p> <p><code>type(X) in (list, tuple)</code></p> <p>but there may be other sequence types I'm not aware of, and no common base class.</p> <p>-N.</p> <p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
17
2008-11-20T13:52:44Z
425,567
<blockquote> <p>The problem with all of the above mentioned ways is that str is considered a sequence (it's iterable, has <strong>getitem</strong>, etc.) yet it's usually treated as a single item.</p> <p>For example, a function may accept an argument that can either be a filename or a list of filenames. What's the most Pythonic way for the function to detect the first from the latter?</p> </blockquote> <p>Based on the revised question, it sounds like what you want is something more like:</p> <pre><code>def to_sequence(arg): ''' determine whether an arg should be treated as a "unit" or a "sequence" if it's a unit, return a 1-tuple with the arg ''' def _multiple(x): return hasattr(x,"__iter__") if _multiple(arg): return arg else: return (arg,) &gt;&gt;&gt; to_sequence("a string") ('a string',) &gt;&gt;&gt; to_sequence( (1,2,3) ) (1, 2, 3) &gt;&gt;&gt; to_sequence( xrange(5) ) xrange(5) </code></pre> <p>This isn't guaranteed to handle <em>all</em> types, but it handles the cases you mention quite well, and should do the right thing for most of the built-in types.</p> <p>When using it, make sure whatever receives the output of this can handle iterables.</p>
5
2009-01-08T19:35:43Z
[ "python", "types", "sequences" ]
List of tables, db schema, dump etc using the Python sqlite3 API
305,378
<p>For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:</p> <pre><code>.tables .dump </code></pre> <p>using the Python sqlite3 API. </p> <p>Is there anything like that?</p>
64
2008-11-20T14:00:23Z
305,395
<p>I'm not familiar with the Python API but you can always use</p> <pre><code>SELECT * FROM sqlite_master; </code></pre>
12
2008-11-20T14:07:20Z
[ "python", "api", "sqlite", "dump" ]
List of tables, db schema, dump etc using the Python sqlite3 API
305,378
<p>For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:</p> <pre><code>.tables .dump </code></pre> <p>using the Python sqlite3 API. </p> <p>Is there anything like that?</p>
64
2008-11-20T14:00:23Z
305,639
<p>You can fetch the list of tables and schemata by querying the SQLITE_MASTER table:</p> <pre><code>sqlite&gt; .tab job snmptarget t1 t2 t3 sqlite&gt; select name from sqlite_master where type = 'table'; job t1 t2 snmptarget t3 sqlite&gt; .schema job CREATE TABLE job ( id INTEGER PRIMARY KEY, data VARCHAR ); sqlite&gt; select sql from sqlite_master where type = 'table' and name = 'job'; CREATE TABLE job ( id INTEGER PRIMARY KEY, data VARCHAR ) </code></pre>
58
2008-11-20T15:26:39Z
[ "python", "api", "sqlite", "dump" ]
List of tables, db schema, dump etc using the Python sqlite3 API
305,378
<p>For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:</p> <pre><code>.tables .dump </code></pre> <p>using the Python sqlite3 API. </p> <p>Is there anything like that?</p>
64
2008-11-20T14:00:23Z
306,783
<p>Check out <a href="http://svn.python.org/projects/python/trunk/Lib/sqlite3/dump.py" rel="nofollow">here</a> for dump. It seems there is a dump function in the library sqlite3.</p>
1
2008-11-20T20:38:33Z
[ "python", "api", "sqlite", "dump" ]
List of tables, db schema, dump etc using the Python sqlite3 API
305,378
<p>For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:</p> <pre><code>.tables .dump </code></pre> <p>using the Python sqlite3 API. </p> <p>Is there anything like that?</p>
64
2008-11-20T14:00:23Z
601,222
<p>Apparently the version of sqlite3 included in Python 2.6 has this ability: <a href="http://docs.python.org/dev/library/sqlite3.html">http://docs.python.org/dev/library/sqlite3.html</a></p> <pre><code># Convert file existing_db.db to SQL dump file dump.sql import sqlite3, os con = sqlite3.connect('existing_db.db') with open('dump.sql', 'w') as f: for line in con.iterdump(): f.write('%s\n' % line) </code></pre>
14
2009-03-02T03:47:31Z
[ "python", "api", "sqlite", "dump" ]
List of tables, db schema, dump etc using the Python sqlite3 API
305,378
<p>For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:</p> <pre><code>.tables .dump </code></pre> <p>using the Python sqlite3 API. </p> <p>Is there anything like that?</p>
64
2008-11-20T14:00:23Z
10,746,045
<p>In Python:</p> <pre><code>con = sqlite3.connect('database.db') cursor = con.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") print(cursor.fetchall()) </code></pre> <p>Watch out for my other <a href="http://stackoverflow.com/a/33100538/236830">answer</a>. There is a much faster way using pandas.</p>
94
2012-05-24T22:15:42Z
[ "python", "api", "sqlite", "dump" ]
List of tables, db schema, dump etc using the Python sqlite3 API
305,378
<p>For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:</p> <pre><code>.tables .dump </code></pre> <p>using the Python sqlite3 API. </p> <p>Is there anything like that?</p>
64
2008-11-20T14:00:23Z
27,392,638
<p>After a lot of fiddling I found a better answer at <a href="http://www.sqlite.org/pragma.html#pragma_table_info" rel="nofollow">sqlite docs</a> for listing the metadata for the table, even attached databases. </p> <pre><code>meta = cursor.execute("PRAGMA table_info('Job')") for r in meta: print r </code></pre> <p>The key information is to prefix table_info, not my_table with the attachment handle name.</p>
0
2014-12-10T03:01:18Z
[ "python", "api", "sqlite", "dump" ]
List of tables, db schema, dump etc using the Python sqlite3 API
305,378
<p>For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:</p> <pre><code>.tables .dump </code></pre> <p>using the Python sqlite3 API. </p> <p>Is there anything like that?</p>
64
2008-11-20T14:00:23Z
29,618,411
<p>I've implemented a sqlite table schema parser in PHP, you may check here: <a href="https://github.com/c9s/LazyRecord/blob/master/src/LazyRecord/TableParser/SqliteTableDefinitionParser.php" rel="nofollow">https://github.com/c9s/LazyRecord/blob/master/src/LazyRecord/TableParser/SqliteTableDefinitionParser.php</a></p> <p>You can use this definition parser to parse the definitions like the code below:</p> <pre><code>$parser = new SqliteTableDefinitionParser; $parser-&gt;parseColumnDefinitions('x INTEGER PRIMARY KEY, y DOUBLE, z DATETIME default \'2011-11-10\', name VARCHAR(100)'); </code></pre>
0
2015-04-14T02:57:17Z
[ "python", "api", "sqlite", "dump" ]
List of tables, db schema, dump etc using the Python sqlite3 API
305,378
<p>For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:</p> <pre><code>.tables .dump </code></pre> <p>using the Python sqlite3 API. </p> <p>Is there anything like that?</p>
64
2008-11-20T14:00:23Z
33,100,538
<p>The FASTEST way of doing this in python is using Pandas (version 0.16 and up).</p> <p>Dump one table:</p> <pre><code>db = sqlite3.connect('database.db') table = pd.read_sql_query("SELECT * from table_name", db) table.to_csv(table_name + '.csv', index_label='index') </code></pre> <p>Dump all tables:</p> <pre><code>import sqlite3 import pandas as pd def to_csv(): db = sqlite3.connect('database.db') cursor = db.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = cursor.fetchall() for table_name in tables: table_name = table_name[0] table = pd.read_sql_query("SELECT * from %s" % table_name, db) table.to_csv(table_name + '.csv', index_label='index') </code></pre>
12
2015-10-13T10:38:59Z
[ "python", "api", "sqlite", "dump" ]
List of tables, db schema, dump etc using the Python sqlite3 API
305,378
<p>For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:</p> <pre><code>.tables .dump </code></pre> <p>using the Python sqlite3 API. </p> <p>Is there anything like that?</p>
64
2008-11-20T14:00:23Z
33,330,898
<pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- if __name__ == "__main__": import sqlite3 dbname = './db/database.db' try: print "INITILIZATION..." con = sqlite3.connect(dbname) cursor = con.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = cursor.fetchall() for tbl in tables: print "\n######## "+tbl[0]+" ########" cursor.execute("SELECT * FROM "+tbl[0]+";") rows = cursor.fetchall() for row in rows: print row print(cursor.fetchall()) except KeyboardInterrupt: print "\nClean Exit By user" finally: print "\nFinally" </code></pre>
0
2015-10-25T14:38:19Z
[ "python", "api", "sqlite", "dump" ]
Python printing the word
305,422
<p>If any one can help me with Python code: If I input a letter, How can I print all the words start with that word?</p>
1
2008-11-20T14:20:16Z
305,430
<p>There are many ways of doing this, e.g.:</p> <pre><code>words = ["zwei", "peanuts", "were", "walking", "down", "the", "strasse"] letter = "w" output = [x for x in words if x[0] == letter] </code></pre> <p>The contents of <code>output</code> will be:</p> <pre><code>['were', 'walking'] </code></pre> <p>Some notes:</p> <ul> <li>If the code needs to be <em>fast</em> you should put the wordlist in some kind of tree.</li> <li>If you need more flexibility, you should build a regular expression for matching</li> </ul>
1
2008-11-20T14:25:30Z
[ "python" ]
Python printing the word
305,422
<p>If any one can help me with Python code: If I input a letter, How can I print all the words start with that word?</p>
1
2008-11-20T14:20:16Z
305,440
<pre><code>print [word for word in words if word.startswith(letter)] </code></pre>
2
2008-11-20T14:30:06Z
[ "python" ]
Appropriate location for my application's cache on Windows
305,647
<p>My application caches some data on disk. Because the cache may be large, it should not be stored on a network drive. It should persist between invocations of the application. I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform.</p> <p>What is the appropriate location for such a cache? Is there an API for determining the appropriate location? How do I call it from Python?</p>
3
2008-11-20T15:28:27Z
305,662
<p>Perhaps the <a href="http://docs.python.org/library/tempfile.html" rel="nofollow"><code>tempfile</code></a> module provides what you need. It uses the Windows Temp directory (which probably is not on a network drive) but you can specify a directory if you want to. Also for security reasons this module should be the right tool - if you use <code>tempfile.mkstemp()</code> the file is readable and writable only by the creating user ID.</p> <p>Oh. I see you have just edited your question and that you need file persistence between invocations of the app. Then <code>tempfile</code> is not that ideal (even though you could choose not to delete your cache between invocations).</p>
1
2008-11-20T15:31:47Z
[ "python", "windows" ]
Appropriate location for my application's cache on Windows
305,647
<p>My application caches some data on disk. Because the cache may be large, it should not be stored on a network drive. It should persist between invocations of the application. I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform.</p> <p>What is the appropriate location for such a cache? Is there an API for determining the appropriate location? How do I call it from Python?</p>
3
2008-11-20T15:28:27Z
305,679
<p>Does the app have any preferences, settings or options that the user can specify? If so, add an option where the user can specify the location of the data, with a default of the current Windows temp directory.</p> <p>There's always a chance they may not have enough space on the drive with the temp directory, and would need to use a different drive/directory.</p>
0
2008-11-20T15:36:00Z
[ "python", "windows" ]
Appropriate location for my application's cache on Windows
305,647
<p>My application caches some data on disk. Because the cache may be large, it should not be stored on a network drive. It should persist between invocations of the application. I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform.</p> <p>What is the appropriate location for such a cache? Is there an API for determining the appropriate location? How do I call it from Python?</p>
3
2008-11-20T15:28:27Z
305,700
<p>There are a number a places you can put your application files in Windows. <a href="http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx" rel="nofollow">This page</a> shows a list (this enum is .Net specific but most of the special folders are standard on Windows in general). Basically you'll need to decide if you need a cache per user, only for the local machine, per application or shared, etc.</p> <p>I don't have much experience with python so I cannot specifically help with how to get these paths, but I'm sure someone more knowledgeable here can. </p>
3
2008-11-20T15:40:21Z
[ "python", "windows" ]
Appropriate location for my application's cache on Windows
305,647
<p>My application caches some data on disk. Because the cache may be large, it should not be stored on a network drive. It should persist between invocations of the application. I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform.</p> <p>What is the appropriate location for such a cache? Is there an API for determining the appropriate location? How do I call it from Python?</p>
3
2008-11-20T15:28:27Z
305,763
<p>The standard location for Windows application to store their (permanent) application data is referenced by the <code>%APPDATA%</code> (current user) or <code>%ALLUSERSPROFILE%</code> (all users) environment variables. You can access them using, e.g. (only rudimentary and not very elegant error checking!):</p> <pre><code>import os app_path = os.getenv("APPDATA") + "\\MyApplicationData" try: os.mkdir(app_path) except WindowsError: # already exists </code></pre> <p>Now you have your own directory for your app. </p>
2
2008-11-20T15:53:15Z
[ "python", "windows" ]
Appropriate location for my application's cache on Windows
305,647
<p>My application caches some data on disk. Because the cache may be large, it should not be stored on a network drive. It should persist between invocations of the application. I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform.</p> <p>What is the appropriate location for such a cache? Is there an API for determining the appropriate location? How do I call it from Python?</p>
3
2008-11-20T15:28:27Z
305,782
<p>Have a look here: <a href="http://en.wikipedia.org/wiki/Environment_variable#User_management_variables" rel="nofollow">http://en.wikipedia.org/wiki/Environment_variable#User_management_variables</a>. Anything that's under the users directory is good. If its for all users, then it should be: %ALLUSERSPROFILE%. If its for a specific user, make sure the permissions are right.</p> <p>Check out MSDN for more info about other Windows Versions. Environment variables can vary from systems to systems.</p>
2
2008-11-20T15:58:00Z
[ "python", "windows" ]
Appropriate location for my application's cache on Windows
305,647
<p>My application caches some data on disk. Because the cache may be large, it should not be stored on a network drive. It should persist between invocations of the application. I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform.</p> <p>What is the appropriate location for such a cache? Is there an API for determining the appropriate location? How do I call it from Python?</p>
3
2008-11-20T15:28:27Z
305,996
<p>The <a href="http://wxpython.org/docs/api/wx.StandardPaths-class.html" rel="nofollow"><code>wx.StandardPaths</code></a> module contains methods that return various standard locations in the file system and transparently tries to do "the right thing" under Unix, Mac OS X, and Windows.</p>
1
2008-11-20T16:46:38Z
[ "python", "windows" ]
In Python, how can you get the name of a member function's class?
305,924
<p>I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g.</p> <pre><code>def analyser(testFunc): print testFunc.__name__, 'belongs to the class, ... </code></pre> <p>I thought </p> <pre><code>testFunc.__class__ </code></pre> <p>would solve my problems, but that just tells me that testFunc is a function.</p>
7
2008-11-20T16:30:30Z
305,948
<p>I'm not a Python expert, but does this work?</p> <pre><code>testFunc.__self__.__class__ </code></pre> <p>It seems to work for bound methods, but in your case, you may be using an unbound method, in which case this may work better:</p> <pre><code>testFunc.__objclass__ </code></pre> <p>Here's the test I used:</p> <pre><code>Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import hashlib &gt;&gt;&gt; hd = hashlib.md5().hexdigest &gt;&gt;&gt; hd &lt;built-in method hexdigest of _hashlib.HASH object at 0x7f9492d96960&gt; &gt;&gt;&gt; hd.__self__.__class__ &lt;type '_hashlib.HASH'&gt; &gt;&gt;&gt; hd2 = hd.__self__.__class__.hexdigest &gt;&gt;&gt; hd2 &lt;method 'hexdigest' of '_hashlib.HASH' objects&gt; &gt;&gt;&gt; hd2.__objclass__ &lt;type '_hashlib.HASH'&gt; </code></pre> <p>Oh yes, another thing:</p> <pre><code>&gt;&gt;&gt; hd.im_class Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'builtin_function_or_method' object has no attribute 'im_class' &gt;&gt;&gt; hd2.im_class Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'method_descriptor' object has no attribute 'im_class' </code></pre> <p>So if you want something bulletproof, it should handle <code>__objclass__</code> and <code>__self__</code> too. But your mileage may vary.</p>
5
2008-11-20T16:35:16Z
[ "python", "reflection", "metaprogramming" ]
In Python, how can you get the name of a member function's class?
305,924
<p>I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g.</p> <pre><code>def analyser(testFunc): print testFunc.__name__, 'belongs to the class, ... </code></pre> <p>I thought </p> <pre><code>testFunc.__class__ </code></pre> <p>would solve my problems, but that just tells me that testFunc is a function.</p>
7
2008-11-20T16:30:30Z
305,980
<pre><code>testFunc.im_class </code></pre> <p><a href="https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy" rel="nofollow">https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy</a></p> <blockquote> <p><code>im_class</code> is the class of <code>im_self</code> for bound methods or the class that asked for the method for unbound methods</p> </blockquote>
10
2008-11-20T16:42:42Z
[ "python", "reflection", "metaprogramming" ]
In Python, how can you get the name of a member function's class?
305,924
<p>I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g.</p> <pre><code>def analyser(testFunc): print testFunc.__name__, 'belongs to the class, ... </code></pre> <p>I thought </p> <pre><code>testFunc.__class__ </code></pre> <p>would solve my problems, but that just tells me that testFunc is a function.</p>
7
2008-11-20T16:30:30Z
306,030
<p>instance methods will have attributes .im_class .im_func .im_self</p> <p><a href="http://docs.python.org/library/inspect.html#types-and-members" rel="nofollow">http://docs.python.org/library/inspect.html#types-and-members</a></p> <p>You probably want to see if the function hasattr .im_class, and get the class info from there.</p>
3
2008-11-20T16:53:50Z
[ "python", "reflection", "metaprogramming" ]
Python decorator makes function forget that it belongs to a class
306,130
<p>I am trying to write a decorator to do logging:</p> <pre><code>def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() </code></pre> <p>I would like this to print:</p> <pre><code>Entering C.f </code></pre> <p>but instead I get this error message:</p> <pre><code>AttributeError: 'function' object has no attribute 'im_class' </code></pre> <p>Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.</p>
41
2008-11-20T17:24:39Z
306,196
<p>It seems that while the class is being created, Python creates regular function objects. They only get turned into unbound method objects afterwards. Knowing that, this is the only way I could find to do what you want:</p> <pre><code>def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): def f(self): pass C.f = logger(C.f) C().f() </code></pre> <p>This outputs the desired result.</p> <p>If you want to wrap all the methods in a class, then you probably want to create a wrapClass function, which you could then use like this:</p> <pre><code>C = wrapClass(C) </code></pre>
6
2008-11-20T17:47:52Z
[ "python", "reflection", "metaprogramming" ]
Python decorator makes function forget that it belongs to a class
306,130
<p>I am trying to write a decorator to do logging:</p> <pre><code>def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() </code></pre> <p>I would like this to print:</p> <pre><code>Entering C.f </code></pre> <p>but instead I get this error message:</p> <pre><code>AttributeError: 'function' object has no attribute 'im_class' </code></pre> <p>Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.</p>
41
2008-11-20T17:24:39Z
306,260
<p>Class functions should always take self as their first argument, so you can use that instead of im_class.</p> <pre><code>def logger(myFunc): def new(self, *args, **keyargs): print 'Entering %s.%s' % (self.__class__.__name__, myFunc.__name__) return myFunc(self, *args, **keyargs) return new class C(object): @logger def f(self): pass C().f() </code></pre> <p>at first I wanted to use <code>self.__name__</code> but that doesn't work because the instance has no name. you must use <code>self.__class__.__name__</code> to get the name of the class.</p>
6
2008-11-20T18:05:01Z
[ "python", "reflection", "metaprogramming" ]
Python decorator makes function forget that it belongs to a class
306,130
<p>I am trying to write a decorator to do logging:</p> <pre><code>def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() </code></pre> <p>I would like this to print:</p> <pre><code>Entering C.f </code></pre> <p>but instead I get this error message:</p> <pre><code>AttributeError: 'function' object has no attribute 'im_class' </code></pre> <p>Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.</p>
41
2008-11-20T17:24:39Z
306,277
<p>Claudiu's answer is correct, but you can also cheat by getting the class name off of the <code>self</code> argument. This will give misleading log statements in cases of inheritance, but will tell you the class of the object whose method is being called. For example:</p> <pre><code>from functools import wraps # use this to preserve function signatures and docstrings def logger(func): @wraps(func) def with_logging(*args, **kwargs): print "Entering %s.%s" % (args[0].__class__.__name__, func.__name__) return func(*args, **kwargs) return with_logging class C(object): @logger def f(self): pass C().f() </code></pre> <p>As I said, this won't work properly in cases where you've inherited a function from a parent class; in this case you might say</p> <pre><code>class B(C): pass b = B() b.f() </code></pre> <p>and get the message <code>Entering B.f</code> where you actually want to get the message <code>Entering C.f</code> since that's the correct class. On the other hand, this might be acceptable, in which case I'd recommend this approach over Claudiu's suggestion.</p>
36
2008-11-20T18:08:33Z
[ "python", "reflection", "metaprogramming" ]
Python decorator makes function forget that it belongs to a class
306,130
<p>I am trying to write a decorator to do logging:</p> <pre><code>def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() </code></pre> <p>I would like this to print:</p> <pre><code>Entering C.f </code></pre> <p>but instead I get this error message:</p> <pre><code>AttributeError: 'function' object has no attribute 'im_class' </code></pre> <p>Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.</p>
41
2008-11-20T17:24:39Z
306,295
<p>You can also use <code>new.instancemethod()</code> to create an instance method (either bound or unbound) from a function.</p>
0
2008-11-20T18:12:34Z
[ "python", "reflection", "metaprogramming" ]
Python decorator makes function forget that it belongs to a class
306,130
<p>I am trying to write a decorator to do logging:</p> <pre><code>def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() </code></pre> <p>I would like this to print:</p> <pre><code>Entering C.f </code></pre> <p>but instead I get this error message:</p> <pre><code>AttributeError: 'function' object has no attribute 'im_class' </code></pre> <p>Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.</p>
41
2008-11-20T17:24:39Z
307,263
<p>Functions only become methods at runtime. That is, when you get <code>C.f</code> you get a bound function (and <code>C.f.im_class is C</code>). At the time your function is defined it is just a plain function, it is not bound to any class. This unbound and disassociated function is what is decorated by logger.</p> <p><code>self.__class__.__name__</code> will give you the name of the class, but you can also use descriptors to accomplish this in a somewhat more general way. This pattern is described <a href="http://blog.ianbicking.org/2008/10/24/decorators-and-descriptors/">in a blog post on Decorators and Descriptors</a>, and an implementation of your logger decorator in particular would look like:</p> <pre><code>class logger(object): def __init__(self, func): self.func = func def __get__(self, obj, type=None): return self.__class__(self.func.__get__(obj, type)) def __call__(self, *args, **kw): print 'Entering %s' % self.func return self.func(*args, **kw) class C(object): @logger def f(self, x, y): return x+y C().f(1, 2) # =&gt; Entering &lt;bound method C.f of &lt;__main__.C object at 0x...&gt;&gt; </code></pre> <p>Obviously the output can be improved (by using, for example, <code>getattr(self.func, 'im_class', None)</code>), but this general pattern will work for both methods and functions. However it will <em>not</em> work for old-style classes (but just don't use those ;)</p>
18
2008-11-20T23:16:51Z
[ "python", "reflection", "metaprogramming" ]
Python decorator makes function forget that it belongs to a class
306,130
<p>I am trying to write a decorator to do logging:</p> <pre><code>def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() </code></pre> <p>I would like this to print:</p> <pre><code>Entering C.f </code></pre> <p>but instead I get this error message:</p> <pre><code>AttributeError: 'function' object has no attribute 'im_class' </code></pre> <p>Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.</p>
41
2008-11-20T17:24:39Z
3,300,907
<p>I found another solution to a very similar problem using the <code>inspect</code> library. When the decorator is called, even though the function is not yet bound to the class, you can inspect the stack and discover which class is calling the decorator. You can at least get the string name of the class, if that is all you need (probably can't reference it yet since it is being created). Then you do not need to call anything after the class has been created.</p> <pre><code>import inspect def logger(myFunc): classname = inspect.getouterframes(inspect.currentframe())[1][3] def new(*args, **keyargs): print 'Entering %s.%s' % (classname, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(self): pass C().f() </code></pre> <p>While this is not necessarily <em>better</em> than the others, it is the <em>only</em> way I can figure out to discover the class name of the future method during the call to the decorator. Make note of not keeping references to frames around in the <code>inspect</code> library documentation.</p>
5
2010-07-21T15:21:22Z
[ "python", "reflection", "metaprogramming" ]
Python decorator makes function forget that it belongs to a class
306,130
<p>I am trying to write a decorator to do logging:</p> <pre><code>def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() </code></pre> <p>I would like this to print:</p> <pre><code>Entering C.f </code></pre> <p>but instead I get this error message:</p> <pre><code>AttributeError: 'function' object has no attribute 'im_class' </code></pre> <p>Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.</p>
41
2008-11-20T17:24:39Z
3,412,743
<p>Ideas proposed here are excellent, but have some disadvantages:</p> <ol> <li><code>inspect.getouterframes</code> and <code>args[0].__class__.__name__</code> are not suitable for plain functions and static-methods.</li> <li><code>__get__</code> must be in a class, that is rejected by <code>@wraps</code>.</li> <li><code>@wraps</code> itself should be hiding traces better.</li> </ol> <p>So, I've combined some ideas from this page, links, docs and my own head,<br> and finally found a solution, that lacks all three disadvantages above.</p> <p>As a result, <code>method_decorator</code>:</p> <ul> <li>Knows the class the decorated method is bound to.</li> <li>Hides decorator traces by answering to system attributes more correctly than <code>functools.wraps()</code> does.</li> <li>Is covered with unit-tests for bound an unbound instance-methods, class-methods, static-methods, and plain functions.</li> </ul> <p>Usage:</p> <pre><code>pip install method_decorator from method_decorator import method_decorator class my_decorator(method_decorator): # ... </code></pre> <p>See <a href="https://github.com/denis-ryzhkov/method_decorator/blob/master/method_decorator.py#L48">full unit-tests for usage details</a>.</p> <p>And here is just the code of the <code>method_decorator</code> class:</p> <pre><code>class method_decorator(object): def __init__(self, func, obj=None, cls=None, method_type='function'): # These defaults are OK for plain functions # and will be changed by __get__() for methods once a method is dot-referenced. self.func, self.obj, self.cls, self.method_type = func, obj, cls, method_type def __get__(self, obj=None, cls=None): # It is executed when decorated func is referenced as a method: cls.func or obj.func. if self.obj == obj and self.cls == cls: return self # Use the same instance that is already processed by previous call to this __get__(). method_type = ( 'staticmethod' if isinstance(self.func, staticmethod) else 'classmethod' if isinstance(self.func, classmethod) else 'instancemethod' # No branch for plain function - correct method_type for it is already set in __init__() defaults. ) return object.__getattribute__(self, '__class__')( # Use specialized method_decorator (or descendant) instance, don't change current instance attributes - it leads to conflicts. self.func.__get__(obj, cls), obj, cls, method_type) # Use bound or unbound method with this underlying func. def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) def __getattribute__(self, attr_name): # Hiding traces of decoration. if attr_name in ('__init__', '__get__', '__call__', '__getattribute__', 'func', 'obj', 'cls', 'method_type'): # Our known names. '__class__' is not included because is used only with explicit object.__getattribute__(). return object.__getattribute__(self, attr_name) # Stopping recursion. # All other attr_names, including auto-defined by system in self, are searched in decorated self.func, e.g.: __module__, __class__, __name__, __doc__, im_*, func_*, etc. return getattr(self.func, attr_name) # Raises correct AttributeError if name is not found in decorated self.func. def __repr__(self): # Special case: __repr__ ignores __getattribute__. return self.func.__repr__() </code></pre>
13
2010-08-05T07:54:48Z
[ "python", "reflection", "metaprogramming" ]
"is" operator behaves unexpectedly with integers
306,313
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
264
2008-11-20T18:21:16Z
306,347
<p>I think your hypotheses is correct. Experiment with id (identity of object)..</p> <pre><code>In [1]: id(255) Out[1]: 146349024 In [2]: id(255) Out[2]: 146349024 In [3]: id(257) Out[3]: 146802752 In [4]: id(257) Out[4]: 148993740 In [5]: a=255 In [6]: b=255 In [7]: c=257 In [8]: d=257 In [9]: id(a), id(b), id(c), id(d) Out[9]: (146349024, 146349024, 146783024, 146804020) </code></pre> <p>It appears that numbers &lt;= 255 are treated as literals and anything above is treated differently!</p>
18
2008-11-20T18:29:48Z
[ "python", "int", "comparison", "operators", "identity" ]
"is" operator behaves unexpectedly with integers
306,313
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
264
2008-11-20T18:21:16Z
306,353
<p>Take a look at this:</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; id(a) 9987148 &gt;&gt;&gt; id(b) 9987148 &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; id(a) 11662816 &gt;&gt;&gt; id(b) 11662828 </code></pre> <p>EDIT: Here's what I found in the Python 2 documentation, <a href="https://docs.python.org/2/c-api/int.html">"Plain Integer Objects"</a> (It's the same for <a href="https://docs.python.org/3/c-api/long.html">Python 3</a>):</p> <blockquote> <p>The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)</p> </blockquote>
222
2008-11-20T18:30:20Z
[ "python", "int", "comparison", "operators", "identity" ]