title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
group by in django
475,552
<p>How can i create simple group by query in trunk version of django?</p> <p>I need something like</p> <pre><code>SELECT name FROM mytable GROUP BY name </code></pre> <p>actually what i want to do is simply get all entries with distinct names. </p>
3
2009-01-24T05:15:15Z
476,156
<p>If you need all the distinct names, just do this:</p> <pre><code>Foo.objects.values('name').distinct() </code></pre> <p>And you'll get a list of dictionaries, each one with a <strong>name</strong> key. If you need other data, just add more attribute names as parameters to the .values() call. Of course, if you add in attributes that may vary between rows with the same name, you'll break the .distinct().</p> <p>This won't help if you want to get complete model objects back. But getting distinct names and getting full data are inherently incompatible goals anyway; how do you know <em>which</em> row with a given name you want returned in its entirety? If you want to calculate some sort of aggregate data for all the rows with a given name, <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/#topics-db-aggregation" rel="nofollow">aggregation support</a> was recently added to Django trunk and can take care of that for you.</p>
12
2009-01-24T15:37:28Z
[ "python", "django", "django-models" ]
Python - why use "self" in a class?
475,871
<p>How do these 2 classes differ?</p> <pre><code>class A(): x=3 class B(): def __init__(self): self.x=3 </code></pre> <p>Is there any significant difference? </p>
68
2009-01-24T11:13:19Z
475,873
<p><code>A.x</code> is a <em>class variable</em>. <code>B</code>'s <code>self.x</code> is an <em>instance variable</em>.</p> <p>i.e. <code>A</code>'s <code>x</code> is shared between instances.</p> <p>It would be easier to demonstrate the difference with something that can be modified like a list:</p> <pre><code>#!/usr/bin/env python class A: x = [] def add(self): self.x.append(1) class B: def __init__(self): self.x = [] def add(self): self.x.append(1) x = A() y = A() x.add() y.add() print "A's x:",x.x x = B() y = B() x.add() y.add() print "B's x:",x.x </code></pre> <p>Output</p> <blockquote> <p>A's x: [1, 1]<br /> B's x: [1]</p> </blockquote>
107
2009-01-24T11:17:47Z
[ "python", "oop" ]
Python - why use "self" in a class?
475,871
<p>How do these 2 classes differ?</p> <pre><code>class A(): x=3 class B(): def __init__(self): self.x=3 </code></pre> <p>Is there any significant difference? </p>
68
2009-01-24T11:13:19Z
475,905
<p>A.x is a class variable, and will be shared across all instances of A, unless specifically overridden within an instance. B.x is an instance variable, and each instance of B has its own version of it.</p> <p>I hope the following Python example can clarify:</p> <pre><code> >>> class Foo(): ... i = 3 ... def bar(self): ... print 'Foo.i is', Foo.i ... print 'self.i is', self.i ... >>> f = Foo() # Create an instance of the Foo class >>> f.bar() Foo.i is 3 self.i is 3 >>> Foo.i = 5 # Change the global value of Foo.i over all instances >>> f.bar() Foo.i is 5 self.i is 5 >>> f.i = 3 # Override this instance's definition of i >>> f.bar() Foo.i is 5 self.i is 3 </code></pre>
17
2009-01-24T11:41:32Z
[ "python", "oop" ]
Python - why use "self" in a class?
475,871
<p>How do these 2 classes differ?</p> <pre><code>class A(): x=3 class B(): def __init__(self): self.x=3 </code></pre> <p>Is there any significant difference? </p>
68
2009-01-24T11:13:19Z
475,919
<p>Just as a side note: <code>self</code> is actually just a randomly chosen word, that everyone uses, but you could also use <code>this</code>, <code>foo</code>, or <code>myself</code> or anything else you want, it's just the first parameter of every non static method for a class. This means that the word <code>self</code> is not a language construct but just a name:</p> <pre><code>&gt;&gt;&gt; class A: ... def __init__(s): ... s.bla = 2 ... &gt;&gt;&gt; &gt;&gt;&gt; a = A() &gt;&gt;&gt; a.bla 2 </code></pre>
42
2009-01-24T11:57:59Z
[ "python", "oop" ]
Python - why use "self" in a class?
475,871
<p>How do these 2 classes differ?</p> <pre><code>class A(): x=3 class B(): def __init__(self): self.x=3 </code></pre> <p>Is there any significant difference? </p>
68
2009-01-24T11:13:19Z
475,924
<p>There have been lately some interesting posts regarding the use of <code>self</code> between Bruce Eckel and GvR. Check it out: <a href="http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html" rel="nofollow">this</a> vs. <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=239003" rel="nofollow">this</a></p>
-1
2009-01-24T12:03:13Z
[ "python", "oop" ]
Python - why use "self" in a class?
475,871
<p>How do these 2 classes differ?</p> <pre><code>class A(): x=3 class B(): def __init__(self): self.x=3 </code></pre> <p>Is there any significant difference? </p>
68
2009-01-24T11:13:19Z
11,342,486
<p>I used to explain it with this example</p> <pre><code># By TMOTTM class Machine: # Class Variable counts how many machines have been created. # The value is the same for all objects of this class. counter = 0 def __init__(self): # Notice: no 'self'. Machine.counter += 1 # Instance variable. # Different for every object of the class. self.id = Machine.counter if __name__ == '__main__': machine1 = Machine() machine2 = Machine() machine3 = Machine() #The value is different for all objects. print 'machine1.id', machine1.id print 'machine2.id', machine2.id print 'machine3.id', machine3.id #The value is the same for all objects. print 'machine1.counter', machine1.counter print 'machine2.counter', machine2.counter print 'machine3.counter', machine3.counter </code></pre> <p>The output then will by</p> <pre> machine1.id 1 machine2.id 2 machine3.id 3 machine1.counter 3 machine2.counter 3 machine3.counter 3 </pre>
13
2012-07-05T10:30:27Z
[ "python", "oop" ]
Python - why use "self" in a class?
475,871
<p>How do these 2 classes differ?</p> <pre><code>class A(): x=3 class B(): def __init__(self): self.x=3 </code></pre> <p>Is there any significant difference? </p>
68
2009-01-24T11:13:19Z
25,025,527
<p>I've just started learning Python and this confused me as well for some time. Trying to figure out how it all works in general I came up with this very simple piece of code:</p> <pre><code># Create a class with a variable inside and an instance of that class class One: color = 'green' obj2 = One() # Here we create a global variable(outside a class suite). color = 'blue' # Create a second class and a local variable inside this class. class Two: color = "red" # Define 3 methods. The only difference between them is the "color" part. def out(self): print(self.color + '!') def out2(self): print(color + '!') def out3(self): print(obj2.color + '!') # Create an object of the class One obj = Two() </code></pre> <p>When we call <code>out()</code> we get:</p> <pre><code>&gt;&gt;&gt; obj.out() red! </code></pre> <p>When we call <code>out2()</code>:</p> <pre><code>&gt;&gt;&gt; obj.out2() blue! </code></pre> <p>When we call <code>out3()</code>:</p> <pre><code>&gt;&gt;&gt; obj.out3() green! </code></pre> <p>So, in the first method <code>self</code> specifies that Python should use the variable(attribute), that "belongs" to the class object we created, not a global one(outside the class). So it uses <code>color = "red"</code>. In the method Python implicitly substitutes <code>self</code> for the name of an object we created(<code>obj</code>). <code>self.color</code> means "I am getting <code>color="red"</code> from the <code>obj</code>"</p> <p>In the second method there is no <code>self</code> to specify the object where the color should be taken from, so it gets the global one <code>color = 'blue'</code>.</p> <p>In the third method instead of <code>self</code> we used <code>obj2</code> - a name of another object to get <code>color</code> from. It gets <code>color = 'green'</code>.</p>
2
2014-07-29T21:47:11Z
[ "python", "oop" ]
python IPC (Inter Process Communication) for Vista UAC (User Access Control)
475,928
<p>I am writing a Filemanager in (wx)python - a lot already works. When copying files there is already a progress dialog, overwrite handling etc.</p> <p>Now in Vista when the user wants to copy a file to certain directories (eg %Program Files%) the application/script needs elevation, which cannot be asked for at runtime. So i have to start another app/script elevated, which does the work, but needs to communicate with the main app, so latter can update the progress etc.</p> <p>I searched and found a lot of articles saying shared memory and pipes are the easiest way. So what i am looking for is a 'high level' platform independent ipc library whith python bindings using shared mem or pipes. </p> <p>I already found ominORB, fnorb, etc. They look very interesting, but use TCP/IP, is there an equivalent lib using shared mem or pipes ? Since the ipc-client is always on the same machine sockets seems not to be neccesary here. And i am also afraid the user would have to allow ipc-socket-communications on his/her personal firewall.</p> <p>EDIT: I really mean high level: it would be great to be able to just call some functions like when using omniORB instead of sending strings to stdin/stdout.</p>
4
2009-01-24T12:05:46Z
476,056
<p>How about just communicating with the second process using stdin/stdout?</p> <p>There are some caveats due to input and output buffering, but take a look at <a href="http://code.activestate.com/recipes/440554/" rel="nofollow">this Python Cookbook recipe</a>, and also <a href="http://www.noah.org/wiki/Pexpect" rel="nofollow">Pexpect</a>, for ideas on how to do this. </p>
2
2009-01-24T14:00:50Z
[ "python", "windows-vista", "wxpython", "ipc", "vista-security" ]
Order a QuerySet by aggregate field value
476,017
<p>Let's say I have the following model:</p> <pre><code>class Contest: title = models.CharField( max_length = 200 ) description = models.TextField() class Image: title = models.CharField( max_length = 200 ) description = models.TextField() contest = models.ForeignKey( Contest ) user = models.ForeignKey( User ) def score( self ): return self.vote_set.all().aggregate( models.Sum( 'value' ) )[ 'value__sum' ] class Vote: value = models.SmallIntegerField() user = models.ForeignKey( User ) image = models.ForeignKey( Image ) </code></pre> <p>The users of a site can contribute their images to several contests. Then other users can vote them up or down. Everything works fine, but now I want to display a page on which users can see all contributions to a certain contest. The images shall be ordered by their score. Therefore I tried the following:</p> <pre><code>Contest.objects.get( pk = id ).image_set.order_by( 'score' ) </code></pre> <p>As I feared it doesn't work since 'score' is no database field that could be used in queries.</p>
24
2009-01-24T13:26:58Z
476,024
<p>You can write your own sort in Python very simply.</p> <pre><code>def getScore( anObject ): return anObject.score() objects= list(Contest.objects.get( pk = id ).image_set) objects.sort( key=getScore ) </code></pre> <p>This works nicely because we sorted the list, which we're going to provide to the template.</p>
9
2009-01-24T13:34:36Z
[ "python", "database", "django", "order" ]
Order a QuerySet by aggregate field value
476,017
<p>Let's say I have the following model:</p> <pre><code>class Contest: title = models.CharField( max_length = 200 ) description = models.TextField() class Image: title = models.CharField( max_length = 200 ) description = models.TextField() contest = models.ForeignKey( Contest ) user = models.ForeignKey( User ) def score( self ): return self.vote_set.all().aggregate( models.Sum( 'value' ) )[ 'value__sum' ] class Vote: value = models.SmallIntegerField() user = models.ForeignKey( User ) image = models.ForeignKey( Image ) </code></pre> <p>The users of a site can contribute their images to several contests. Then other users can vote them up or down. Everything works fine, but now I want to display a page on which users can see all contributions to a certain contest. The images shall be ordered by their score. Therefore I tried the following:</p> <pre><code>Contest.objects.get( pk = id ).image_set.order_by( 'score' ) </code></pre> <p>As I feared it doesn't work since 'score' is no database field that could be used in queries.</p>
24
2009-01-24T13:26:58Z
476,025
<p>The db-level <code>order_by</code> cannot sort queryset by model's python method.</p> <p>The solution is to introduce <code>score</code> field to <code>Image</code> model and recalculate it on every <code>Vote</code> update. Some sort of denormalization. When you will can to sort by it.</p>
0
2009-01-24T13:36:40Z
[ "python", "database", "django", "order" ]
Order a QuerySet by aggregate field value
476,017
<p>Let's say I have the following model:</p> <pre><code>class Contest: title = models.CharField( max_length = 200 ) description = models.TextField() class Image: title = models.CharField( max_length = 200 ) description = models.TextField() contest = models.ForeignKey( Contest ) user = models.ForeignKey( User ) def score( self ): return self.vote_set.all().aggregate( models.Sum( 'value' ) )[ 'value__sum' ] class Vote: value = models.SmallIntegerField() user = models.ForeignKey( User ) image = models.ForeignKey( Image ) </code></pre> <p>The users of a site can contribute their images to several contests. Then other users can vote them up or down. Everything works fine, but now I want to display a page on which users can see all contributions to a certain contest. The images shall be ordered by their score. Therefore I tried the following:</p> <pre><code>Contest.objects.get( pk = id ).image_set.order_by( 'score' ) </code></pre> <p>As I feared it doesn't work since 'score' is no database field that could be used in queries.</p>
24
2009-01-24T13:26:58Z
476,033
<p>Oh, of course I forget about new aggregation support in Django and its <code>annotate</code> functionality.</p> <p>So query may look like this:</p> <pre><code>Contest.objects.get(pk=id).image_set.annotate(score=Sum('vote__value')).order_by( 'score' ) </code></pre>
44
2009-01-24T13:44:37Z
[ "python", "database", "django", "order" ]
The OLE way of doing drag&drop in wxPython
476,142
<p>I have wxPython app which is running on MS Windows and I'd like it to support drag&amp;drop between its instances (so the user opens my app 3 times and drags data from one instance to another).</p> <p>The simple drag&amp;drop in wxPython works that way:</p> <ol> <li><strong>User initiates drag</strong>: The source window packs necessary data in wx.DataObject(), creates new wx.DropSource, sets its data and calls dropSource.DoDragDrop()</li> <li><strong>User drops data onto target window</strong>: The drop target calls library function GetData() which transfers actual data to its wx.DataObject instance and finally - dataObject.GetData() unpacks the actual data.</li> </ol> <p>I'd like to have some more sophisticated drag&amp;drop which would allow user to choose what data is dragged <strong>after</strong> he drops.<br /> Scenario of <em>my dreams</em>: </p> <ol> <li><strong>User initiates drag</strong>: Only some pointer to the source window is packed (some function or object).</li> <li><strong>User drops data onto target window</strong>: Nice dialog is displayed which asks user which drag&amp;drop mode he chooses (like - dragging only song title, or song title and the artists name or whole album of the dragged artist).</li> <li><strong>Users chooses drag&amp;drop mode</strong>: Drop target calls some function on the dragged data object, which then retrieves data from the drag source and transfers it to the drop target.</li> </ol> <p>The scenario of my dreams seems doable in MS Windows, but the docs for wxWidgets and wxPython are pretty complex and ambigious. Not all wx.DataObject classes are available in wxPython (only wx.PySimpleDataObject), so I'd like someone to share his experience with such approach. Can such behaviour be implemented in wxPython without having to code it directly in winAPI?</p> <p>EDIT: Toni Ruža gave an answer with working drag&amp;drop example, but that's not exactly the scenario of <em>my dreams</em>. His code manipulates data when it's dropped (the <strong>HandleDrop()</strong> shows popup menu), but data is prepared when drag is initiated (in <strong>On_ElementDrag()</strong>). In my application there should be three different drag&amp;drop modes, and some of them require time-consuming data preparation. That's why I want to postpone data retrieval to the moment user drops data and chooses (potentially costly) d&amp;d mode.</p> <p>And for memory protection issue - I want to use OLE mechanisms for inter-process communication, like MS Office does. You can copy Excel diagram and paste it into MS-Word where it will behave like an image (well, sort of). Since it works I believe it can be done in winAPI. I just don't know if I can code it in wxPython.</p>
2
2009-01-24T15:29:45Z
476,570
<p>Since you can't use one of the <a href="http://www.wxpython.org/docs/api/wx.DataFormat-class.html" rel="nofollow">standard</a> data formats to store references to python objects I would recommend you use a text data format for storing the parameters you need for your method calls rather than making a new data format. And anyway, it would be no good to pass a reference to an object from one app to another as the object in question would not be accessible (remember memory protection?).</p> <p>Here is a simple example for your requirements:</p> <pre><code>import wx class TestDropTarget(wx.TextDropTarget): def OnDropText(self, x, y, text): wx.GetApp().TopWindow.HandleDrop(text) def OnDragOver(self, x, y, d): return wx.DragCopy class Test(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.numbers = wx.ListCtrl(self, style = wx.LC_ICON | wx.LC_AUTOARRANGE) self.field = wx.TextCtrl(self) sizer = wx.FlexGridSizer(2, 2, 5, 5) sizer.AddGrowableCol(1) sizer.AddGrowableRow(0) self.SetSizer(sizer) sizer.Add(wx.StaticText(self, label="Drag from:")) sizer.Add(self.numbers, flag=wx.EXPAND) sizer.Add(wx.StaticText(self, label="Drag to:"), flag=wx.ALIGN_CENTER_VERTICAL) sizer.Add(self.field) for i in range(100): self.numbers.InsertStringItem(self.numbers.GetItemCount(), str(i)) self.numbers.Bind(wx.EVT_LIST_BEGIN_DRAG, self.On_ElementDrag) self.field.SetDropTarget(TestDropTarget()) menu_id1 = wx.NewId() menu_id2 = wx.NewId() self.menu = wx.Menu() self.menu.AppendItem(wx.MenuItem(self.menu, menu_id1, "Simple copy")) self.menu.AppendItem(wx.MenuItem(self.menu, menu_id2, "Mess with it")) self.Bind(wx.EVT_MENU, self.On_SimpleCopy, id=menu_id1) self.Bind(wx.EVT_MENU, self.On_MessWithIt, id=menu_id2) def On_ElementDrag(self, event): data = wx.TextDataObject(self.numbers.GetItemText(event.Index)) source = wx.DropSource(self.numbers) source.SetData(data) source.DoDragDrop() def HandleDrop(self, text): self._text = text self.PopupMenu(self.menu) def On_SimpleCopy(self, event): self.field.Value = self._text def On_MessWithIt(self, event): self.field.Value = "&lt;-%s-&gt;" % "".join([int(c)*c for c in self._text]) app = wx.PySimpleApp() app.TopWindow = Test() app.TopWindow.Show() app.MainLoop() </code></pre> <p>Methods like On_SimpleCopy and On_MessWithIt get executed after the drop so any lengthy operations you might want to do you can do there based on the textual or some other standard type of data you transfered with the drag (self._text in my case), and look... no OLE :)</p>
3
2009-01-24T19:59:58Z
[ "python", "windows", "drag-and-drop", "wxpython", "ole" ]
The OLE way of doing drag&drop in wxPython
476,142
<p>I have wxPython app which is running on MS Windows and I'd like it to support drag&amp;drop between its instances (so the user opens my app 3 times and drags data from one instance to another).</p> <p>The simple drag&amp;drop in wxPython works that way:</p> <ol> <li><strong>User initiates drag</strong>: The source window packs necessary data in wx.DataObject(), creates new wx.DropSource, sets its data and calls dropSource.DoDragDrop()</li> <li><strong>User drops data onto target window</strong>: The drop target calls library function GetData() which transfers actual data to its wx.DataObject instance and finally - dataObject.GetData() unpacks the actual data.</li> </ol> <p>I'd like to have some more sophisticated drag&amp;drop which would allow user to choose what data is dragged <strong>after</strong> he drops.<br /> Scenario of <em>my dreams</em>: </p> <ol> <li><strong>User initiates drag</strong>: Only some pointer to the source window is packed (some function or object).</li> <li><strong>User drops data onto target window</strong>: Nice dialog is displayed which asks user which drag&amp;drop mode he chooses (like - dragging only song title, or song title and the artists name or whole album of the dragged artist).</li> <li><strong>Users chooses drag&amp;drop mode</strong>: Drop target calls some function on the dragged data object, which then retrieves data from the drag source and transfers it to the drop target.</li> </ol> <p>The scenario of my dreams seems doable in MS Windows, but the docs for wxWidgets and wxPython are pretty complex and ambigious. Not all wx.DataObject classes are available in wxPython (only wx.PySimpleDataObject), so I'd like someone to share his experience with such approach. Can such behaviour be implemented in wxPython without having to code it directly in winAPI?</p> <p>EDIT: Toni Ruža gave an answer with working drag&amp;drop example, but that's not exactly the scenario of <em>my dreams</em>. His code manipulates data when it's dropped (the <strong>HandleDrop()</strong> shows popup menu), but data is prepared when drag is initiated (in <strong>On_ElementDrag()</strong>). In my application there should be three different drag&amp;drop modes, and some of them require time-consuming data preparation. That's why I want to postpone data retrieval to the moment user drops data and chooses (potentially costly) d&amp;d mode.</p> <p>And for memory protection issue - I want to use OLE mechanisms for inter-process communication, like MS Office does. You can copy Excel diagram and paste it into MS-Word where it will behave like an image (well, sort of). Since it works I believe it can be done in winAPI. I just don't know if I can code it in wxPython.</p>
2
2009-01-24T15:29:45Z
479,987
<p>Ok, it seems that it can't be done the way I wanted it.</p> <p>Possible solutions are: </p> <ol> <li>Pass some parameters in d&amp;d and do some inter-process communication on your own, after user drops data in target processes window. </li> <li>Use <a href="http://www.wxpython.org/docs/api/wx.DataObjectComposite-class.html" rel="nofollow">DataObjectComposite</a> to support multiple drag&amp;drop formats and keyboard modifiers to choose current format. Scenario: <ol> <li>User initiates drag. State of CTRL, ALT and SHIFT is checked, and depending on it the d&amp;d format is selected. DataObjectComposite is created, and has set data in chosen format.</li> <li>User drops data in target window. Drop target asks dropped DataObject for supported format and retrieves data, <strong>knowing</strong> what format it is in.</li> </ol></li> </ol> <p>I'm choosing the solution <strong>2.</strong>, because it doesn't require hand crafting communication between processes and it allows me to avoid unnecessary data retrieval when user wants to drag only the simplest data.</p> <p>Anyway - Toni, thanks for your answer! Played with it a little and it made me think of d&amp;d and of changing my approach to the problem.</p>
0
2009-01-26T14:40:39Z
[ "python", "windows", "drag-and-drop", "wxpython", "ole" ]
Where can i get a wiki formatting widget for my django application?
476,187
<p>Am looking for a wiki formatting widget for my django application, just like the one am using to type this question in stackoverflow?</p>
2
2009-01-24T15:49:59Z
476,415
<p>Stack Overflow uses <a href="http://wmd-editor.com/" rel="nofollow">WMD</a> for their editing. This is an editor for the <strong>Markdown</strong> language, which, while not <em>strictly</em> wiki markup, is quite close.<br /> An un-obfuscated Stack Overflow-edition version of WMD is available <a href="http://github.com/derobins/wmd/tree/master" rel="nofollow">here</a>.</p>
2
2009-01-24T18:02:19Z
[ "python", "django", "wiki" ]
Where can i get a wiki formatting widget for my django application?
476,187
<p>Am looking for a wiki formatting widget for my django application, just like the one am using to type this question in stackoverflow?</p>
2
2009-01-24T15:49:59Z
476,546
<p>There are two parts to this question. If you're looking for the client-side Javascript WYSIWYG (or WYSIWYM) editor widget, that's unrelated to Django and WMD is a fine choice (though personally I prefer <a href="http://markitup.jaysalvat.com" rel="nofollow">MarkItUp!</a>).</p> <p>If you're looking for the server-side (Django) piece of the equation, you might check into <a href="http://www.bitbucket.org/carljm/django-markitup" rel="nofollow">django-markitup</a>.</p>
3
2009-01-24T19:42:30Z
[ "python", "django", "wiki" ]
Where can i get a wiki formatting widget for my django application?
476,187
<p>Am looking for a wiki formatting widget for my django application, just like the one am using to type this question in stackoverflow?</p>
2
2009-01-24T15:49:59Z
9,243,900
<p>You can check out my plugin for Django CMS, which adds Trac wiki syntax (with Trac macro support):</p> <p><a href="https://bitbucket.org/mitar/cmsplugin-markup-tracwiki" rel="nofollow">https://bitbucket.org/mitar/cmsplugin-markup-tracwiki</a></p>
0
2012-02-11T20:43:46Z
[ "python", "django", "wiki" ]
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
476,227
<p>How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect?</p> <p>I know I can do an <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> checksum of the files content but that won't work for different bitrates. And I don't know if ID3 tags have influence in generating the MD5 checksum. Should I re-encode MP3 files that have a different bitrate and then I can do the checksum? What do you recommend?</p>
12
2009-01-24T16:14:12Z
476,258
<p>I don't think simple checksums will ever work:</p> <ol> <li>ID3 tags will affect the md5</li> <li>Different encoders will encode the same song different ways - so the checksums will be different</li> <li>Different bit-rates will produce different checksums</li> <li>Re-encoding an mp3 to a different bit-rate will probably sound terrible and will certainly be different to the original audio compressed in one step.</li> </ol> <p>I think you'll have to compare ID3 tags, song length, and filenames.</p>
2
2009-01-24T16:26:11Z
[ "python", "file", "mp3", "duplicates", "id3" ]
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
476,227
<p>How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect?</p> <p>I know I can do an <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> checksum of the files content but that won't work for different bitrates. And I don't know if ID3 tags have influence in generating the MD5 checksum. Should I re-encode MP3 files that have a different bitrate and then I can do the checksum? What do you recommend?</p>
12
2009-01-24T16:14:12Z
476,307
<p>Re-encoding at the same bit rate won't work, in fact it may make things worse as transcoding (that is what re-encoding at different bitrates is called) is going to change the nature of the compression, you are recompressing an already compressed file is going to lead to a significantly different file.</p> <p>This is a little out of my league but I would approach the problem by looking at the wave pattern of the MP3. Either by converting the MP3 to an uncompressd .wav or maybe by just running the analysis on the MP3 file itself. There should be a library out there for this. Just a word of warning, this is an expensive operation. </p> <p>Another idea, use ReplayGain to scan the files. If they are the same song, they should be be tagged with the same gain. This will only work on the exact same song from the exact same album. I know of several cases were reissues are remastered at a higher volume, thus changing the replaygain.</p> <p>EDIT:<br/> You might want to check out <a href="http://www.speech.kth.se/snack/" rel="nofollow">http://www.speech.kth.se/snack/</a>, which apparently can do spectrogram visualization. I imagine any library that can visual spectrogram can help you compare them.</p> <p>This <a href="http://wiki.python.org/moin/PythonInMusic" rel="nofollow">link</a> from the official python page may also be helpful.</p>
2
2009-01-24T16:47:41Z
[ "python", "file", "mp3", "duplicates", "id3" ]
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
476,227
<p>How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect?</p> <p>I know I can do an <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> checksum of the files content but that won't work for different bitrates. And I don't know if ID3 tags have influence in generating the MD5 checksum. Should I re-encode MP3 files that have a different bitrate and then I can do the checksum? What do you recommend?</p>
12
2009-01-24T16:14:12Z
476,382
<p>The exact same question that people at the old AudioScrobbler and currently at <a href="http://musicbrainz.org/">MusicBrainz</a> have worked on since long ago. For the time being, the Python project that can aid in your quest, is <a href="http://musicbrainz.org/doc/PicardDownload">Picard</a>, which will tag audio files (not only MPEG 1 Layer 3 files) with a GUID (actually, several of them), and from then on, matching the tags is quite simple.</p> <p>If you prefer to do it as a project of your own, <a href="http://code.google.com/p/musicip-libofa/">libofa</a> might be of help.</p>
13
2009-01-24T17:39:41Z
[ "python", "file", "mp3", "duplicates", "id3" ]
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
476,227
<p>How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect?</p> <p>I know I can do an <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> checksum of the files content but that won't work for different bitrates. And I don't know if ID3 tags have influence in generating the MD5 checksum. Should I re-encode MP3 files that have a different bitrate and then I can do the checksum? What do you recommend?</p>
12
2009-01-24T16:14:12Z
477,814
<p>Like the others said, simple checksums won't detect duplicates with different bitrates or ID3 tags. What you need is an audio fingerprint algorithm. The Python Audioprocessing Suite has such an an algorithm, but I can't say anything about how reliable it is.</p> <p><a href="http://rudd-o.com/new-projects/python-audioprocessing" rel="nofollow">http://rudd-o.com/new-projects/python-audioprocessing</a></p>
4
2009-01-25T15:24:26Z
[ "python", "file", "mp3", "duplicates", "id3" ]
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
476,227
<p>How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect?</p> <p>I know I can do an <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> checksum of the files content but that won't work for different bitrates. And I don't know if ID3 tags have influence in generating the MD5 checksum. Should I re-encode MP3 files that have a different bitrate and then I can do the checksum? What do you recommend?</p>
12
2009-01-24T16:14:12Z
585,671
<p>For tag issues, <a href="http://musicbrainz.org/doc/PicardTagger" rel="nofollow">Picard</a> may indeed be a very good bet. If, having identified two potentially duplicate files, what you want is to extract bitrate information from them, have a look at <a href="http://shibatch.sourceforge.net/" rel="nofollow">mp3guessenc</a>.</p>
3
2009-02-25T11:43:03Z
[ "python", "file", "mp3", "duplicates", "id3" ]
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
476,227
<p>How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect?</p> <p>I know I can do an <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> checksum of the files content but that won't work for different bitrates. And I don't know if ID3 tags have influence in generating the MD5 checksum. Should I re-encode MP3 files that have a different bitrate and then I can do the checksum? What do you recommend?</p>
12
2009-01-24T16:14:12Z
2,397,542
<p>I'm looking for something similar and I found this:<br> <a href="http://www.lastfm.es/user/nova77LF/journal/2007/10/12/4kaf_fingerprint_(command_line)_client" rel="nofollow">http://www.lastfm.es/user/nova77LF/journal/2007/10/12/4kaf_fingerprint_(command_line)_client</a></p> <p>Hope it helps.</p>
1
2010-03-07T19:14:15Z
[ "python", "file", "mp3", "duplicates", "id3" ]
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
476,227
<p>How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect?</p> <p>I know I can do an <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> checksum of the files content but that won't work for different bitrates. And I don't know if ID3 tags have influence in generating the MD5 checksum. Should I re-encode MP3 files that have a different bitrate and then I can do the checksum? What do you recommend?</p>
12
2009-01-24T16:14:12Z
4,750,190
<p>I'd use length as my primary heuristic. That's what iTunes does when it's trying to identify a CD using the <a href="http://en.wikipedia.org/wiki/Gracenote" rel="nofollow">Gracenote database</a>. <a href="http://stackoverflow.com/questions/993971/mp3-length-in-milliseconds">Measure the lengths in milliseconds</a> rather than seconds. Remember, this is only a heuristic: you should definitely listen to any detected duplicates before deleting them.</p>
1
2011-01-20T17:03:58Z
[ "python", "file", "mp3", "duplicates", "id3" ]
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
476,227
<p>How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect?</p> <p>I know I can do an <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> checksum of the files content but that won't work for different bitrates. And I don't know if ID3 tags have influence in generating the MD5 checksum. Should I re-encode MP3 files that have a different bitrate and then I can do the checksum? What do you recommend?</p>
12
2009-01-24T16:14:12Z
23,745,588
<p>The Dejavu project is written in Python and does exactly what you are looking for. </p> <p><a href="https://github.com/worldveil/dejavu" rel="nofollow">https://github.com/worldveil/dejavu</a></p> <p>It also supports many common formats (.wav, .mp3, etc) as well as finding the time offset of the clip in the original audio track.</p>
2
2014-05-19T19:20:45Z
[ "python", "file", "mp3", "duplicates", "id3" ]
Detect duplicate MP3 files with different bitrates and/or different ID3 tags?
476,227
<p>How could I detect (preferably with Python) duplicate MP3 files that can be encoded with different bitrates (but they are the same song) and ID3 tags that can be incorrect?</p> <p>I know I can do an <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> checksum of the files content but that won't work for different bitrates. And I don't know if ID3 tags have influence in generating the MD5 checksum. Should I re-encode MP3 files that have a different bitrate and then I can do the checksum? What do you recommend?</p>
12
2009-01-24T16:14:12Z
27,886,496
<p>You can use the successor for PUID and MusicBrainz, called <strong><a href="https://musicbrainz.org/doc/AcoustID" rel="nofollow">AcoustiD</a></strong>:</p> <blockquote> <p>AcoustID is an open source project that aims to create a free database of audio fingerprints with mapping to the MusicBrainz metadata database and provide a web service for audio file identification using this database...</p> <p>...fingerprints along with some metadata necessary to identify the songs to the AcoustID database...</p> </blockquote> <p>You will find various client libraries and examples for the webservice at <a href="https://acoustid.org/" rel="nofollow">https://acoustid.org/</a></p>
1
2015-01-11T11:25:44Z
[ "python", "file", "mp3", "duplicates", "id3" ]
Trimming Mako output
476,324
<p>I really like the Mako templating system that's used in Pylons and a couple other Python frameworks, and my only complaint is how much WS leaks through even a simple inheritance scheme.</p> <p>Is there anyway to accomplish below, without creating such huge WS gaps... or packing my code in like I started to do with base.mako?</p> <p>Otherwise to get a grip on what I'm trying to accomplish with below.</p> <p>Base is kind of like interface class for all views for the entire application, layout is just a prototype idea for 3-4 different layout files ( tables, pure CSS, etc ), and controller/action is a test to make sure my idea's are sane.</p> <p>Short summary of question: How to cut out the WS created in my Mako scheme?</p> <p>Update: Is not a solution because it involves seeding all of my mako files with \'s <a href="http://www.makotemplates.org/docs/syntax.html#syntax_newline" rel="nofollow">http://www.makotemplates.org/docs/syntax.html#syntax_newline</a></p> <p>/base.mako </p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html&gt; &lt;head&gt;&lt;%def name="headtags()"&gt;&lt;/%def&gt;${self.headtags()}&lt;/head&gt; &lt;body&gt; &lt;%def name="header()"&gt;&lt;/%def&gt;${self.header()}${next.body()}&lt;%def name="footer()"&gt;&lt;/%def&gt;${self.footer()} &lt;/body&gt; &lt;/html&gt; </code></pre> <p>/layout.mako</p> <pre><code>&lt;%inherit file="/base.mako"/&gt; &lt;%def name="headtags()"&gt; ${parent.headtags()} &lt;script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"&gt;&lt;/script&gt; &lt;/%def&gt; &lt;%def name="header()"&gt; &lt;h1&gt;My Blogination&lt;/h1&gt; &lt;/%def&gt; &lt;div id="content"&gt;${next.body()}&lt;/div&gt; </code></pre> <p>/controller/action.mako</p> <pre><code>&lt;%inherit file="/layout.mako" /&gt; &lt;%def name="headtags()"&gt; &lt;title&gt; Hello world, templating system is 1 percent done&lt;/title&gt; ${parent.headtags()} &lt;/%def&gt; Hello ${c.name}! </code></pre> <p>rendered output:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt; Hello world, templating system is 1 percent done&lt;/title&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;My Blogination&lt;/h1&gt; &lt;div id="content"&gt; Hello Anonymous! &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
4
2009-01-24T16:56:22Z
476,428
<p>Found my own answer <a href="http://docs.makotemplates.org/en/latest/filtering.html" rel="nofollow">http://docs.makotemplates.org/en/latest/filtering.html</a></p> <p>It still required some trial and error, but using</p> <pre><code>t = TemplateLookup(directories=['/tmp'], default_filters=['trim']) </code></pre> <p>dramatically cut down on whitespace bleed. Additional savings can be found by checking the compiled template's and looking for any writes that are just pushing ' ' or similar. </p>
2
2009-01-24T18:14:20Z
[ "python", "layout", "template-engine", "mako" ]
Is there a way to install the scipy special module without the rest of scipy?
476,369
<p>I'm writing some Python numerical code and would like to use some functions from the <a href="http://scipy.org/SciPyPackages/Special" rel="nofollow">special module</a>. So far, my code only depends on numpy, which I've found very easy to install in a variety of Python environments. Installing scipy, on the other hand, has generally been an exercise in frustration. Is there a way to get just the special module?</p> <p><em>Note, I see now that there is a downloadable scipy package for the Mac, but that hasn't always been the case</em></p>
3
2009-01-24T17:26:24Z
476,376
<p>I'm not familiar with <em>scipy</em> in particular, but in general, modules for software packages depend on the installation of the package itself. So, yes, I'm pretty sure that you need to install <em>scipy</em> to use the special module.</p>
0
2009-01-24T17:35:03Z
[ "python", "numpy", "package", "scipy" ]
Is there a way to install the scipy special module without the rest of scipy?
476,369
<p>I'm writing some Python numerical code and would like to use some functions from the <a href="http://scipy.org/SciPyPackages/Special" rel="nofollow">special module</a>. So far, my code only depends on numpy, which I've found very easy to install in a variety of Python environments. Installing scipy, on the other hand, has generally been an exercise in frustration. Is there a way to get just the special module?</p> <p><em>Note, I see now that there is a downloadable scipy package for the Mac, but that hasn't always been the case</em></p>
3
2009-01-24T17:26:24Z
476,655
<p>If you already have the right version of Numpy installed then you could try to just take the source for the special module, stick it in a directory somewhere, add it to your PYTHONPATH, and see if it works. It all depends on its dependencies. If it has dependencies beyond Numpy, then you'll have to install those, and if those have dependencies...</p>
0
2009-01-24T21:07:12Z
[ "python", "numpy", "package", "scipy" ]
Is there a way to install the scipy special module without the rest of scipy?
476,369
<p>I'm writing some Python numerical code and would like to use some functions from the <a href="http://scipy.org/SciPyPackages/Special" rel="nofollow">special module</a>. So far, my code only depends on numpy, which I've found very easy to install in a variety of Python environments. Installing scipy, on the other hand, has generally been an exercise in frustration. Is there a way to get just the special module?</p> <p><em>Note, I see now that there is a downloadable scipy package for the Mac, but that hasn't always been the case</em></p>
3
2009-01-24T17:26:24Z
476,886
<p>The scipy subpackages can usually be installed individually. Try cd-ing to the "<code>special</code>" directory and running your normal "<code>python setup.py install</code>". The name space for importing should now be <code>special</code> and now <code>scipy.special</code>.</p>
2
2009-01-24T23:35:24Z
[ "python", "numpy", "package", "scipy" ]
Django "Did you mean?" query
476,394
<p>I am writing a fairly simple Django application where users can enter string queries. The application will the search through the database for this string.</p> <pre><code>Entry.objects.filter(headline__contains=query) </code></pre> <p>This query is pretty strait forward but not really helpful to someone who isn't 100% sure what they are looking for. So I expanded the search.</p> <pre><code>from django.utils import stopwords results = Entry.objects.filter(headline__contains=query) if(!results): query = strip_stopwords(query) for(q in query.split(' ')): results += Entry.objects.filter(headline__contains=q) </code></pre> <p>I would like to add some additional functionality to this. Searching for miss spelled words, plurals, common homophones (sound the same spelled differently), ect. I was just wondering if any of these things were built into Djangos query language. It isn't important enough for me to write a huge algorithm for I am really just looking for something built in.</p> <p>Thanks in advance for all the answers.</p>
3
2009-01-24T17:47:30Z
476,420
<p>You could try using python's <a href="http://docs.python.org/library/difflib">difflib</a> module.</p> <pre><code>&gt;&gt;&gt; from difflib import get_close_matches &gt;&gt;&gt; get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) ['apple', 'ape'] &gt;&gt;&gt; import keyword &gt;&gt;&gt; get_close_matches('wheel', keyword.kwlist) ['while'] &gt;&gt;&gt; get_close_matches('apple', keyword.kwlist) [] &gt;&gt;&gt; get_close_matches('accept', keyword.kwlist) ['except'] </code></pre> <p>Problem is that to use difflib one must build a list of words from the database. That can be expensive. Maybe if you cache the list of words and only rebuild it once in a while.</p> <p>Some database systems support a search method to do what you want, like PostgreSQL's <a href="http://www.postgresql.org/docs/8.3/static/fuzzystrmatch.html"><code>fuzzystrmatch</code></a> module. If that is your case you could try calling it.</p> <p><hr /></p> <p><strong>edit:</strong></p> <p>For your new "requirement", well, you are out of luck. No, there is nothing built in inside django's query language.</p>
9
2009-01-24T18:07:09Z
[ "python", "django", "spell-checking" ]
Django "Did you mean?" query
476,394
<p>I am writing a fairly simple Django application where users can enter string queries. The application will the search through the database for this string.</p> <pre><code>Entry.objects.filter(headline__contains=query) </code></pre> <p>This query is pretty strait forward but not really helpful to someone who isn't 100% sure what they are looking for. So I expanded the search.</p> <pre><code>from django.utils import stopwords results = Entry.objects.filter(headline__contains=query) if(!results): query = strip_stopwords(query) for(q in query.split(' ')): results += Entry.objects.filter(headline__contains=q) </code></pre> <p>I would like to add some additional functionality to this. Searching for miss spelled words, plurals, common homophones (sound the same spelled differently), ect. I was just wondering if any of these things were built into Djangos query language. It isn't important enough for me to write a huge algorithm for I am really just looking for something built in.</p> <p>Thanks in advance for all the answers.</p>
3
2009-01-24T17:47:30Z
476,527
<p>djangos orm doesn't have this behavior out-of-box, but there are several projects that integrate django w/ search services like: </p> <ul> <li>sphinx (<a href="http://github.com/dcramer/django-sphinx/tree/master" rel="nofollow">django-sphinx</a>)</li> <li>solr, a lightweight version of lucene (<a href="https://code.google.com/p/django-solr-search/" rel="nofollow">djangosearch</a>)</li> <li>lucene (<a href="http://code.google.com/p/django-search-lucene/" rel="nofollow">django-search-lucene</a>)</li> </ul> <p>I cant speak to how well options #2 and #3 work, but I've used django-sphinx quite a lot, and am very happy with the results. </p>
5
2009-01-24T19:31:54Z
[ "python", "django", "spell-checking" ]
Python Regular Expression to add links to urls
476,478
<p>I'm trying to make a regular expression that will correctly capture URLs, including ones that are wrapped in parenthesis as in (<a href="http://example.com" rel="nofollow">http://example.com</a>) and spoken about on coding horror at <a href="http://www.codinghorror.com/blog/archives/001181.html" rel="nofollow">http://www.codinghorror.com/blog/archives/001181.html</a></p> <p>I'm currently using the following to create HTML A tags in python for links that start with http and www.</p> <pre><code>r1 = r"(\b(http|https)://([-A-Za-z0-9+&amp;@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&amp;@#/%=~_()|]))" r2 = r"((^|\b)www\.([-A-Za-z0-9+&amp;@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&amp;@#/%=~_()|]))" return re.sub(r2,r'&lt;a rel="nofollow" target="_blank" href="http://\1"&gt;\1&lt;/a&gt;',re.sub(r1,r'&lt;a rel="nofollow" target="_blank" href="\1"&gt;\1&lt;/a&gt;',text)) </code></pre> <p>this works well except for the case where someone wraps the url in parens. Does anyone have a better way?</p>
4
2009-01-24T18:48:33Z
476,493
<p>Problem is, URLs could have parenthesis as part of them... (<a href="http://en.wikipedia.org/wiki/Tropical_Storm_Alberto_(2006)" rel="nofollow">http://en.wikipedia.org/wiki/Tropical_Storm_Alberto_(2006)</a>) . You can't treat that with regexp alone, since it doesn't have state. You need a parser. So your best chance would be to use a parser, and try to guess the correct close parenthesis. That is error-prone (the url could open parenthesis and never close it) so I guess you're out of luck anyway.</p> <p>See also <a href="http://en.wikipedia.org/wiki/," rel="nofollow">http://en.wikipedia.org/wiki/,</a> or (<a href="http://en.wikipedia.org/wiki/)" rel="nofollow">http://en.wikipedia.org/wiki/)</a>) and other similar valid URLs.</p>
4
2009-01-24T18:57:39Z
[ "python", "regex", "url" ]
Resolving a relative url path to its absolute path
476,511
<p>Is there a library in python that works like this?</p> <pre><code>&gt;&gt;&gt; resolvePath("http://www.asite.com/folder/currentpage.html", "anotherpage.html") 'http://www.asite.com/folder/anotherpage.html' &gt;&gt;&gt; resolvePath("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html") 'http://www.asite.com/folder/folder2/anotherpage.html' &gt;&gt;&gt; resolvePath("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html") 'http://www.asite.com/folder3/anotherpage.html' &gt;&gt;&gt; resolvePath("http://www.asite.com/folder/currentpage.html", "../finalpage.html") 'http://www.asite.com/finalpage.html' </code></pre>
43
2009-01-24T19:09:59Z
476,521
<p>Yes, there is <a href="https://docs.python.org/2/library/urlparse.html#urlparse.urljoin"><code>urlparse.urljoin</code></a>, or <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin"><code>urllib.parse.urljoin</code></a> for Python 3.</p> <pre><code>&gt;&gt;&gt; try: from urlparse import urljoin # Python2 ... except ImportError: from urllib.parse import urljoin # Python3 ... &gt;&gt;&gt; urljoin("http://www.asite.com/folder/currentpage.html", "anotherpage.html") 'http://www.asite.com/folder/anotherpage.html' &gt;&gt;&gt; urljoin("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html") 'http://www.asite.com/folder/folder2/anotherpage.html' &gt;&gt;&gt; urljoin("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html") 'http://www.asite.com/folder3/anotherpage.html' &gt;&gt;&gt; urljoin("http://www.asite.com/folder/currentpage.html", "../finalpage.html") 'http://www.asite.com/finalpage.html' </code></pre> <p>for copy-and-paste:</p> <pre><code>try: from urlparse import urljoin # Python2 except ImportError: from urllib.parse import urljoin # Python3 </code></pre>
70
2009-01-24T19:20:19Z
[ "python", "url", "path" ]
Is anyone using meta-meta-classes / meta-meta-meta-classes in Python/ other languages?
476,586
<p>I recently discovered metaclasses in python. </p> <p>Basically a metaclass in python is a class that creates a class. There are many useful reasons why you would want to do this - any kind of class initialisation for example. Registering classes on factories, complex validation of attributes, altering how inheritance works, etc. All of this becomes not only possible but simple.</p> <p>But in python, metaclasses are also plain classes. So, I started wondering if the abstraction could usefully go higher, and it seems to me that it can and that:</p> <ul> <li>a metaclass corresponds to or implements a role in a pattern (as in GOF pattern languages). </li> <li>a meta-metaclass is the pattern itself (if we allow it to create tuples of classes representing abstract roles, rather than just a single class)</li> <li>a meta-meta-metaclass is a <em>pattern factory</em>, which corresponds to the GOF pattern groupings, e.g. Creational, Structural, Behavioural. A factory where you could describe a case of a certain type of problem and it would give you a set of classes that solved it.</li> <li>a meta-meta-meta-metaclass (as far as I could go), is a <em>pattern factory factory</em>, a factory to which you could perhaps describe the type of your problem and it would give you a pattern factory to ask.</li> </ul> <p>I have found some stuff about this online, but mostly not very useful. One problem is that different languages define metaclasses slightly differently.</p> <p>Has anyone else used metaclasses like this in python/elsewhere, or seen this used in the wild, or thought about it? What are the analogues in other languages? E.g. in C++ how deep can the template recursion go?</p> <p>I'd very much like to research it further.</p>
13
2009-01-24T20:10:48Z
476,633
<p>To answer your question: no.</p> <p>Feel free to research it further. </p> <p>Note, however, that you've conflated design patterns (which are just ideas) with code (which is an implementation.)</p> <p>Good code often reflects a number of interlocking design patterns. There's no easy way for formalize this. The best you can do is a nice picture, well-written docstrings, and method names that reflect the various design patterns.</p> <p>Also note that a meta-class is a class. That's a loop. There's no higher level of abstractions. At that point, it's just intent. The idea of meta-meta-class doesn't mean much -- it's a meta-class for meta-classes, which is silly but technically possible. It's all just a class, however.</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>"Are classes that create metaclasses really so silly? How does their utility suddenly run out?"</p> <p>A class that creates a class is fine. That's pretty much it. The fact that the target class is a meta class or an abstract superclass or a concrete class doesn't matter. Metaclasses make classes. They might make other metaclasses, which is weird, but they're still just metaclasses making classes.</p> <p>The utility "suddenly" runs out because there's no actual thing you need (or can even write) in a metaclass that makes another metaclass. It isn't that it "suddenly" becomes silly. It's that there's nothing useful there.</p> <p>As I seed, feel free to research it. For example, actually write a metaclass that builds another metaclass. Have fun. There might be something useful there.</p> <p>The point of OO is to write class definitions that model real-world entities. As such, a metaclass is sometimes handy to define cross-cutting aspects of several related classes. (It's a way to do some Aspect-Oriented Programming.) That's all a metaclass can really do; it's a place to hold a few functions, like <code>__new__()</code>, that aren't proper parts of the class itself.</p>
6
2009-01-24T20:49:28Z
[ "python", "metaprogramming", "design-patterns", "factory", "metaclass" ]
Is anyone using meta-meta-classes / meta-meta-meta-classes in Python/ other languages?
476,586
<p>I recently discovered metaclasses in python. </p> <p>Basically a metaclass in python is a class that creates a class. There are many useful reasons why you would want to do this - any kind of class initialisation for example. Registering classes on factories, complex validation of attributes, altering how inheritance works, etc. All of this becomes not only possible but simple.</p> <p>But in python, metaclasses are also plain classes. So, I started wondering if the abstraction could usefully go higher, and it seems to me that it can and that:</p> <ul> <li>a metaclass corresponds to or implements a role in a pattern (as in GOF pattern languages). </li> <li>a meta-metaclass is the pattern itself (if we allow it to create tuples of classes representing abstract roles, rather than just a single class)</li> <li>a meta-meta-metaclass is a <em>pattern factory</em>, which corresponds to the GOF pattern groupings, e.g. Creational, Structural, Behavioural. A factory where you could describe a case of a certain type of problem and it would give you a set of classes that solved it.</li> <li>a meta-meta-meta-metaclass (as far as I could go), is a <em>pattern factory factory</em>, a factory to which you could perhaps describe the type of your problem and it would give you a pattern factory to ask.</li> </ul> <p>I have found some stuff about this online, but mostly not very useful. One problem is that different languages define metaclasses slightly differently.</p> <p>Has anyone else used metaclasses like this in python/elsewhere, or seen this used in the wild, or thought about it? What are the analogues in other languages? E.g. in C++ how deep can the template recursion go?</p> <p>I'd very much like to research it further.</p>
13
2009-01-24T20:10:48Z
476,641
<p>This reminds me of the eternal quest some people seem to be on to make a "generic implementation of a pattern." Like a factory that can create any object (<a href="http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12">including another factory</a>), or a general-purpose dependency injection framework that is far more complex to manage than simply writing code that actually <em>does</em> something.</p> <p>I had to deal with people intent on abstraction to the point of navel-gazing when I was managing the Zend Framework project. I turned down a bunch of proposals to create components that didn't do anything, they were just magical implementations of GoF patterns, as though the pattern were a goal in itself, instead of a means to a goal.</p> <p>There's a point of diminishing returns for abstraction. Some abstraction is great, but eventually you need to write code that does something useful.</p> <p>Otherwise it's just <a href="http://en.wikipedia.org/wiki/Turtles_all_the_way_down">turtles all the way down</a>.</p>
18
2009-01-24T21:00:00Z
[ "python", "metaprogramming", "design-patterns", "factory", "metaclass" ]
Is anyone using meta-meta-classes / meta-meta-meta-classes in Python/ other languages?
476,586
<p>I recently discovered metaclasses in python. </p> <p>Basically a metaclass in python is a class that creates a class. There are many useful reasons why you would want to do this - any kind of class initialisation for example. Registering classes on factories, complex validation of attributes, altering how inheritance works, etc. All of this becomes not only possible but simple.</p> <p>But in python, metaclasses are also plain classes. So, I started wondering if the abstraction could usefully go higher, and it seems to me that it can and that:</p> <ul> <li>a metaclass corresponds to or implements a role in a pattern (as in GOF pattern languages). </li> <li>a meta-metaclass is the pattern itself (if we allow it to create tuples of classes representing abstract roles, rather than just a single class)</li> <li>a meta-meta-metaclass is a <em>pattern factory</em>, which corresponds to the GOF pattern groupings, e.g. Creational, Structural, Behavioural. A factory where you could describe a case of a certain type of problem and it would give you a set of classes that solved it.</li> <li>a meta-meta-meta-metaclass (as far as I could go), is a <em>pattern factory factory</em>, a factory to which you could perhaps describe the type of your problem and it would give you a pattern factory to ask.</li> </ul> <p>I have found some stuff about this online, but mostly not very useful. One problem is that different languages define metaclasses slightly differently.</p> <p>Has anyone else used metaclasses like this in python/elsewhere, or seen this used in the wild, or thought about it? What are the analogues in other languages? E.g. in C++ how deep can the template recursion go?</p> <p>I'd very much like to research it further.</p>
13
2009-01-24T20:10:48Z
476,743
<p>The class system in Smalltalk is an interesting one to study. In Smalltalk, everything is an object and every object has a class. This doesn't imply that the hierarchy goes to infinity. If I remember correctly, it goes something like:</p> <p>5 -> Integer -> Integer class -> Metaclass -> Metaclass class -> Metaclass -> ... (it loops)</p> <p>Where '->' denotes "is an instance of".</p>
4
2009-01-24T22:08:59Z
[ "python", "metaprogramming", "design-patterns", "factory", "metaclass" ]
Is anyone using meta-meta-classes / meta-meta-meta-classes in Python/ other languages?
476,586
<p>I recently discovered metaclasses in python. </p> <p>Basically a metaclass in python is a class that creates a class. There are many useful reasons why you would want to do this - any kind of class initialisation for example. Registering classes on factories, complex validation of attributes, altering how inheritance works, etc. All of this becomes not only possible but simple.</p> <p>But in python, metaclasses are also plain classes. So, I started wondering if the abstraction could usefully go higher, and it seems to me that it can and that:</p> <ul> <li>a metaclass corresponds to or implements a role in a pattern (as in GOF pattern languages). </li> <li>a meta-metaclass is the pattern itself (if we allow it to create tuples of classes representing abstract roles, rather than just a single class)</li> <li>a meta-meta-metaclass is a <em>pattern factory</em>, which corresponds to the GOF pattern groupings, e.g. Creational, Structural, Behavioural. A factory where you could describe a case of a certain type of problem and it would give you a set of classes that solved it.</li> <li>a meta-meta-meta-metaclass (as far as I could go), is a <em>pattern factory factory</em>, a factory to which you could perhaps describe the type of your problem and it would give you a pattern factory to ask.</li> </ul> <p>I have found some stuff about this online, but mostly not very useful. One problem is that different languages define metaclasses slightly differently.</p> <p>Has anyone else used metaclasses like this in python/elsewhere, or seen this used in the wild, or thought about it? What are the analogues in other languages? E.g. in C++ how deep can the template recursion go?</p> <p>I'd very much like to research it further.</p>
13
2009-01-24T20:10:48Z
2,090,276
<p>During the History of Programming Languages conference in 2007, Simon Peyton Jones commented that Haskell allows meta programming using Type Classes, but that its really turtles all the way down. You can meta-meta-meta-meta etc program in Haskell, but that he's never heard of anyone using more than 3 levels of indirection.</p> <p>Guy Steele pointed out that its the same thing in Lisp and Scheme. You can do meta-programming using backticks and evals (you can think of a backtick as a Python lambda, kinda), but he's never seen more than 3 backticks used.</p> <p>Presumably they have seen more code than you or I ever has, so its only a slight exaggeration to say that no-one has ever gone beyond 3 levels of meta.</p> <p>If you think about it, most people don't ever use meta-programming, and two levels is pretty hard to wrap your head around. I would guess that three is nearly impossible, and the that last guy to try four ended up in an asylum.</p>
5
2010-01-19T00:39:14Z
[ "python", "metaprogramming", "design-patterns", "factory", "metaclass" ]
Cygwin and Python 2.6
476,659
<p>New to python (and programming). What exactly do I need from Cygwin? I'm running python 2.6 on winxp. Can I safely download the complete Cygwin? It just seems like a huge bundle of stuff.</p> <p>Well, I keep running into modules and functionality (i.e. piping output) which suggest downloading various cygwin components. Will cygwin change or modify any other os functionality or have any other side effects?</p>
2
2009-01-24T21:09:26Z
476,666
<p>There are builds of python which don't require cygwin. For instance (from python.org):</p> <p><a href="http://www.python.org/download/releases/" rel="nofollow">link text</a></p> <p>Also, there is the .NET version called Iron Python:</p> <p><a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython" rel="nofollow">link text</a></p>
2
2009-01-24T21:16:23Z
[ "python", "windows-xp", "cygwin", "python-2.6" ]
Cygwin and Python 2.6
476,659
<p>New to python (and programming). What exactly do I need from Cygwin? I'm running python 2.6 on winxp. Can I safely download the complete Cygwin? It just seems like a huge bundle of stuff.</p> <p>Well, I keep running into modules and functionality (i.e. piping output) which suggest downloading various cygwin components. Will cygwin change or modify any other os functionality or have any other side effects?</p>
2
2009-01-24T21:09:26Z
476,809
<p>cygwin is effectively a Unix subkernel. Setup and installed in its default manner it won't interrupt or change any existing Windows XP functionality. However, you'll have to start the cygwin equivalent of the command prompt before you can use its functionality. </p> <p>With that said, some of the functionality you're talking about is available in Windows. Piping definitely is. For instance:</p> <p>netstat -ano | findstr :1433</p> <p>is a command line I use to make sure my SQL Server is listening on the default port. The output of netstat is being piped to findstr so I only have to see any lines containing :1433.</p>
1
2009-01-24T22:42:08Z
[ "python", "windows-xp", "cygwin", "python-2.6" ]
Cygwin and Python 2.6
476,659
<p>New to python (and programming). What exactly do I need from Cygwin? I'm running python 2.6 on winxp. Can I safely download the complete Cygwin? It just seems like a huge bundle of stuff.</p> <p>Well, I keep running into modules and functionality (i.e. piping output) which suggest downloading various cygwin components. Will cygwin change or modify any other os functionality or have any other side effects?</p>
2
2009-01-24T21:09:26Z
10,878,598
<p>I would say the simplest option is to try a Linux Distro. I know if your new Linux can be intimidating, but when I looked at Ubuntu and started developing there my life was changed. Ubuntu is bloated (for linux) however, it comes with the things that I would expect a Microsoft based OS to come pre-packaged with. The limitless amount of free software written by creative minds for creative minds is a wonder. The open-source community is great to get involved in for learning and experience. I can vouch that programming on Linux in any language (except myabe . . . .NET ?) will be a much pleasurable experience from the go. One is windows paths, sure you can still create portable Python applications that will port to windows, it just requires another couple lines of replacing characters and escaping them. If they are personal apps this can be bothersome if you do not plan to distribute them. </p> <p>I found Ubuntu to be a nice balance suited towards both general usability, and development. </p> <p>Stock Distro: Python 2.7 Perl XTerm MP3 Player that kills WMP and Winamp =+ V.3.0 E-Mail w/ Thunderbird ( much like outlook express by the makers of Fire Fox browser with add-on and extensions) Empathy (Internet Chat Client for AIM, ICQ, FACEBOOK, MySpace, etc . . it also keeps all your contacts on one list and operates just like AIM for all accounts) Gwibber (social networking app that compiles the posts made on your twitter and your Facebook wall into a nice desktop widget that also allows you to reply and comment right from the app.)</p> <p>Multiple Desktop Support: You can change your "desktop view" by pressing a hot key. Each desktop only has the windows you want on it. So you can create a work space, a chat space, a web browsing space and alternate between them quickly. You can also move windows around between work spaces quickly as needed.</p> <p>Global Hot-Key Mapper: In your administration options you have an OS wide hot-key map. You can launch programs, and many other tasks simply by assigning a hot-key through the default interface.</p> <p>Bash, Terminal, Shell, XTerm: These CLI (command line interfaces) offer much more functionality as you found than can be generally found in windows. Yes you can pipe output in windows but that's not what this is about. These CLIs allow you to create scripts that can take user input and perform complex tasks that usually would have to be done manually. The BASH is somewhat a programming language of itself; allowing for the assignment of functions, variables, if statements, etc.</p> <p>I was very surprised that not only was Ubuntu well and ready to handle the developer but it was also plenty user friendly for your grand-parents. It comes with everything you need out of the box (for an average user not a developer) and the developer only requires a few installs. You're also working in open-source software remember. So you are going to be dealing with bugs and you may be stuck waiting on a ticket to be resolved in Windows for some time. If ever. </p> <p>Also, Ubuntu is boot-able from CD and you can check out the main interface just by doing so. You can also dual-boot it with a screen asking you which partition/disk to boot after POST boot. There is also a tutorial on running it off a thumb drive.</p> <p>Linux and the speed of your computer: Linux compared to say Windows 7 is EXTREMELY lightweight. What is considered to be a MID level computer such as an AMD Phenom 955 Black Edition x4 and it will run like a high level computer. 1 gib of memory goes quite a bit further in Linux than it does in windows.</p> <p>The best way to try a Linux distro is as follows. You do not have to install it on the system. You can sandbox it with a virtual environment if you like it and want the speed and overhead improvements of running it stand-alone maybe consider the dual-boot at first followed by the "change".</p> <p>Download the Linux Dist ISO of your choosing. For new users again Ubuntu, Mint, something simple. Something debian. Mostly due to the ease of using a good package manager. Download <a href="https://www.virtualbox.org/" rel="nofollow" title="Oracle Virtual Box">Oracle Virtual Box</a> . Follow the instructions, create a new virtual disk, then start the virtual disk with install media placed in DVD drive or virtual DVD drive and install like a normal OS.</p> <p>In my experience unless it is essential that you be using windows all the time, there is no reason not to try a Linux Distro. Just be careful because something like ArchLinux or SlackWare may scare you off right away; where as distros like Ubuntu, Mint, and others have built in GUI right off the bat. Linux comes in many varieties. It is more loosely coupled than windows you for example you can use any desktop environment you want. Linux is just a kernal. The distros are collections of tools the group maintaining the distro thinks will fit their over-all goal and purpose. Desktop Environments, programming tools, package managers, and other freely licensed pieces of software.</p>
0
2012-06-04T08:47:26Z
[ "python", "windows-xp", "cygwin", "python-2.6" ]
Resources for TDD aimed at Python Web Development
476,668
<p>I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.</p> <p>Are there any particular ones you would recommend for this language/application?</p>
15
2009-01-24T21:19:07Z
476,689
<p>I know that Kent Beck's book (which you mentioned) covers TDD in Python to some pretty good depth. If I remember correctly, the last half of the book takes you through development of a unit test framework in Python. There's nothing specific to web development, though, which is a problem in many TDD resources that I've read. It's a best practice to keep your business logic separate from your presentation in order to make your BL more testable, among other reasons.</p> <p>Another good book that you might want to look into is <a href="http://rads.stackoverflow.com/amzn/click/0131495054" rel="nofollow">xUnit Test Patterns</a>. It doesn't use Python, but it does talk a lot about designing for testability, how to use mocks and stubs (which you'll need for testing web applications), and automating testing. It's more advanced than Beck's book, which makes it a good follow-up.</p>
2
2009-01-24T21:32:14Z
[ "python", "tdd", "testing" ]
Resources for TDD aimed at Python Web Development
476,668
<p>I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.</p> <p>Are there any particular ones you would recommend for this language/application?</p>
15
2009-01-24T21:19:07Z
476,690
<p>I'd recommend "xUnit Test Patterns: Refactoring Test Code" by Gerard Meszaros. It is not Python or Web specific, but it's a good book on TDD in general and the xUnit framework in particular. Since python unittest is actually an xUnit implementation ("a Python version of JUnit", as the docs say), I'd say that the book is very useful for Python unit testers.</p> <p>It has an online version at <a href="http://xunitpatterns.com/" rel="nofollow">xunitpatterns.com</a>.</p>
2
2009-01-24T21:32:16Z
[ "python", "tdd", "testing" ]
Resources for TDD aimed at Python Web Development
476,668
<p>I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.</p> <p>Are there any particular ones you would recommend for this language/application?</p>
15
2009-01-24T21:19:07Z
476,858
<p>I wrote a series of blogs on <a href="http://blog.cerris.com/category/django-tdd/">TDD in Django</a> that covers some TDD with the <a href="http://somethingaboutorange.com/mrl/projects/nose/">nose testing framework</a>.</p> <p>There are a lot of free online resources out there for learning about TDD:</p> <ul> <li><a href="http://c2.com/cgi-bin/wiki?TestDrivenDevelopment">The c2 wiki article</a> gives good background on general TDD philosophy.</li> <li><a href="http://www.onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html">The onlamp article</a> is a simple introduction.</li> <li>Here's a presentation on <a href="http://powertwenty.com/kpd/blog/index.php/python/test_driven_development_in_python">TDD with game development in pygame</a> that really helped me understand TDD.</li> </ul> <p>For testing web applications, test first or otherwise, I'd recommend <a href="http://twill.idyll.org/">twill</a> and <a href="http://seleniumhq.org/">selenium</a> as tools to use.</p>
13
2009-01-24T23:08:13Z
[ "python", "tdd", "testing" ]
Resources for TDD aimed at Python Web Development
476,668
<p>I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.</p> <p>Are there any particular ones you would recommend for this language/application?</p>
15
2009-01-24T21:19:07Z
2,856,092
<p>A very good unit test framework is also <a href="http://twistedmatrix.com/trac/wiki/TwistedTrial" rel="nofollow">trial</a> from the twisted project.</p>
0
2010-05-18T09:46:22Z
[ "python", "tdd", "testing" ]
Resources for TDD aimed at Python Web Development
476,668
<p>I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.</p> <p>Are there any particular ones you would recommend for this language/application?</p>
15
2009-01-24T21:19:07Z
6,887,352
<p>A little late to the game with this one, but I have been hunting for a Python oriented TDD book, and I just found <a href="http://rads.stackoverflow.com/amzn/click/1847198848" rel="nofollow">Python Testing: Beginner's Guide by Daniel Arbuckle</a>. Haven't had a chance to read it yet, but when I do, I'll try to remember to post a follow up here. The reviews on the Amazon page look pretty positive though. </p>
0
2011-07-31T03:22:50Z
[ "python", "tdd", "testing" ]
Resources for TDD aimed at Python Web Development
476,668
<p>I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.</p> <p>Are there any particular ones you would recommend for this language/application?</p>
15
2009-01-24T21:19:07Z
10,648,767
<p>Can I plug my own tutorial, which covers the materials from the official Django tutorial, but uses full TDD all the way - including "proper" functional/acceptance tests using the Selenium browser-automation tool... <a href="http://tdd-django-tutorial.com" rel="nofollow">http://tdd-django-tutorial.com</a> </p> <p>[update 2014-01] I now have a book, just about to be published by OReilly, that covers all the stuff from the tutorial and much more. The full thing is available online (free) at <a href="http://www.obeythetestinggoat.com" rel="nofollow">http://www.obeythetestinggoat.com</a></p>
8
2012-05-18T07:50:46Z
[ "python", "tdd", "testing" ]
Resources for TDD aimed at Python Web Development
476,668
<p>I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.</p> <p>Are there any particular ones you would recommend for this language/application?</p>
15
2009-01-24T21:19:07Z
12,446,364
<p><a href="http://blog.fruiapps.com/tag/test-driven-development" rel="nofollow">Here</a> is a great series of article written on test driven development in python. It starts from basic and goes to a point, where you are taught stuffs as designing for maintainability etc. I am sure you would like it.</p>
1
2012-09-16T11:07:36Z
[ "python", "tdd", "testing" ]
Get foreign key without requesting the whole object
476,731
<p>I have a model Foo which have a ForeignKey to the User model.</p> <p>Later, I need to grab all the User's id and put then on a list</p> <pre><code>foos = Foo.objects.filter(...) l = [ f.user.id for f in foos ] </code></pre> <p>But when I do that, django grabs the whole User instance from the DB instead of giving me just the numeric user's id, which exist in each Foo row.</p> <p>How can I get all the ids without querying each user or using a select_related?</p> <p>Thanks</p>
0
2009-01-24T22:00:43Z
476,805
<p>Nevermind... I´m not sure why this didn´t work before when I tried, but this is how to do:</p> <pre><code>l = [ f.user_id for f in foos ] </code></pre>
0
2009-01-24T22:41:20Z
[ "python", "django", "django-models" ]
Get foreign key without requesting the whole object
476,731
<p>I have a model Foo which have a ForeignKey to the User model.</p> <p>Later, I need to grab all the User's id and put then on a list</p> <pre><code>foos = Foo.objects.filter(...) l = [ f.user.id for f in foos ] </code></pre> <p>But when I do that, django grabs the whole User instance from the DB instead of giving me just the numeric user's id, which exist in each Foo row.</p> <p>How can I get all the ids without querying each user or using a select_related?</p> <p>Thanks</p>
0
2009-01-24T22:00:43Z
476,967
<p>Use <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#values-fields" rel="nofollow">queryset's values() function</a>, which will return a list of dictionaries containing name/value pairs for each attribute passed as parameters:</p> <pre><code>&gt;&gt;&gt; Foo.objects.all().values('user__id') [{'user__id': 1}, {'user__id' 2}, {'user__id': 3}] </code></pre> <p>The ORM will then be able to optimize the SQL query to only return the required fields, instead of doing a "SELECT *".</p>
5
2009-01-25T00:41:14Z
[ "python", "django", "django-models" ]
Get foreign key without requesting the whole object
476,731
<p>I have a model Foo which have a ForeignKey to the User model.</p> <p>Later, I need to grab all the User's id and put then on a list</p> <pre><code>foos = Foo.objects.filter(...) l = [ f.user.id for f in foos ] </code></pre> <p>But when I do that, django grabs the whole User instance from the DB instead of giving me just the numeric user's id, which exist in each Foo row.</p> <p>How can I get all the ids without querying each user or using a select_related?</p> <p>Thanks</p>
0
2009-01-24T22:00:43Z
486,544
<p>Whenever you define a ForeignKey in Django, it automatically adds a FIELD_id field to your model.</p> <p>For instance, if <code>Foo</code> has a FK to <code>User</code> with an attribute named "<code>user</code>", then you also have an attribute named <strong>user_id</strong> which contains the id of the related user.</p> <pre><code>l = [ f.user_id for f in foos ] </code></pre> <p>Calling <code>.values()</code> also adds performance if you select your attributes wisely</p>
3
2009-01-28T05:11:17Z
[ "python", "django", "django-models" ]
python string join performance
476,772
<p>There are a lot of articles around the web concerning python performance, the first thing you read: concatenating strings should not be done using '+': avoid s1+s2+s3, instead use str.join</p> <p>I tried the following: concatenating two strings as part of a directory path: three approaches:</p> <ol> <li>'+' which i should not do</li> <li>str.join</li> <li>os.path.join</li> </ol> <p>Here is my code:</p> <pre><code>import os,time s1='/part/one/of/dir' s2='part/two/of/dir' N=10000 t=time.clock() for i in xrange(N): s=s1+os.sep+s2 print time.clock()-t t=time.clock() for i in xrange(N): s=os.sep.join((s1,s2)) print time.clock()-t t=time.clock() for i in xrange(N): s=os.path.join(s1,s2) print time.clock()-t </code></pre> <p>Here the results (python 2.5 WinXP)</p> <pre><code>0.0182201927899 0.0262544541275 0.120238186697 </code></pre> <p>Shouldn't it be exactly the other way round ?</p>
10
2009-01-24T22:26:13Z
476,787
<p>It is true you should not use '+'. Your example is quite special, try the same code with:</p> <pre><code>s1='*'*100000 s2='+'*100000 </code></pre> <p>Then the second version (str.join) is much faster.</p>
4
2009-01-24T22:32:25Z
[ "python", "performance", "string" ]
python string join performance
476,772
<p>There are a lot of articles around the web concerning python performance, the first thing you read: concatenating strings should not be done using '+': avoid s1+s2+s3, instead use str.join</p> <p>I tried the following: concatenating two strings as part of a directory path: three approaches:</p> <ol> <li>'+' which i should not do</li> <li>str.join</li> <li>os.path.join</li> </ol> <p>Here is my code:</p> <pre><code>import os,time s1='/part/one/of/dir' s2='part/two/of/dir' N=10000 t=time.clock() for i in xrange(N): s=s1+os.sep+s2 print time.clock()-t t=time.clock() for i in xrange(N): s=os.sep.join((s1,s2)) print time.clock()-t t=time.clock() for i in xrange(N): s=os.path.join(s1,s2) print time.clock()-t </code></pre> <p>Here the results (python 2.5 WinXP)</p> <pre><code>0.0182201927899 0.0262544541275 0.120238186697 </code></pre> <p>Shouldn't it be exactly the other way round ?</p>
10
2009-01-24T22:26:13Z
476,788
<p>Most of the performance issues with string concatenation are ones of asymptotic performance, so the differences become most significant when you are concatenating many long strings. In your sample, you are performing the same concatenation many times. You aren't building up any long string, and it may be that the python interpreter is optimizing your loops. This would explain why the time increases when you move to str.join and path.join - they are more complex functions that are not as easily reduced. (os.path.join does a lot of checking on the strings to see if they need to be rewritten in any way before they are concatenated. This sacrifices some performance for the sake of portability.)</p> <p>By the way, since file paths are not usually very long, you almost certainly want to use os.path.join for the sake of the portability. If the performance of the concatenation is a problem, you're doing something very odd with your filesystem.</p>
12
2009-01-24T22:32:32Z
[ "python", "performance", "string" ]
python string join performance
476,772
<p>There are a lot of articles around the web concerning python performance, the first thing you read: concatenating strings should not be done using '+': avoid s1+s2+s3, instead use str.join</p> <p>I tried the following: concatenating two strings as part of a directory path: three approaches:</p> <ol> <li>'+' which i should not do</li> <li>str.join</li> <li>os.path.join</li> </ol> <p>Here is my code:</p> <pre><code>import os,time s1='/part/one/of/dir' s2='part/two/of/dir' N=10000 t=time.clock() for i in xrange(N): s=s1+os.sep+s2 print time.clock()-t t=time.clock() for i in xrange(N): s=os.sep.join((s1,s2)) print time.clock()-t t=time.clock() for i in xrange(N): s=os.path.join(s1,s2) print time.clock()-t </code></pre> <p>Here the results (python 2.5 WinXP)</p> <pre><code>0.0182201927899 0.0262544541275 0.120238186697 </code></pre> <p>Shouldn't it be exactly the other way round ?</p>
10
2009-01-24T22:26:13Z
476,794
<blockquote> <p>Shouldn't it be exactly the other way round ?</p> </blockquote> <p>Not necessarily. I don't know the internals of Python well enough to comment specifically but some common observations are that your first loop uses a simple operator <code>+</code> which is probly implemented as a primitive by the runtime. In contrast, the other loops first have to resolve a module name, resolve the variable/class found there and then call a member function on that.</p> <p>Another note is that your loop might simply be too small to yield significant numbers. Considering your low overall running time, this probably makes your tests useless.</p> <p>Also, your test case is highly specialized on two short strings. Such cases never give a clear picture of edge case performance.</p>
5
2009-01-24T22:33:59Z
[ "python", "performance", "string" ]
python string join performance
476,772
<p>There are a lot of articles around the web concerning python performance, the first thing you read: concatenating strings should not be done using '+': avoid s1+s2+s3, instead use str.join</p> <p>I tried the following: concatenating two strings as part of a directory path: three approaches:</p> <ol> <li>'+' which i should not do</li> <li>str.join</li> <li>os.path.join</li> </ol> <p>Here is my code:</p> <pre><code>import os,time s1='/part/one/of/dir' s2='part/two/of/dir' N=10000 t=time.clock() for i in xrange(N): s=s1+os.sep+s2 print time.clock()-t t=time.clock() for i in xrange(N): s=os.sep.join((s1,s2)) print time.clock()-t t=time.clock() for i in xrange(N): s=os.path.join(s1,s2) print time.clock()-t </code></pre> <p>Here the results (python 2.5 WinXP)</p> <pre><code>0.0182201927899 0.0262544541275 0.120238186697 </code></pre> <p>Shouldn't it be exactly the other way round ?</p>
10
2009-01-24T22:26:13Z
476,893
<p>The advice is about concatenating a lot of strings.</p> <p>To compute s = s1 + s2 + ... + sn,</p> <p>1) using +. A new string s1+s2 is created, then a new string s1+s2+s3 is created,..., etc, so a lot of memory allocation and copy operations is involved. In fact, s1 is copied n-1 times, s2 is copied n-2 time, ..., etc.</p> <p>2) using "".join([s1,s2,...,sn]). The concatenation is done in one pass, and each char in the strings is copied only once.</p> <p>In your code, join is called on each iteration, so it's just like using +. The correct way is collect the items in an array, then call join on it.</p> <p>edit: fixed the typo</p>
4
2009-01-24T23:43:59Z
[ "python", "performance", "string" ]
python string join performance
476,772
<p>There are a lot of articles around the web concerning python performance, the first thing you read: concatenating strings should not be done using '+': avoid s1+s2+s3, instead use str.join</p> <p>I tried the following: concatenating two strings as part of a directory path: three approaches:</p> <ol> <li>'+' which i should not do</li> <li>str.join</li> <li>os.path.join</li> </ol> <p>Here is my code:</p> <pre><code>import os,time s1='/part/one/of/dir' s2='part/two/of/dir' N=10000 t=time.clock() for i in xrange(N): s=s1+os.sep+s2 print time.clock()-t t=time.clock() for i in xrange(N): s=os.sep.join((s1,s2)) print time.clock()-t t=time.clock() for i in xrange(N): s=os.path.join(s1,s2) print time.clock()-t </code></pre> <p>Here the results (python 2.5 WinXP)</p> <pre><code>0.0182201927899 0.0262544541275 0.120238186697 </code></pre> <p>Shouldn't it be exactly the other way round ?</p>
10
2009-01-24T22:26:13Z
476,921
<p>String concatenation (<code>+</code>) has an optimized implementation on CPython. But this may not be the case on other architectures like Jython or IronPython. So when you want your code to performe well on these interpreters you should use the <code>.join()</code> method on strings. <code>os.path.join()</code> is specifically meant to join filesystem paths. It takes care of different path separators, too. This would be the right way to build a file name.</p>
1
2009-01-25T00:00:58Z
[ "python", "performance", "string" ]
python string join performance
476,772
<p>There are a lot of articles around the web concerning python performance, the first thing you read: concatenating strings should not be done using '+': avoid s1+s2+s3, instead use str.join</p> <p>I tried the following: concatenating two strings as part of a directory path: three approaches:</p> <ol> <li>'+' which i should not do</li> <li>str.join</li> <li>os.path.join</li> </ol> <p>Here is my code:</p> <pre><code>import os,time s1='/part/one/of/dir' s2='part/two/of/dir' N=10000 t=time.clock() for i in xrange(N): s=s1+os.sep+s2 print time.clock()-t t=time.clock() for i in xrange(N): s=os.sep.join((s1,s2)) print time.clock()-t t=time.clock() for i in xrange(N): s=os.path.join(s1,s2) print time.clock()-t </code></pre> <p>Here the results (python 2.5 WinXP)</p> <pre><code>0.0182201927899 0.0262544541275 0.120238186697 </code></pre> <p>Shouldn't it be exactly the other way round ?</p>
10
2009-01-24T22:26:13Z
848,867
<p>I would like to add a link to the python wiki, where there are notes regarding string concatenation and also that "<em>this section is somewhat wrong with python2.5. Python 2.5 string concatenation is fairly fast</em>".</p> <p>I believe that string concatenation had a big improvement since 2.5, and that although str.join is still faster (specially for big strings), you will not see as much improvement as in older Python versions.</p> <p><a href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips#StringConcatenation" rel="nofollow">http://wiki.python.org/moin/PythonSpeed/PerformanceTips#StringConcatenation</a></p>
0
2009-05-11T16:18:24Z
[ "python", "performance", "string" ]
Splitting a large XML file in Python
476,949
<p>I'm looking to split a huge XML file into smaller bits. I'd like to scan through the file looking for a specific tag, then grab all info between and , then save that into a file, then continue on through the rest of the file.</p> <p>My issue is trying to find a clean way to note the start and end of the tags, so that I can grab the text inside as I scan through the file with "for line in f"</p> <p>I'd rather not use sentinel variables. Is there a pythonic way to get this done?</p> <p>The file is too big to read into memory. </p>
9
2009-01-25T00:22:01Z
476,958
<p>You might consider using the ElementTree <a href="https://docs.python.org/2/library/xml.etree.elementtree.html" rel="nofollow">iterparse</a> function for this situation.</p>
5
2009-01-25T00:32:07Z
[ "python", "xml" ]
Splitting a large XML file in Python
476,949
<p>I'm looking to split a huge XML file into smaller bits. I'd like to scan through the file looking for a specific tag, then grab all info between and , then save that into a file, then continue on through the rest of the file.</p> <p>My issue is trying to find a clean way to note the start and end of the tags, so that I can grab the text inside as I scan through the file with "for line in f"</p> <p>I'd rather not use sentinel variables. Is there a pythonic way to get this done?</p> <p>The file is too big to read into memory. </p>
9
2009-01-25T00:22:01Z
476,982
<p>There are two common ways to handle XML data.</p> <p>One is called DOM, which stands for Document Object Model. This style of XML parsing is probably what you have seen when looking at documentation, because it reads the entire XML into memory to create the object model.</p> <p>The second is called SAX, which is a streaming method. The parser starts reading the XML and sends signals to your code about certain events, e.g. when a new start tag is found.</p> <p>So SAX is clearly what you need for your situation. Sax parsers can be found in the python library under <a href="http://www.python.org/doc/2.5.2/lib/module-xml.sax.html" rel="nofollow">xml.sax</a> and <a href="http://www.python.org/doc/2.5.2/lib/module-xml.parsers.expat.html" rel="nofollow">xml.parsers.expat</a>.</p>
9
2009-01-25T00:49:08Z
[ "python", "xml" ]
Splitting a large XML file in Python
476,949
<p>I'm looking to split a huge XML file into smaller bits. I'd like to scan through the file looking for a specific tag, then grab all info between and , then save that into a file, then continue on through the rest of the file.</p> <p>My issue is trying to find a clean way to note the start and end of the tags, so that I can grab the text inside as I scan through the file with "for line in f"</p> <p>I'd rather not use sentinel variables. Is there a pythonic way to get this done?</p> <p>The file is too big to read into memory. </p>
9
2009-01-25T00:22:01Z
477,046
<p>How serendipitous! Will Larson just made a good post about <a href="http://lethain.com/entry/2009/jan/22/handling-very-large-csv-and-xml-files-in-python/" rel="nofollow">Handling Very Large CSV and XML File in Python</a>.</p> <p>The main takeaways seem to be to use the <code>xml.sax</code> module, as Van mentioned, and to make some macro-functions to abstract away the details of the low-level SAX API.</p>
1
2009-01-25T01:53:15Z
[ "python", "xml" ]
Splitting a large XML file in Python
476,949
<p>I'm looking to split a huge XML file into smaller bits. I'd like to scan through the file looking for a specific tag, then grab all info between and , then save that into a file, then continue on through the rest of the file.</p> <p>My issue is trying to find a clean way to note the start and end of the tags, so that I can grab the text inside as I scan through the file with "for line in f"</p> <p>I'd rather not use sentinel variables. Is there a pythonic way to get this done?</p> <p>The file is too big to read into memory. </p>
9
2009-01-25T00:22:01Z
488,947
<p>I have had success with the cElementTree.iterparse method in order to do a similar task.</p> <p>I had a large xml doc with repeated 'entries' with tag 'resFrame' and I wanted to filter out entries for a specific id. Here is the code that I used for it:</p> <p>source document had this structure</p> <pre><code>&lt;snapDoc&gt; &lt;bucket&gt;....&lt;/bucket&gt; &lt;bucket&gt;....&lt;/bucket&gt; &lt;bucket&gt;....&lt;/bucket&gt; ... &lt;resFrame&gt;&lt;id&gt;234234&lt;/id&gt;.....&lt;/resFrame&gt; &lt;frame&gt;&lt;id&gt;344234&lt;/id&gt;.....&lt;/frame&gt; &lt;resFrame&gt;...&lt;/resFrame&gt; &lt;frame&gt;...&lt;/frame&gt; &lt;/snapDoc&gt; </code></pre> <p>I used the following script to create a smaller doc that had the same structure, bucket entries and only resFrame entries with a specific id.</p> <pre><code>#!/usr/bin/env python2.6 import xml.etree.cElementTree as cElementTree start = '''&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;snapDoc&gt;''' def main(): print start context = cElementTree.iterparse('snap.xml', events=("start", "end")) context = iter(context) event, root = context.next() # get the root element of the XML doc for event, elem in context: if event == "end": if elem.tag == 'bucket': # i want to write out all &lt;bucket&gt; entries elem.tail = None print cElementTree.tostring( elem ) if elem.tag == 'resFrame': if elem.find("id").text == ":4:39644:482:-1:1": # i only want to write out resFrame entries with this id elem.tail = None print cElementTree.tostring( elem ) if elem.tag in ['bucket', 'frame', 'resFrame']: root.clear() # when done parsing a section clear the tree to safe memory print "&lt;/snapDoc&gt;" main() </code></pre>
6
2009-01-28T19:17:39Z
[ "python", "xml" ]
Splitting a large XML file in Python
476,949
<p>I'm looking to split a huge XML file into smaller bits. I'd like to scan through the file looking for a specific tag, then grab all info between and , then save that into a file, then continue on through the rest of the file.</p> <p>My issue is trying to find a clean way to note the start and end of the tags, so that I can grab the text inside as I scan through the file with "for line in f"</p> <p>I'd rather not use sentinel variables. Is there a pythonic way to get this done?</p> <p>The file is too big to read into memory. </p>
9
2009-01-25T00:22:01Z
1,075,441
<p>This is an old, but very good article from Uche Ogbuji's also very good Python &amp; XMl column. It covers your exact question and uses the standard lib's sax module like the other answer has suggested. <a href="http://www.xml.com/pub/a/2004/07/28/py-xml.html" rel="nofollow">Decomposition, Process, Recomposition</a></p>
0
2009-07-02T16:42:26Z
[ "python", "xml" ]
Using a java library from python
476,968
<p>I have a python app and java app. The python app generates input for the java app and invokes it on the command line.</p> <p>I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java.</p> <p>Any pointers? (FYI I'm v. new to Python) </p> <p><strong>Clarification</strong> (at the cost of a long question: apologies) The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app.</p> <p>So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM).</p> <p>Since there is no obvious mechanism for this I think the simple CL invocation is the best solution.</p>
25
2009-01-25T00:41:22Z
476,977
<p>Take a look at <a href="http://www.jython.org/">Jython</a>. It's kind of like JNI, but replace C with Python, i.e. you can call Python from Java and vice versa. It's not totally clear what you're trying to do or why your current approach isn't what you want.</p>
8
2009-01-25T00:46:46Z
[ "java", "python", "jython" ]
Using a java library from python
476,968
<p>I have a python app and java app. The python app generates input for the java app and invokes it on the command line.</p> <p>I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java.</p> <p>Any pointers? (FYI I'm v. new to Python) </p> <p><strong>Clarification</strong> (at the cost of a long question: apologies) The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app.</p> <p>So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM).</p> <p>Since there is no obvious mechanism for this I think the simple CL invocation is the best solution.</p>
25
2009-01-25T00:41:22Z
477,533
<p>Wrap your Java-Code in a Container (Servlet / EJB). </p> <p>So you don´t loose time in the vm-startup and you go the way to more service-oriented. </p> <p>For the wraping you can use jython (<em>only make sense if you are familiar with python</em>)</p> <p>Choose a communication-protocoll in which python and java can use:</p> <ul> <li>json (see www.json.org) </li> <li>rmi (Python: JPype)</li> <li>REST</li> <li>SOAP (only for the brave)</li> </ul> <p>Choose something you or your partners are familliar with!</p>
4
2009-01-25T10:50:46Z
[ "java", "python", "jython" ]
Using a java library from python
476,968
<p>I have a python app and java app. The python app generates input for the java app and invokes it on the command line.</p> <p>I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java.</p> <p>Any pointers? (FYI I'm v. new to Python) </p> <p><strong>Clarification</strong> (at the cost of a long question: apologies) The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app.</p> <p>So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM).</p> <p>Since there is no obvious mechanism for this I think the simple CL invocation is the best solution.</p>
25
2009-01-25T00:41:22Z
511,109
<p>If you really want to embed your Java app within your Python process, have a look at <a href="http://jpype.sourceforge.net/">JPype</a>. It provides access to Java through JNI.</p>
5
2009-02-04T12:18:07Z
[ "java", "python", "jython" ]
Using a java library from python
476,968
<p>I have a python app and java app. The python app generates input for the java app and invokes it on the command line.</p> <p>I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java.</p> <p>Any pointers? (FYI I'm v. new to Python) </p> <p><strong>Clarification</strong> (at the cost of a long question: apologies) The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app.</p> <p>So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM).</p> <p>Since there is no obvious mechanism for this I think the simple CL invocation is the best solution.</p>
25
2009-01-25T00:41:22Z
511,177
<p>How about using swig: <a href="http://www.swig.org/Doc1.3/Java.html" rel="nofollow">http://www.swig.org/Doc1.3/Java.html</a> ?</p>
3
2009-02-04T12:38:23Z
[ "java", "python", "jython" ]
Using a java library from python
476,968
<p>I have a python app and java app. The python app generates input for the java app and invokes it on the command line.</p> <p>I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java.</p> <p>Any pointers? (FYI I'm v. new to Python) </p> <p><strong>Clarification</strong> (at the cost of a long question: apologies) The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app.</p> <p>So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM).</p> <p>Since there is no obvious mechanism for this I think the simple CL invocation is the best solution.</p>
25
2009-01-25T00:41:22Z
511,209
<p>Give JCC a try <a href="http://pypi.python.org/pypi/JCC/2.1" rel="nofollow">http://pypi.python.org/pypi/JCC/2.1</a></p> <p>JCC is a code generator for calling Java directly from CPython. It supports CPython 2.3+, several JREs (Sun JDK 1.4+, Apple JRE 1.4+, and OpenJDK 1.7) on OS X, Linux, Solaris, and Windows. It's produced by the Open Source Application Foundation (OSAF, the people making Chandler) and is released under an Apache-style license.</p> <p>From the package description:</p> <blockquote> <p>JCC is a C++ code generator for producing the glue code necessary to call into Java classes from CPython via Java's Native Invocation Interface (JNI).</p> <p>JCC generates C++ wrapper classes that hide all the gory details of JNI access as well Java memory and object reference management.</p> <p>JCC generates CPython types that make these C++ classes accessible from a Python interpreter. JCC attempts to make these Python types pythonic by detecting iterators and property accessors. Iterators and mappings may also be declared to JCC.</p> </blockquote>
2
2009-02-04T12:54:28Z
[ "java", "python", "jython" ]
Using a java library from python
476,968
<p>I have a python app and java app. The python app generates input for the java app and invokes it on the command line.</p> <p>I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java.</p> <p>Any pointers? (FYI I'm v. new to Python) </p> <p><strong>Clarification</strong> (at the cost of a long question: apologies) The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app.</p> <p>So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM).</p> <p>Since there is no obvious mechanism for this I think the simple CL invocation is the best solution.</p>
25
2009-01-25T00:41:22Z
3,793,496
<p>Sorry to ressurect the thread, but there was no accepted answer...</p> <p>You could also use <a href="http://py4j.sourceforge.net/index.html">Py4J</a>. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:</p> <pre><code>&gt;&gt;&gt; from py4j.java_gateway import JavaGateway &gt;&gt;&gt; gateway = JavaGateway() # connect to the JVM &gt;&gt;&gt; java_object = gateway.jvm.mypackage.MyClass() # invoke constructor &gt;&gt;&gt; other_object = java_object.doThat() &gt;&gt;&gt; other_object.doThis(1,'abc') &gt;&gt;&gt; gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method </code></pre> <p>As opposed to Jython, Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The communication is done through sockets instead of JNI.</p> <p><em>Disclaimer: I am the author of Py4J</em></p>
37
2010-09-25T10:51:57Z
[ "java", "python", "jython" ]
How to read Unicode input and compare Unicode strings in Python?
477,061
<p>I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of <code>raw_input</code>?</p> <p>Also, I would like to test Unicode strings for equality and it looks like a standard <code>==</code> does not work.</p> <p>Thank you for your help !</p>
26
2009-01-25T02:19:21Z
477,084
<p>It should work. <code>raw_input</code> returns a byte string which you must decode using the correct encoding to get your <code>unicode</code> object. For example, the following works for me under Python 2.5 / Terminal.app / OSX:</p> <pre><code>&gt;&gt;&gt; bytes = raw_input() 日本語 Ελληνικά &gt;&gt;&gt; bytes '\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e \xce\x95\xce\xbb\xce\xbb\xce\xb7\xce\xbd\xce\xb9\xce\xba\xce\xac' &gt;&gt;&gt; uni = bytes.decode('utf-8') # substitute the encoding of your terminal if it's not utf-8 &gt;&gt;&gt; uni u'\u65e5\u672c\u8a9e \u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac' &gt;&gt;&gt; print uni 日本語 Ελληνικά </code></pre> <p>As for comparing unicode strings: can you post an example where the comparison doesn't work?</p>
14
2009-01-25T02:38:34Z
[ "python", "unicode" ]
How to read Unicode input and compare Unicode strings in Python?
477,061
<p>I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of <code>raw_input</code>?</p> <p>Also, I would like to test Unicode strings for equality and it looks like a standard <code>==</code> does not work.</p> <p>Thank you for your help !</p>
26
2009-01-25T02:19:21Z
477,087
<p>I'm not really sure, which format you mean by "Unicode format", there are several. UTF-8? UTF-16? In any case you should be able to read a normal string with <code>raw_input</code> and then decode it using the strings <code>decode</code> method:</p> <pre><code>raw = raw_input("Please input some funny characters: ") decoded = raw.decode("utf-8") </code></pre> <p>If you have a different input encoding just use "utf-16" or whatever instead of "utf-8". Also see <a href="http://docs.python.org/library/codecs.html#encodings-and-unicode" rel="nofollow">the codecs modules docs</a> for different kinds of encodings.</p> <p>Comparing then should work just fine with <code>==</code>. If you have string literals containing special characters you should prefix them with "u" to mark them as unicode:</p> <pre><code>if decoded == u"äöü": print "Do you speak German?" </code></pre> <p>And if you want to output these strings again, you probably want to encode them again in the desired encoding:</p> <pre><code>print decoded.encode("utf-8") </code></pre>
3
2009-01-25T02:42:49Z
[ "python", "unicode" ]
How to read Unicode input and compare Unicode strings in Python?
477,061
<p>I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of <code>raw_input</code>?</p> <p>Also, I would like to test Unicode strings for equality and it looks like a standard <code>==</code> does not work.</p> <p>Thank you for your help !</p>
26
2009-01-25T02:19:21Z
477,104
<p>In the general case, it's probably not possible to compare unicode strings. The problem is that there are several ways to compose the same characters. A simple example is accented roman characters. Although there are codepoints for basically all of the commonly used accented characters, it is also correct to compose them from unaccented base letters and a non-spacing accent. This issue is more significant in many non-roman alphabets. </p>
1
2009-01-25T03:20:14Z
[ "python", "unicode" ]
How to read Unicode input and compare Unicode strings in Python?
477,061
<p>I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of <code>raw_input</code>?</p> <p>Also, I would like to test Unicode strings for equality and it looks like a standard <code>==</code> does not work.</p> <p>Thank you for your help !</p>
26
2009-01-25T02:19:21Z
477,496
<p><a href="https://docs.python.org/2/library/functions.html#raw_input" rel="nofollow" title="raw_input()"><code>raw_input()</code></a> returns strings as encoded by the OS or UI facilities. The difficulty is knowing which is that decoding. You might attempt the following:</p> <pre><code>import sys, locale text= raw_input().decode(sys.stdin.encoding or locale.getpreferredencoding(True)) </code></pre> <p>which should work correctly in most of the cases.</p> <p>We need more data about not working Unicode comparisons in order to help you. However, it might be a matter of normalization. Consider the following:</p> <pre><code>&gt;&gt;&gt; a1= u'\xeatre' &gt;&gt;&gt; a2= u'e\u0302tre' </code></pre> <p><code>a1</code> and <code>a2</code> are equivalent but not equal:</p> <pre><code>&gt;&gt;&gt; print a1, a2 être être &gt;&gt;&gt; print a1 == a2 False </code></pre> <p>So you might want to use the <a href="https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize" rel="nofollow" title="unicodedata.normalize()"><code>unicodedata.normalize()</code></a> method:</p> <pre><code>&gt;&gt;&gt; import unicodedata as ud &gt;&gt;&gt; ud.normalize('NFC', a1) u'\xeatre' &gt;&gt;&gt; ud.normalize('NFC', a2) u'\xeatre' &gt;&gt;&gt; ud.normalize('NFC', a1) == ud.normalize('NFC', a2) True </code></pre> <p>If you give us more information, we might be able to help you more, though.</p>
48
2009-01-25T10:25:54Z
[ "python", "unicode" ]
Python import coding style
477,096
<p>I've discovered a new pattern. Is this pattern well known or what is the opinion about it?</p> <p>Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of</p> <pre><code>import foo from bar.baz import quux def myFunction(): foo.this.that(quux) </code></pre> <p>I move all my imports into the function where they're actually used., like this:</p> <pre><code>def myFunction(): import foo from bar.baz import quux foo.this.that(quux) </code></pre> <p>This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the <code>__all__</code> variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.</p> <p>Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.</p>
46
2009-01-25T03:06:09Z
477,103
<p>A few problems with this approach:</p> <ul> <li>It's not immediately obvious when opening the file which modules it depends on.</li> <li>It will confuse programs that have to analyze dependencies, such as <code>py2exe</code>, <code>py2app</code> etc.</li> <li>What about modules that you use in many functions? You will either end up with a lot of redundant imports or you'll have to have some at the top of the file and some inside functions.</li> </ul> <p>So... the preferred way is to put all imports at the top of the file. I've found that if my imports get hard to keep track of, it usually means I have too much code that I'd be better off splitting it into two or more files.</p> <p>Some situations where I <em>have</em> found imports inside functions to be useful:</p> <ul> <li>To deal with circular dependencies (if you really really can't avoid them)</li> <li>Platform specific code</li> </ul> <p>Also: putting imports inside each function is actually <em>not</em> appreciably slower than at the top of the file. The first time each module is loaded it is put into <code>sys.modules</code>, and each subsequent import costs only the time to look up the module, which is fairly fast (it is not reloaded).</p>
18
2009-01-25T03:19:08Z
[ "python", "coding-style" ]
Python import coding style
477,096
<p>I've discovered a new pattern. Is this pattern well known or what is the opinion about it?</p> <p>Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of</p> <pre><code>import foo from bar.baz import quux def myFunction(): foo.this.that(quux) </code></pre> <p>I move all my imports into the function where they're actually used., like this:</p> <pre><code>def myFunction(): import foo from bar.baz import quux foo.this.that(quux) </code></pre> <p>This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the <code>__all__</code> variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.</p> <p>Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.</p>
46
2009-01-25T03:06:09Z
477,107
<p>This does have a few disadvantages.</p> <h1>Testing</h1> <p>On the off chance you want to test your module through runtime modification, it may make it more difficult. Instead of doing</p> <pre><code>import mymodule mymodule.othermodule = module_stub </code></pre> <p>You'll have to do</p> <pre><code>import othermodule othermodule.foo = foo_stub </code></pre> <p>This means that you'll have to patch the othermodule globally, as opposed to just change what the reference in mymodule points to.</p> <h1>Dependency Tracking</h1> <p>This makes it non-obvious what modules your module depends on. This is especially irritating if you use many third party libraries or are re-organizing code.</p> <p>I had to maintain some legacy code that used imports inline all over the place, it made the code extremely difficult to refactor or repackage.</p> <h1>Notes On Performance</h1> <p>Because of the way python caches modules, there isn't a performance hit. In fact, since the module is in the local namespace, there is a slight performance benefit to importing modules in a function.</p> <h2>Top Import</h2> <pre><code>import random def f(): L = [] for i in xrange(1000): L.append(random.random()) for i in xrange(10000): f() $ time python test.py real 0m1.569s user 0m1.560s sys 0m0.010s </code></pre> <h2>Import in Function Body</h2> <pre><code>def f(): import random L = [] for i in xrange(1000): L.append(random.random()) for i in xrange(10000): f() $ time python test2.py real 0m1.385s user 0m1.380s sys 0m0.000s </code></pre>
48
2009-01-25T03:24:50Z
[ "python", "coding-style" ]
Python import coding style
477,096
<p>I've discovered a new pattern. Is this pattern well known or what is the opinion about it?</p> <p>Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of</p> <pre><code>import foo from bar.baz import quux def myFunction(): foo.this.that(quux) </code></pre> <p>I move all my imports into the function where they're actually used., like this:</p> <pre><code>def myFunction(): import foo from bar.baz import quux foo.this.that(quux) </code></pre> <p>This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the <code>__all__</code> variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.</p> <p>Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.</p>
46
2009-01-25T03:06:09Z
477,110
<p>From a performance point of view, you can see this: <a href="http://stackoverflow.com/questions/128478/should-python-import-statements-always-be-at-the-top-of-a-module">Should Python import statements always be at the top of a module? </a></p> <p>In general, I only use local imports in order to break dependency cycles.</p>
2
2009-01-25T03:29:21Z
[ "python", "coding-style" ]
Python import coding style
477,096
<p>I've discovered a new pattern. Is this pattern well known or what is the opinion about it?</p> <p>Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of</p> <pre><code>import foo from bar.baz import quux def myFunction(): foo.this.that(quux) </code></pre> <p>I move all my imports into the function where they're actually used., like this:</p> <pre><code>def myFunction(): import foo from bar.baz import quux foo.this.that(quux) </code></pre> <p>This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the <code>__all__</code> variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.</p> <p>Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.</p>
46
2009-01-25T03:06:09Z
477,116
<p>Another useful thing to note is that the <code>from module import *</code> syntax inside of a function has been removed in Python 3.0.</p> <p>There is a brief mention of it under "Removed Syntax" here:</p> <p><a href="http://docs.python.org/3.0/whatsnew/3.0.html" rel="nofollow">http://docs.python.org/3.0/whatsnew/3.0.html</a></p>
8
2009-01-25T03:32:28Z
[ "python", "coding-style" ]
Python import coding style
477,096
<p>I've discovered a new pattern. Is this pattern well known or what is the opinion about it?</p> <p>Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of</p> <pre><code>import foo from bar.baz import quux def myFunction(): foo.this.that(quux) </code></pre> <p>I move all my imports into the function where they're actually used., like this:</p> <pre><code>def myFunction(): import foo from bar.baz import quux foo.this.that(quux) </code></pre> <p>This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the <code>__all__</code> variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.</p> <p>Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.</p>
46
2009-01-25T03:06:09Z
477,128
<p>I believe this is a recommended approach in some cases/scenarios. For example in Google App Engine lazy-loading big modules is recommended since it will minimize the warm-up cost of instantiating new Python VMs/interpreters. Have a look at a <a href="https://sites.google.com/site/io/building-scalable-web-applications-with-google-app-engine" rel="nofollow">Google Engineer's</a> presentation describing this. However keep in mind this <strong>doesn't</strong> mean you should lazy-load all your modules.</p>
2
2009-01-25T03:48:46Z
[ "python", "coding-style" ]
Python import coding style
477,096
<p>I've discovered a new pattern. Is this pattern well known or what is the opinion about it?</p> <p>Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of</p> <pre><code>import foo from bar.baz import quux def myFunction(): foo.this.that(quux) </code></pre> <p>I move all my imports into the function where they're actually used., like this:</p> <pre><code>def myFunction(): import foo from bar.baz import quux foo.this.that(quux) </code></pre> <p>This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the <code>__all__</code> variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.</p> <p>Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.</p>
46
2009-01-25T03:06:09Z
477,548
<p>You might want to take a look at Import <a href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips#ImportStatementOverhead" rel="nofollow">statement overhead</a> in the python wiki. In short: if the module has already been loaded (look at <code>sys.modules</code>) your code will run slower. If your module hasn't been loaded yet, and will <code>foo</code> will only get loaded when needed, which can be zero times, then the overall performance will be better.</p>
1
2009-01-25T11:03:19Z
[ "python", "coding-style" ]
Python import coding style
477,096
<p>I've discovered a new pattern. Is this pattern well known or what is the opinion about it?</p> <p>Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of</p> <pre><code>import foo from bar.baz import quux def myFunction(): foo.this.that(quux) </code></pre> <p>I move all my imports into the function where they're actually used., like this:</p> <pre><code>def myFunction(): import foo from bar.baz import quux foo.this.that(quux) </code></pre> <p>This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the <code>__all__</code> variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.</p> <p>Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.</p>
46
2009-01-25T03:06:09Z
477,873
<p>I would suggest that you try to avoid <code>from foo import bar</code> imports. I only use them inside packages, where the splitting into modules is an implementation detail and there won't be many of them anyway.</p> <p>In all other places, where you import a package, just use <code>import foo</code> and then reference it by the full name <code>foo.bar</code>. This way you can always tell where a certain element comes from and don't have to maintain the list of imported elements (in reality this will always be outdated and import no longer used elements). </p> <p>If <code>foo</code> is a really long name you can simplify it with <code>import foo as f</code> and then write <code>f.bar</code>. This is still far more convenient and explicit than maintaining all the <code>from</code> imports.</p>
3
2009-01-25T16:10:16Z
[ "python", "coding-style" ]
Python import coding style
477,096
<p>I've discovered a new pattern. Is this pattern well known or what is the opinion about it?</p> <p>Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of</p> <pre><code>import foo from bar.baz import quux def myFunction(): foo.this.that(quux) </code></pre> <p>I move all my imports into the function where they're actually used., like this:</p> <pre><code>def myFunction(): import foo from bar.baz import quux foo.this.that(quux) </code></pre> <p>This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the <code>__all__</code> variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.</p> <p>Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.</p>
46
2009-01-25T03:06:09Z
479,642
<p>People have explained very well why to avoid inline-imports, but not really alternative workflows to address the reasons you want them in the first place.</p> <blockquote> <p>I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth</p> </blockquote> <p>To check for unused imports I use <a href="http://www.logilab.org/project/pylint" rel="nofollow">pylint</a>. It does static(ish)-analysis of Python code, and one of the (many) things it checks for is unused imports. For example, the following script..</p> <pre><code>import urllib import urllib2 urllib.urlopen("http://stackoverflow.com") </code></pre> <p>..would generate the following message:</p> <pre><code>example.py:2 [W0611] Unused import urllib2 </code></pre> <p>As for checking available imports, I generally rely on TextMate's (fairly simplistic) completion - when you press Esc, it completes the current word with others in the document. If I have done <code>import urllib</code>, <code>urll[Esc]</code> will expand to <code>urllib</code>, if not I jump to the start of the file and add the import.</p>
3
2009-01-26T12:32:50Z
[ "python", "coding-style" ]
Python import coding style
477,096
<p>I've discovered a new pattern. Is this pattern well known or what is the opinion about it?</p> <p>Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of</p> <pre><code>import foo from bar.baz import quux def myFunction(): foo.this.that(quux) </code></pre> <p>I move all my imports into the function where they're actually used., like this:</p> <pre><code>def myFunction(): import foo from bar.baz import quux foo.this.that(quux) </code></pre> <p>This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the <code>__all__</code> variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.</p> <p>Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.</p>
46
2009-01-25T03:06:09Z
4,789,963
<p>The (previously) <a href="http://stackoverflow.com/questions/477096/python-import-coding-style/477107#477107">top-voted answer</a> to this question is nicely formatted but absolutely wrong about performance. Let me demonstrate</p> <h1>Performance</h1> <h2>Top Import</h2> <pre><code>import random def f(): L = [] for i in xrange(1000): L.append(random.random()) for i in xrange(1000): f() $ time python import.py real 0m0.721s user 0m0.412s sys 0m0.020s </code></pre> <h2>Import in Function Body</h2> <pre><code>def f(): import random L = [] for i in xrange(1000): L.append(random.random()) for i in xrange(1000): f() $ time python import2.py real 0m0.661s user 0m0.404s sys 0m0.008s </code></pre> <p>As you can see, it can be <strong>more</strong> efficient to import the module in the function. The reason for this is simple. It moves the reference from a global reference to a local reference. This means that, for CPython at least, the compiler will emit <code>LOAD_FAST</code> instructions instead of <code>LOAD_GLOBAL</code> instructions. These are, as the name implies, faster. The other answerer artificially inflated the performance hit of looking in <code>sys.modules</code> by <em>importing on every single iteration of the loop</em>. </p> <p>As a rule, it's best to import at the top but performance is <em>not</em> the reason if you are accessing the module a lot of times. The reasons are that one can keep track of what a module depends on more easily and that doing so is consistent with most of the rest of the Python universe.</p>
63
2011-01-25T04:23:27Z
[ "python", "coding-style" ]
Python import coding style
477,096
<p>I've discovered a new pattern. Is this pattern well known or what is the opinion about it?</p> <p>Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of</p> <pre><code>import foo from bar.baz import quux def myFunction(): foo.this.that(quux) </code></pre> <p>I move all my imports into the function where they're actually used., like this:</p> <pre><code>def myFunction(): import foo from bar.baz import quux foo.this.that(quux) </code></pre> <p>This does a few things. First, I rarely accidentally pollute my modules with the contents of other modules. I could set the <code>__all__</code> variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.</p> <p>Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it. Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.</p>
46
2009-01-25T03:06:09Z
37,095,634
<h1>Security Implementations</h1> <p>Consider an environment where all of your Python code is located within a folder only a privileged user has access to. In order to avoid running your whole program as privileged user, you decide to drop privileges to an unprivileged user during execution. As soon as you make use of a function that imports another module, your program will throw an <code>ImportError</code> since the unprivileged user is unable to import the module due to file permissions.</p>
0
2016-05-08T02:35:17Z
[ "python", "coding-style" ]
How to list the files in a static directory?
477,135
<p>I am playing with Google App Engine and Python and I cannot list the files of a static directory. Below is the code I currently use.</p> <p><strong>app.yaml</strong></p> <pre><code>- url: /data static_dir: data </code></pre> <p><strong>Python code to list the files</strong></p> <pre><code>myFiles = [] for root, dirs, files in os.walk(os.path.join(os.path.dirname(__file__), 'data/') ): for name in files: full_name = os.path.join(root, name) myFiles.append('%s;%s\n' % (name, datetime.fromtimestamp(os.stat(full_name).st_mtime))) </code></pre> <p>When I run this code locally on my machine, everything is alright. I have my Python script at the root of the directory and it walks the files under the data directory. However, when I upload and run the exact same code in GAE, it doesn`t work. It seems to me that the directory structure of my application is not exactly replicated in Google App Engine. <strong>Where are the static files?</strong> </p> <p>Thanks!</p>
8
2009-01-25T03:59:08Z
477,887
<p><a href="https://developers.google.com/appengine/docs/python/config/appconfig#Python_app_yaml_Static_file_handlers" rel="nofollow">https://developers.google.com/appengine/docs/python/config/appconfig#Python_app_yaml_Static_file_handlers</a></p> <p>They're not where you think they are, GAE puts static content into GoogleFS which is equivalent of a CDN. The idea is that static content is meant to be served directly to your users and not act as a file store you can manipulate. Furthermore GAE has 1K file limit and it would be difficult to police this rule if you could manipulate your static file store.</p>
7
2009-01-25T16:23:31Z
[ "python", "google-app-engine" ]
How to list the files in a static directory?
477,135
<p>I am playing with Google App Engine and Python and I cannot list the files of a static directory. Below is the code I currently use.</p> <p><strong>app.yaml</strong></p> <pre><code>- url: /data static_dir: data </code></pre> <p><strong>Python code to list the files</strong></p> <pre><code>myFiles = [] for root, dirs, files in os.walk(os.path.join(os.path.dirname(__file__), 'data/') ): for name in files: full_name = os.path.join(root, name) myFiles.append('%s;%s\n' % (name, datetime.fromtimestamp(os.stat(full_name).st_mtime))) </code></pre> <p>When I run this code locally on my machine, everything is alright. I have my Python script at the root of the directory and it walks the files under the data directory. However, when I upload and run the exact same code in GAE, it doesn`t work. It seems to me that the directory structure of my application is not exactly replicated in Google App Engine. <strong>Where are the static files?</strong> </p> <p>Thanks!</p>
8
2009-01-25T03:59:08Z
477,956
<p>Here´s a project that let you browse your static files: <a href="http://code.google.com/p/appfilesbrowser/" rel="nofollow">http://code.google.com/p/appfilesbrowser/</a></p> <p>And here is must see list of recipes for appengine: <a href="http://appengine-cookbook.appspot.com/" rel="nofollow">http://appengine-cookbook.appspot.com/</a> (I found about that project here sometime ago)</p>
2
2009-01-25T17:33:25Z
[ "python", "google-app-engine" ]
How to list the files in a static directory?
477,135
<p>I am playing with Google App Engine and Python and I cannot list the files of a static directory. Below is the code I currently use.</p> <p><strong>app.yaml</strong></p> <pre><code>- url: /data static_dir: data </code></pre> <p><strong>Python code to list the files</strong></p> <pre><code>myFiles = [] for root, dirs, files in os.walk(os.path.join(os.path.dirname(__file__), 'data/') ): for name in files: full_name = os.path.join(root, name) myFiles.append('%s;%s\n' % (name, datetime.fromtimestamp(os.stat(full_name).st_mtime))) </code></pre> <p>When I run this code locally on my machine, everything is alright. I have my Python script at the root of the directory and it walks the files under the data directory. However, when I upload and run the exact same code in GAE, it doesn`t work. It seems to me that the directory structure of my application is not exactly replicated in Google App Engine. <strong>Where are the static files?</strong> </p> <p>Thanks!</p>
8
2009-01-25T03:59:08Z
477,972
<p>You can't access files uploaded as static content programmatically - they're not installed on the server along with your app, rather they're served up directly. If you really need to access them, you can remove the static file handler and serve them up yourself.</p>
0
2009-01-25T17:42:51Z
[ "python", "google-app-engine" ]
Generating and submitting a dynamic number of objects in a form with Django
477,183
<p>I want to be able to update a dynamic number of objects within a single form using Django and I'm wondering what the best way to do this would be. An example of a similar situation may help.</p> <p>Model:</p> <pre><code>class Customer(Model.models): name = models.CharField(max_length=100) active = models.BooleanField() </code></pre> <p>Form (I know I'm mixing view and template code here which doesn't work but this is a general idea for what the form is supposed to do):</p> <pre><code>customers = Customer.objects.all() for c in customers: print &lt;li&gt; {{ c.name }} &lt;input type="checkbox" value="{{ c.active }}" name="?" /&gt; </code></pre> <p>How would I go about submitting a list of these objects? Would the best bet be to attach the id of the customer into each 'row' and then process based on the id? Is there a mechanism for submitting a list of tuples? What would be the ideal solution?</p>
2
2009-01-25T05:02:30Z
477,194
<p><a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/" rel="nofollow">Formsets</a>!</p> <p>Also, the equivalent for forms generated directly models are <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1" rel="nofollow">model formsets</a>.</p>
8
2009-01-25T05:17:59Z
[ "python", "html", "django", "forms", "web-applications" ]
How do I simulate flip of biased coin in python?
477,237
<p>In unbiased coin flip H or T occurs 50% of times.</p> <p>But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'.</p> <p>something like this:</p> <pre><code>def flip(p): '''this function return H with probability p''' # do something return result &gt;&gt; [flip(0.8) for i in xrange(10)] [H,H,T,H,H,H,T,H,H,H] </code></pre>
20
2009-01-25T06:13:00Z
477,239
<pre><code>import random def flip(p): return (random.random() &lt; p) </code></pre> <p>That returns a boolean which you can then use to choose H or T (or choose between any two values) you want. You could also include the choice in the method:</p> <pre><code>def flip(p): if random.random() &lt; p: return 'H' else: return 'T' </code></pre> <p>but it'd be less generally useful that way.</p>
4
2009-01-25T06:14:29Z
[ "python", "random", "coin-flipping" ]
How do I simulate flip of biased coin in python?
477,237
<p>In unbiased coin flip H or T occurs 50% of times.</p> <p>But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'.</p> <p>something like this:</p> <pre><code>def flip(p): '''this function return H with probability p''' # do something return result &gt;&gt; [flip(0.8) for i in xrange(10)] [H,H,T,H,H,H,T,H,H,H] </code></pre>
20
2009-01-25T06:13:00Z
477,246
<ul> <li><p>Import a random number between 0 - 1 (you can use randrange function)</p></li> <li><p>If the number is above (1-p), return tails.</p></li> <li><p>Else, return heads</p></li> </ul>
0
2009-01-25T06:17:46Z
[ "python", "random", "coin-flipping" ]
How do I simulate flip of biased coin in python?
477,237
<p>In unbiased coin flip H or T occurs 50% of times.</p> <p>But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'.</p> <p>something like this:</p> <pre><code>def flip(p): '''this function return H with probability p''' # do something return result &gt;&gt; [flip(0.8) for i in xrange(10)] [H,H,T,H,H,H,T,H,H,H] </code></pre>
20
2009-01-25T06:13:00Z
477,248
<p><code>random.random()</code> returns a <em>uniformly distributed</em> pseudo-random floating point number in the range [0, 1). This number is less than a given number <code>p</code> in the range [0,1) with probability <code>p</code>. Thus:</p> <pre><code>def flip(p): return 'H' if random.random() &lt; p else 'T' </code></pre> <p>Some experiments:</p> <pre><code>&gt;&gt;&gt; N = 100 &gt;&gt;&gt; flips = [flip(0.2) for i in xrange(N)] &gt;&gt;&gt; float(flips.count('H'))/N 0.17999999999999999 # Approximately 20% of the coins are heads &gt;&gt;&gt; N = 10000 &gt;&gt;&gt; flips = [flip(0.2) for i in xrange(N)] &gt;&gt;&gt; float(flips.count('H'))/N 0.20549999999999999 # Better approximation </code></pre>
37
2009-01-25T06:17:59Z
[ "python", "random", "coin-flipping" ]
How do I simulate flip of biased coin in python?
477,237
<p>In unbiased coin flip H or T occurs 50% of times.</p> <p>But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'.</p> <p>something like this:</p> <pre><code>def flip(p): '''this function return H with probability p''' # do something return result &gt;&gt; [flip(0.8) for i in xrange(10)] [H,H,T,H,H,H,T,H,H,H] </code></pre>
20
2009-01-25T06:13:00Z
478,513
<p>Do you want the "bias" to be based in symmetric distribuition? Or maybe exponential distribution? Gaussian anyone?</p> <p>Well, here are all the methods, extracted from random documentation itself.</p> <p>First, an example of triangular distribution:</p> <pre><code>print random.triangular(0, 1, 0.7) </code></pre> <blockquote> <p><strong><code>random.triangular(low, high, mode)</code></strong>:</p> <p>Return a random floating point number <code>N</code> such that <code>low &lt;= N &lt; high</code> and with the specified mode between those bounds. The <code>low</code> and <code>high</code> bounds default to <em>zero</em> and <em>one</em>. The <code>mode</code> argument defaults to the midpoint between the bounds, giving a symmetric distribution.</p> <p><strong><code>random.betavariate(alpha, beta)</code></strong>:</p> <p>Beta distribution. Conditions on the parameters are <code>alpha &gt; 0</code> and <code>beta &gt; 0</code>. Returned values range between <code>0</code> and <code>1</code>.</p> <p><strong><code>random.expovariate(lambd)</code></strong>:</p> <p>Exponential distribution. <code>lambd</code> is <code>1.0</code> divided by the desired mean. It should be <em>nonzero</em>. (The parameter would be called “<em><code>lambda</code></em>”, but that is a reserved word in Python.) Returned values range from <code>0</code> to <em>positive infinity</em> if <code>lambd</code> is positive, and from <em>negative infinity</em> to <code>0</code> if <code>lambd</code> is negative.</p> <p><strong><code>random.gammavariate(alpha, beta)</code></strong>:</p> <p>Gamma distribution. (Not the gamma function!) Conditions on the parameters are <code>alpha &gt; 0</code> and <code>beta &gt; 0</code>.</p> <p><strong><code>random.gauss(mu, sigma)</code></strong>:</p> <p>Gaussian distribution. <code>mu</code> is the mean, and <code>sigma</code> is the standard deviation. This is slightly faster than the <code>normalvariate()</code> function defined below.</p> <p><strong><code>random.lognormvariate(mu, sigma)</code></strong>:</p> <p>Log normal distribution. If you take the natural logarithm of this distribution, you’ll get a normal distribution with mean <code>mu</code> and standard deviation <code>sigma</code>. <code>mu</code> can have any value, and <code>sigma</code> must be greater than <em>zero</em>.</p> <p><strong><code>random.normalvariate(mu, sigma)</code></strong>:</p> <p>Normal distribution. <code>mu</code> is the mean, and <code>sigma</code> is the standard deviation.</p> <p><strong><code>random.vonmisesvariate(mu, kappa)</code></strong>:</p> <p><code>mu</code> is the mean angle, expressed in radians between <code>0</code> and <code>2*pi</code>, and <code>kappa</code> is the concentration parameter, which must be greater than or equal to <em>zero</em>. If <code>kappa</code> is equal to <em>zero</em>, this distribution reduces to a uniform random angle over the range <code>0</code> to <code>2*pi</code>.</p> <p><strong><code>random.paretovariate(alpha)</code></strong>:</p> <p>Pareto distribution. <code>alpha</code> is the shape parameter.</p> <p><strong><code>random.weibullvariate(alpha, beta)</code></strong></p> <p>Weibull distribution. <code>alpha</code> is the scale parameter and <code>beta</code> is the shape parameter.</p> </blockquote>
7
2009-01-25T23:24:57Z
[ "python", "random", "coin-flipping" ]
How do I simulate flip of biased coin in python?
477,237
<p>In unbiased coin flip H or T occurs 50% of times.</p> <p>But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'.</p> <p>something like this:</p> <pre><code>def flip(p): '''this function return H with probability p''' # do something return result &gt;&gt; [flip(0.8) for i in xrange(10)] [H,H,T,H,H,H,T,H,H,H] </code></pre>
20
2009-01-25T06:13:00Z
25,470,152
<p>How about:</p> <pre><code>import numpy as np n, p = 1, .33 # n = coins flipped, p = prob of success s = np.random.binomial(n, p, 100) </code></pre>
2
2014-08-24T09:09:20Z
[ "python", "random", "coin-flipping" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
477,506
<p>Increase the magnitude of <code>i</code> for the loop and then reduce it when you need it.</p> <pre><code>for i * 100 in range(0, 100, 10): print i / 100.0 </code></pre> <p><strong>EDIT: I honestly cannot remember why I thought that would work syntactically</strong></p> <pre><code>for i in range(0, 11, 1): print i / 10.0 </code></pre> <p>That should have the desired output. </p>
22
2009-01-25T10:32:01Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
477,507
<p>The range() built-in function returns a sequence of integer values, I'm afraid, so you can't use it to do a decimal step. </p> <p>I'd say just use a while loop:</p> <pre><code>i = 0.0 while i &lt;= 1.0: print i i += 0.1 </code></pre> <p>If you're curious, Python is converting your 0.1 to 0, which is why it's telling you the argument can't be zero.</p>
7
2009-01-25T10:32:43Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
477,513
<p>Python's range() can only do integers, not floating point. In your specific case, you can use a list comprehension instead:</p> <pre><code>[x * 0.1 for x in range(0, 10)] </code></pre> <p>(Replace the call to range with that expression.) </p> <p>For the more general case, you may want to write a custom function or generator.</p>
109
2009-01-25T10:35:25Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
477,527
<p>And if you do this often, you might want to save the generated list <code>r</code></p> <pre><code>r=map(lambda x: x/10.0,range(0,10)) for i in r: print i </code></pre>
3
2009-01-25T10:48:33Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
477,610
<p>Building on <a href="http://docs.python.org/library/functions.html#xrange">'xrange([start], stop[, step])'</a>, you can define a generator that accepts and produces any type you choose (stick to types supporting <code>+</code> and <code>&lt;</code>):</p> <pre><code>&gt;&gt;&gt; def drange(start, stop, step): ... r = start ... while r &lt; stop: ... yield r ... r += step ... &gt;&gt;&gt; i0=drange(0.0, 1.0, 0.1) &gt;&gt;&gt; ["%g" % x for x in i0] ['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1'] &gt;&gt;&gt; </code></pre>
132
2009-01-25T11:57:17Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
477,635
<p>You can also use the <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> library (which isn't part of standard library but is relatively easy to obtain) which has the <code>arange</code> function:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.arange(0,1,0.1) array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) </code></pre> <p>as well as the <code>linspace</code> function which lets you have control over what happens at the endpoint (non-trivial for floating point numbers when things won't always divide into the correct number of "slices"):</p> <pre><code>&gt;&gt;&gt; np.linspace(0,1,11) array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]) &gt;&gt;&gt; np.linspace(0,1,10,endpoint=False) array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) </code></pre>
343
2009-01-25T12:26:08Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
3,120,257
<p>You can use this function:</p> <pre><code>def frange(start,end,step): return map(lambda x: x*step, range(int(start*1./step),int(end*1./step))) </code></pre>
2
2010-06-25T17:57:04Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
4,321,838
<p>Add auto-correction for the possibility of an incorrect sign on step:</p> <pre><code>def frange(start,step,stop): step *= 2*((stop&gt;start)^(step&lt;0))-1 return [start+i*step for i in range(int((stop-start)/step))] </code></pre>
1
2010-12-01T06:36:16Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
10,575,982
<pre><code>[x * 0.1 for x in range(0, 10)] </code></pre> <p>in Python 2.7x gives you the result of:</p> <blockquote> <p>[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]</p> </blockquote> <p>but if you use:</p> <pre><code>[ round(x * 0.1, 1) for x in range(0, 10)] </code></pre> <p>gives you the desired:</p> <blockquote> <p>[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]</p> </blockquote>
5
2012-05-13T23:20:58Z
[ "python", "floating-point", "range" ]
Python decimal range() step value
477,486
<p>Is there a way to step between 0 and 1 by 0.1? </p> <p>I thought I could do it like the following, but it failed:</p> <pre><code>for i in range(0, 1, 0.1): print i </code></pre> <p>Instead, it says that the step argument cannot be zero, which I did not expect.</p>
283
2009-01-25T10:20:43Z
10,986,098
<p>Similar to <a href="http://en.wikipedia.org/wiki/R_%28programming_language%29">R's</a> <code>seq</code> function, this one returns a sequence in any order given the correct step value. The last value is equal to the stop value. </p> <pre><code>def seq(start, stop, step=1): n = int(round((stop - start)/float(step))) if n &gt; 1: return([start + step*i for i in range(n+1)]) else: return([]) </code></pre> <h3>Results</h3> <pre><code>seq(1, 5, 0.5) </code></pre> <blockquote> <p>[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]</p> </blockquote> <pre><code>seq(10, 0, -1) </code></pre> <blockquote> <p>[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]</p> </blockquote> <pre><code>seq(10, 0, -2) </code></pre> <blockquote> <p>[10, 8, 6, 4, 2, 0]</p> </blockquote>
12
2012-06-11T19:10:53Z
[ "python", "floating-point", "range" ]