title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
Any good AJAX framework for Google App Engine apps?
53,997
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p> <p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
12
2008-09-10T13:12:07Z
54,034
<p>jQuery is a fine library, but also check out the <a href="http://www.prototypejs.org/" rel="nofollow">Prototype JavaScript framework</a>. It really turns JavaScript from being an occasionally awkward language into a beautiful and elegant language.</p>
1
2008-09-10T13:29:54Z
[ "python", "ajax", "google-app-engine" ]
Any good AJAX framework for Google App Engine apps?
53,997
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p> <p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
12
2008-09-10T13:12:07Z
55,041
<p>There is no reason why you shouldn't use GAE and Google Web Toolkit (GWT) together. You write your backend code in Python and the frontend code in Java (and possibly some JavaScript), which is then compiled to JavaScript. When using another AJAX framework you will also have this difference between server and client side language.</p> <p>GWT has features that make remote invocation of java code on the server easier, but these are entirely optional. You can just use JSON or XML interfaces, just like with other AJAX frameworks.</p> <p>GWT 1.5 also comes with JavaScript Overlay Types, that basically allow you to treat a piece of JSON data like a Java object when developing the client side code. You can read more about this <a href="http://googlewebtoolkit.blogspot.com/2008/08/getting-to-really-know-gwt-part-2.html" rel="nofollow">here</a>.</p> <p><strong>Update:</strong></p> <p>Now that Google has added Java support for Google App Engine, you can develop both backend and frontend code in Java on a full Google stack - if you like. There is a nice <a href="http://code.google.com/eclipse/" rel="nofollow">Eclipse plugin</a> from Google that makes it very easy to develop and deploy applications that use GAE, GWT or both.</p>
4
2008-09-10T19:00:38Z
[ "python", "ajax", "google-app-engine" ]
Any good AJAX framework for Google App Engine apps?
53,997
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p> <p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
12
2008-09-10T13:12:07Z
62,976
<p>If you want to be able to invoke method calls from JavaScript to Python, <a href="http://json-rpc.org/wiki/python-json-rpc" rel="nofollow">JSON-RPC</a> works well with Google App Engine. See Google's article, "<a href="http://code.google.com/appengine/articles/rpc.html" rel="nofollow">Using AJAX to Enable Client RPC Requests</a>", for details.</p>
0
2008-09-15T13:43:08Z
[ "python", "ajax", "google-app-engine" ]
Any good AJAX framework for Google App Engine apps?
53,997
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p> <p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
12
2008-09-10T13:12:07Z
230,476
<p>I'm currently using JQuery for my GAE app and it works beautifully for me. I have a chart (google charts) that is dynamic and uses an Ajax call to grab a JSON string. It really seems to work fine for me.</p>
0
2008-10-23T16:41:43Z
[ "python", "ajax", "google-app-engine" ]
Any good AJAX framework for Google App Engine apps?
53,997
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p> <p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
12
2008-09-10T13:12:07Z
352,120
<p>You may want to have a look at Pyjamas (<a href="http://pyjs.org/" rel="nofollow">http://pyjs.org/</a>), which is "GWT for Python". </p>
2
2008-12-09T08:33:51Z
[ "python", "ajax", "google-app-engine" ]
Any good AJAX framework for Google App Engine apps?
53,997
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p> <p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
12
2008-09-10T13:12:07Z
605,156
<p>Here is how we've implemented Ajax on the Google App Engine, but the idea can be generalized to other platforms.</p> <p>We have a handler script for Ajax requests that responds -mostly- with JSON responses. The structure looks something like this (this is an excerpt from a standard GAE handler script):</p> <pre><code>def Get(self, user): self.handleRequest() def Post(self, user): self.handleRequest() def handleRequest(self): ''' A dictionary that maps an operation name to a command. aka: a dispatcher map. ''' operationMap = {'getfriends': [GetFriendsCommand], 'requestfriend': [RequestFriendCommand, [self.request.get('id')]], 'confirmfriend': [ConfirmFriendCommand, [self.request.get('id')]], 'ignorefriendrequest': [IgnoreFriendRequestCommand, [self.request.get('id')]], 'deletefriend': [DeleteFriendCommand, [self.request.get('id')]]} # Delegate the request to the matching command class here. </code></pre> <p>The commands are a simple implementation of the command pattern:</p> <pre><code>class Command(): """ A simple command pattern. """ _valid = False def validate(self): """ Validates input. Sanitize user input here. """ self._valid = True def _do_execute(self): """ Executes the command. Override this in subclasses. """ pass @property def valid(self): return self._valid def execute(self): """ Override _do_execute rather than this. """ try: self.validate() except: raise return self._do_execute() # Make it easy to invoke commands: # So command() is equivalent to command.execute() __call__ = execute </code></pre> <p>On the client side, we create an Ajax delegate. Prototype.js makes this easy to write and understand. Here is an excerpt:</p> <pre><code>/** * Ajax API * * You should create a new instance for every call. */ var AjaxAPI = Class.create({ /* Service URL */ url: HOME_PATH+"ajax/", /* Function to call on results */ resultCallback: null, /* Function to call on faults. Implementation not shown */ faultCallback: null, /* Constructor/Initializer */ initialize: function(resultCallback, faultCallback){ this.resultCallback = resultCallback; this.faultCallback = faultCallback; }, requestFriend: function(friendId){ return new Ajax.Request(this.url + '?op=requestFriend', {method: 'post', parameters: {'id': friendId}, onComplete: this.resultCallback }); }, getFriends: function(){ return new Ajax.Request(this.url + '?op=getfriends', {method: 'get', onComplete: this.resultCallback }); } }); </code></pre> <p>to call the delegate, you do something like:</p> <pre><code>new AjaxApi(resultHandlerFunction, faultHandlerFunction).getFriends() </code></pre> <p>I hope this helps!</p>
4
2009-03-03T04:56:35Z
[ "python", "ajax", "google-app-engine" ]
Any good AJAX framework for Google App Engine apps?
53,997
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p> <p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
12
2008-09-10T13:12:07Z
800,037
<p>A nice way is to use an AJAX library is to take advantage of <a href="http://code.google.com/apis/ajaxlibs/" rel="nofollow">Google's AJAX Libraries API service</a>. This is a bit faster and cleaner than downloading the JS and putting it in your <code>/static/</code> folder and doesn't eat into your disk quota.</p> <p>In your javascript you would just put, for example:</p> <pre><code>google.load("jquery", "1.3.2"); </code></pre> <p>and/or</p> <pre><code>google.load(google.load("dojo", "1.3.0"); </code></pre> <p>Somewhere in your header you would put something like:</p> <pre><code>&lt;script src="http://www.google.com/jsapi?key=your-key-here"&gt;&lt;/script&gt; </code></pre> <p>And that's all you need to use Google's API libraries.</p>
7
2009-04-28T22:08:08Z
[ "python", "ajax", "google-app-engine" ]
Any good AJAX framework for Google App Engine apps?
53,997
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p> <p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
12
2008-09-10T13:12:07Z
800,072
<p>Google has recently announced the Java version of Google App Engine. This release also provides an Eclipse plugin that makes developing GAE applications with GWT easier.</p> <p>See details here: <a href="http://code.google.com/appengine/docs/java/overview.html" rel="nofollow">http://code.google.com/appengine/docs/java/overview.html</a></p> <p>Of course, it would require you to rewrite your application in Java instead of python, but as someone who's worked with GWT, let me tell you, the advantages of using a modern IDE on your AJAX codebase are totally worth it.</p>
0
2009-04-28T22:17:55Z
[ "python", "ajax", "google-app-engine" ]
Any good AJAX framework for Google App Engine apps?
53,997
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p> <p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
12
2008-09-10T13:12:07Z
994,994
<p>try also <a href="http://ajaxian.com/archives/gquery-java-gwt-and-jquery-together" rel="nofollow">GQuery for GWT</a>. This is Java code:</p> <pre><code>public void onModuleLoad() { $("div").css("color", "red").click(new Function() { public void f(Element e) { Window.alert("Hello"); $(e).as(Effects).fadeOut(); } }); } </code></pre> <p>Being Java code resulting in somewhat expensive compile-time (Java->JavaScript) optimizations and easier refactoring. </p> <p>Nice, it isn't?</p>
2
2009-06-15T08:12:29Z
[ "python", "ajax", "google-app-engine" ]
Any good AJAX framework for Google App Engine apps?
53,997
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p> <p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
12
2008-09-10T13:12:07Z
1,037,446
<p>In my blog I deal with an easy way to do this - the link is: <a href="http://pythoughts.com/ajax-with-google-app-engine" rel="nofollow">AJAX with Google App Engine</a>. I include all the javascript and python code I used.</p>
3
2009-06-24T10:01:26Z
[ "python", "ajax", "google-app-engine" ]
What is the difference between old style and new style classes in Python?
54,867
<p>What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?</p>
604
2008-09-10T18:01:27Z
54,873
<p>From <a href="http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes">http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes</a> :</p> <blockquote> <p>Up to Python 2.1, old-style classes were the only flavour available to the user. The concept of (old-style) class is unrelated to the concept of type: if <code>x</code> is an instance of an old-style class, then <code>x.__class__</code> designates the class of <code>x</code>, but <code>type(x)</code> is always <code>&lt;type 'instance'&gt;</code>. This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance. </p> <p><strong>New-style classes were introduced in Python 2.2 to unify the concepts of class and type</strong>. A new-style class is simply a user-defined type, no more, no less. If x is an instance of a new-style class, then <code>type(x)</code> is typically the same as <code>x.__class__</code> (although this is not guaranteed – a new-style class instance is permitted to override the value returned for <code>x.__class__</code>).</p> <p><strong>The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model</strong>. It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of "descriptors", which enable computed properties. </p> <p><strong>For compatibility reasons, classes are still old-style by default</strong>. New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the "top-level type" object if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns. Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are "fixes" that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance. </p> <p><strong>Python 3 only has new-style classes</strong>. No matter if you subclass from <code>object</code> or not, classes are new-style in Python 3. It is however recommended that you still subclass from <code>object</code>.</p> </blockquote>
340
2008-09-10T18:02:43Z
[ "python", "class", "oop", "types", "new-style-class" ]
What is the difference between old style and new style classes in Python?
54,867
<p>What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?</p>
604
2008-09-10T18:01:27Z
55,354
<p>Or rather, you should always use new-style classes, <em>unless</em> you have code that needs to work with versions of Python older than 2.2.</p>
4
2008-09-10T21:23:53Z
[ "python", "class", "oop", "types", "new-style-class" ]
What is the difference between old style and new style classes in Python?
54,867
<p>What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?</p>
604
2008-09-10T18:01:27Z
242,700
<p>New-style classes inherit from <code>object</code> and must be written as such in Python 2.2 onwards (i.e. <code>class Classname(object):</code> instead of <code>class Classname:</code>). The core change is to unify types and classes, and the nice side-effect of this is that it allows you to inherit from built-in types.</p> <p>Read <a href="http://www.python.org/download/releases/2.2.3/descrintro/" rel="nofollow">descrintro</a> for more details.</p>
5
2008-10-28T09:54:30Z
[ "python", "class", "oop", "types", "new-style-class" ]
What is the difference between old style and new style classes in Python?
54,867
<p>What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?</p>
604
2008-09-10T18:01:27Z
1,203,997
<p><strong>Declaration-wise:</strong></p> <p>New-style classes inherit from object, or from another new-style class.</p> <pre><code>class NewStyleClass(object): pass class AnotherNewStyleClass(NewStyleClass): pass </code></pre> <p>Old-style classes don't.</p> <pre><code>class OldStyleClass(): pass </code></pre>
220
2009-07-30T01:21:59Z
[ "python", "class", "oop", "types", "new-style-class" ]
What is the difference between old style and new style classes in Python?
54,867
<p>What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?</p>
604
2008-09-10T18:01:27Z
3,228,045
<p>Old style classes are still marginally faster for attribute lookup. This is not usually important, but may be useful in performance-sensitive Python 2.x code:</p> <pre> In [3]: class A: ...: def __init__(self): ...: self.a = 'hi there' ...: In [4]: class B(object): ...: def __init__(self): ...: self.a = 'hi there' ...: In [6]: aobj = A() In [7]: bobj = B() In [8]: %timeit aobj.a 10000000 loops, best of 3: 78.7 ns per loop In [10]: %timeit bobj.a 10000000 loops, best of 3: 86.9 ns per loop </pre>
29
2010-07-12T11:26:52Z
[ "python", "class", "oop", "types", "new-style-class" ]
What is the difference between old style and new style classes in Python?
54,867
<p>What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?</p>
604
2008-09-10T18:01:27Z
16,193,572
<p>Guido has written <a href="http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html">The Inside Story on New-Style Classes</a>, a really great article about new-style and old-style class in Python.</p> <p>Python 3 has only new-style class, even if you write an 'old-style class', it is implicitly derived from <code>object</code>.</p> <p>New-style classes have some advanced features lacking in old-style classes, such as <code>super</code> and the new <a href="http://en.wikipedia.org/wiki/C3_linearization">C3 mro</a>, some magical methods, etc.</p>
22
2013-04-24T13:41:26Z
[ "python", "class", "oop", "types", "new-style-class" ]
What is the difference between old style and new style classes in Python?
54,867
<p>What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?</p>
604
2008-09-10T18:01:27Z
16,295,402
<p>New style classes may use <code>super(Foo, self)</code> where <code>Foo</code> is a class and <code>self</code> is the instance.</p> <blockquote> <p><code>super(type[, object-or-type])</code></p> <p>Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.</p> </blockquote> <p>And in Python 3.x you can simply use <code>super()</code> inside a class with no parameters.</p>
4
2013-04-30T08:28:52Z
[ "python", "class", "oop", "types", "new-style-class" ]
What is the difference between old style and new style classes in Python?
54,867
<p>What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?</p>
604
2008-09-10T18:01:27Z
19,273,761
<p>Here's a very practical, True/False difference. The only difference between the two versions of the following code is that in the second version Person inherits from object. Other than that the two versions are identical, but with different results :</p> <p>1) old-style classes</p> <pre><code>class Person(): _names_cache = {} def __init__(self,name): self.name = name def __new__(cls,name): return cls._names_cache.setdefault(name,object.__new__(cls,name)) ahmed1 = Person("Ahmed") ahmed2 = Person("Ahmed") print ahmed1 is ahmed2 print ahmed1 print ahmed2 &gt;&gt;&gt; False &lt;__main__.Person instance at 0xb74acf8c&gt; &lt;__main__.Person instance at 0xb74ac6cc&gt; &gt;&gt;&gt; </code></pre> <p>2) new-style classes </p> <pre><code>class Person(object): _names_cache = {} def __init__(self,name): self.name = name def __new__(cls,name): return cls._names_cache.setdefault(name,object.__new__(cls,name)) ahmed1 = Person("Ahmed") ahmed2 = Person("Ahmed") print ahmed2 is ahmed1 print ahmed1 print ahmed2 &gt;&gt;&gt; True &lt;__main__.Person object at 0xb74ac66c&gt; &lt;__main__.Person object at 0xb74ac66c&gt; &gt;&gt;&gt; </code></pre>
8
2013-10-09T13:40:29Z
[ "python", "class", "oop", "types", "new-style-class" ]
What is the difference between old style and new style classes in Python?
54,867
<p>What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?</p>
604
2008-09-10T18:01:27Z
19,950,198
<p><strong>Important behavior changes between old and new style classes</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/576169/understanding-python-super-and-init-methods">super</a> added</li> <li>MRO changed (explained below)</li> <li><a href="http://docs.python.org/2/howto/descriptor.html">descriptors</a> added</li> <li>new style class objects cannot be raised unless derived from <code>Exception</code> (example below)</li> <li><a href="http://docs.python.org/2/reference/datamodel.html#slots"><code>__slots__</code></a> added</li> </ul> <h2>MRO (Method Resolution Order) changed</h2> <p>It was mentioned in other answers, but here goes a concrete example of the difference between classic MRO and C3 MRO (used in new style classes).</p> <p>The question is the order in which attributes (which include methods and member variables) are searched for in multiple inheritance.</p> <p><strong>Classic classes</strong> do a depth first search from left to right. Stop on first match. They do not have the <code>__mro__</code> attribute.</p> <pre><code>class C: i = 0 class C1(C): pass class C2(C): i = 2 class C12(C1, C2): pass class C21(C2, C1): pass assert C12().i == 0 assert C21().i == 2 try: C12.__mro__ except AttributeError: pass else: assert False </code></pre> <p><strong>New-style classes</strong> MRO is more complicated to synthesize in a single English sentence. It is explained in detail <a href="http://www.python.org/download/releases/2.3/mro/">here</a>. One of its properties is that a Base class is only searched for once all its Derived classes have been. They have the <code>__mro__</code> attribute which shows the search order. </p> <pre><code>class C(object): i = 0 class C1(C): pass class C2(C): i = 2 class C12(C1, C2): pass class C21(C2, C1): pass assert C12().i == 2 assert C21().i == 2 assert C12.__mro__ == (C12, C1, C2, C, object) assert C21.__mro__ == (C21, C2, C1, C, object) </code></pre> <h2>New style class objects cannot be raised unless derived from <code>Exception</code></h2> <p>Around Python 2.5 many classes could be raised, around Python 2.6 this was removed. On Python 2.7.3:</p> <pre><code># OK, old: class Old: pass try: raise Old() except Old: pass else: assert False # TypeError, new not derived from `Exception`. class New(object): pass try: raise New() except TypeError: pass else: assert False # OK, derived from `Exception`. class New(Exception): pass try: raise New() except New: pass else: assert False # `'str'` is a new style object, so you can't raise it: try: raise 'str' except TypeError: pass else: assert False </code></pre>
126
2013-11-13T09:36:59Z
[ "python", "class", "oop", "types", "new-style-class" ]
In Python, how can you easily retrieve sorted items from a dictionary?
55,180
<p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p> <p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p> <p>For example, you had this:</p> <pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'} </code></pre> <p>I want to print the associated values in the following sequence sorted by key:</p> <pre><code>this is a this is b this is c </code></pre>
11
2008-09-10T20:05:25Z
55,188
<p>This snippet will do so. If you're going to do it frequently, you might want to make a 'sortkeys' method or somesuch to make it easier on the eyes.</p> <pre><code>keys = list(d.keys()) keys.sort() for key in keys: print d[key] </code></pre> <p>Edit: dF's solution is better -- I forgot all about sorted().</p>
1
2008-09-10T20:08:48Z
[ "python", "sorting", "dictionary", "list" ]
In Python, how can you easily retrieve sorted items from a dictionary?
55,180
<p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p> <p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p> <p>For example, you had this:</p> <pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'} </code></pre> <p>I want to print the associated values in the following sequence sorted by key:</p> <pre><code>this is a this is b this is c </code></pre>
11
2008-09-10T20:05:25Z
55,193
<p>Do you mean that you need the values sorted by the value of the key? In that case, this should do it:</p> <pre><code>for key in sorted(d): print d[key] </code></pre> <p><strong>EDIT:</strong> changed to use sorted(d) instead of sorted(d.keys()), thanks <a href="http://stackoverflow.com/users/1694/eli-courtwright" rel="nofollow">Eli</a>!</p>
16
2008-09-10T20:10:05Z
[ "python", "sorting", "dictionary", "list" ]
In Python, how can you easily retrieve sorted items from a dictionary?
55,180
<p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p> <p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p> <p>For example, you had this:</p> <pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'} </code></pre> <p>I want to print the associated values in the following sequence sorted by key:</p> <pre><code>this is a this is b this is c </code></pre>
11
2008-09-10T20:05:25Z
55,194
<p>Or shorter,</p> <pre><code>for key, value in sorted(d.items()): print value </code></pre>
16
2008-09-10T20:10:51Z
[ "python", "sorting", "dictionary", "list" ]
In Python, how can you easily retrieve sorted items from a dictionary?
55,180
<p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p> <p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p> <p>For example, you had this:</p> <pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'} </code></pre> <p>I want to print the associated values in the following sequence sorted by key:</p> <pre><code>this is a this is b this is c </code></pre>
11
2008-09-10T20:05:25Z
55,197
<pre><code>&gt;&gt;&gt; d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'} &gt;&gt;&gt; for k,v in sorted(d.items()): ... print v, k ... this is a a this is b b this is c c </code></pre>
1
2008-09-10T20:11:55Z
[ "python", "sorting", "dictionary", "list" ]
In Python, how can you easily retrieve sorted items from a dictionary?
55,180
<p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p> <p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p> <p>For example, you had this:</p> <pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'} </code></pre> <p>I want to print the associated values in the following sequence sorted by key:</p> <pre><code>this is a this is b this is c </code></pre>
11
2008-09-10T20:05:25Z
55,202
<pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'} ks = d.keys() ks.sort() for k in ks: print "this is " + k </code></pre>
0
2008-09-10T20:12:48Z
[ "python", "sorting", "dictionary", "list" ]
In Python, how can you easily retrieve sorted items from a dictionary?
55,180
<p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p> <p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p> <p>For example, you had this:</p> <pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'} </code></pre> <p>I want to print the associated values in the following sequence sorted by key:</p> <pre><code>this is a this is b this is c </code></pre>
11
2008-09-10T20:05:25Z
56,134
<pre><code>for key in sorted(d): print d[key] </code></pre>
1
2008-09-11T09:34:47Z
[ "python", "sorting", "dictionary", "list" ]
In Python, how can you easily retrieve sorted items from a dictionary?
55,180
<p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p> <p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p> <p>For example, you had this:</p> <pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'} </code></pre> <p>I want to print the associated values in the following sequence sorted by key:</p> <pre><code>this is a this is b this is c </code></pre>
11
2008-09-10T20:05:25Z
59,235
<p>You can also sort a dictionary by value and control the sort order:</p> <pre><code>import operator d = {'b' : 'this is 3', 'a': 'this is 2' , 'c' : 'this is 1'} for key, value in sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True): print key, " ", value </code></pre> <p>Output:<br /> b this is 3<br /> a this is 2<br /> c this is 1</p>
1
2008-09-12T15:11:00Z
[ "python", "sorting", "dictionary", "list" ]
How can I get Emacs' key bindings in Python's IDLE?
55,365
<p>I use Emacs primarily for coding Python but sometimes I use IDLE. Is there a way to change the key bindings easily in IDLE to match Emacs?</p>
4
2008-09-10T21:32:47Z
55,493
<p>There's a program for Windows called XKeymacs that allows you to specify emacs keybindings for different programs. It should work with IDLE.</p> <p><a href="http://www.cam.hi-ho.ne.jp/oishi/indexen.html" rel="nofollow">http://www.cam.hi-ho.ne.jp/oishi/indexen.html</a></p> <p>-Mark</p>
2
2008-09-10T23:33:46Z
[ "python", "emacs", "ide", "keyboard" ]
How can I get Emacs' key bindings in Python's IDLE?
55,365
<p>I use Emacs primarily for coding Python but sometimes I use IDLE. Is there a way to change the key bindings easily in IDLE to match Emacs?</p>
4
2008-09-10T21:32:47Z
56,008
<p>IDLE provides Emacs keybindings without having to install other software. </p> <ol> <li>Open up the menu item Options -> Configure IDLE...</li> <li>Go to Keys tab</li> <li>In the drop down menu on the right side of the dialog change the select to "IDLE Classic Unix"</li> </ol> <p>It's not the true emacs key bindings but you get the basics like movement, saving/opening, ...</p>
6
2008-09-11T08:18:07Z
[ "python", "emacs", "ide", "keyboard" ]
How can I get Emacs' key bindings in Python's IDLE?
55,365
<p>I use Emacs primarily for coding Python but sometimes I use IDLE. Is there a way to change the key bindings easily in IDLE to match Emacs?</p>
4
2008-09-10T21:32:47Z
85,113
<p><a href="http://www.python.org/doc/2.5/lib/module-readline.html" rel="nofollow">'readline' module</a> supposedly provides Emacs like key bindings and even functionality. However, it is not available on Windows but on Unix. Therefore, this might be a viable solution if you are not using Windows.</p> <pre><code>import readline </code></pre> <p>Since I am running IDLE on Windows it is unfortunately not an option for me.</p>
0
2008-09-17T16:36:39Z
[ "python", "emacs", "ide", "keyboard" ]
Python regular expression for HTML parsing (BeautifulSoup)
55,391
<p>I want to grab the value of a hidden input field in HTML.</p> <pre><code>&lt;input type="hidden" name="fooId" value="12-3456789-1111111111" /&gt; </code></pre> <p>I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format</p> <pre><code>&lt;input type="hidden" name="fooId" value="**[id is here]**" /&gt; </code></pre> <p>Can someone provide an example in Python to parse the HTML for the value?</p>
9
2008-09-10T21:49:53Z
55,399
<pre><code>/&lt;input type="hidden" name="fooId" value="([\d-]+)" \/&gt;/ </code></pre>
0
2008-09-10T21:56:05Z
[ "python", "regex", "screen-scraping" ]
Python regular expression for HTML parsing (BeautifulSoup)
55,391
<p>I want to grab the value of a hidden input field in HTML.</p> <pre><code>&lt;input type="hidden" name="fooId" value="12-3456789-1111111111" /&gt; </code></pre> <p>I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format</p> <pre><code>&lt;input type="hidden" name="fooId" value="**[id is here]**" /&gt; </code></pre> <p>Can someone provide an example in Python to parse the HTML for the value?</p>
9
2008-09-10T21:49:53Z
55,401
<p>Parsing is one of those areas where you really don't want to roll your own if you can avoid it, as you'll be chasing down the edge-cases and bugs for years go come</p> <p>I'd recommend using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>. It has a very good reputation and looks from the docs like it's pretty easy to use.</p>
5
2008-09-10T21:57:00Z
[ "python", "regex", "screen-scraping" ]
Python regular expression for HTML parsing (BeautifulSoup)
55,391
<p>I want to grab the value of a hidden input field in HTML.</p> <pre><code>&lt;input type="hidden" name="fooId" value="12-3456789-1111111111" /&gt; </code></pre> <p>I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format</p> <pre><code>&lt;input type="hidden" name="fooId" value="**[id is here]**" /&gt; </code></pre> <p>Can someone provide an example in Python to parse the HTML for the value?</p>
9
2008-09-10T21:49:53Z
55,404
<pre><code>import re reg = re.compile('&lt;input type="hidden" name="([^"]*)" value="&lt;id&gt;" /&gt;') value = reg.search(inputHTML).group(1) print 'Value is', value </code></pre>
8
2008-09-10T21:59:47Z
[ "python", "regex", "screen-scraping" ]
Python regular expression for HTML parsing (BeautifulSoup)
55,391
<p>I want to grab the value of a hidden input field in HTML.</p> <pre><code>&lt;input type="hidden" name="fooId" value="12-3456789-1111111111" /&gt; </code></pre> <p>I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format</p> <pre><code>&lt;input type="hidden" name="fooId" value="**[id is here]**" /&gt; </code></pre> <p>Can someone provide an example in Python to parse the HTML for the value?</p>
9
2008-09-10T21:49:53Z
55,424
<p>For this particular case, BeautifulSoup is harder to write than a regex, but it is much more robust... I'm just contributing with the BeautifulSoup example, given that you already know which regexp to use :-)</p> <pre><code>from BeautifulSoup import BeautifulSoup #Or retrieve it from the web, etc. html_data = open('/yourwebsite/page.html','r').read() #Create the soup object from the HTML data soup = BeautifulSoup(html_data) fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag value = fooId.attrs[2][1] #The value of the third attribute of the desired tag #or index it directly via fooId['value'] </code></pre>
27
2008-09-10T22:16:24Z
[ "python", "regex", "screen-scraping" ]
Python regular expression for HTML parsing (BeautifulSoup)
55,391
<p>I want to grab the value of a hidden input field in HTML.</p> <pre><code>&lt;input type="hidden" name="fooId" value="12-3456789-1111111111" /&gt; </code></pre> <p>I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format</p> <pre><code>&lt;input type="hidden" name="fooId" value="**[id is here]**" /&gt; </code></pre> <p>Can someone provide an example in Python to parse the HTML for the value?</p>
9
2008-09-10T21:49:53Z
56,144
<pre><code>/&lt;input\s+type="hidden"\s+name="([A-Za-z0-9_]+)"\s+value="([A-Za-z0-9_\-]*)"\s*/&gt;/ &gt;&gt;&gt; import re &gt;&gt;&gt; s = '&lt;input type="hidden" name="fooId" value="12-3456789-1111111111" /&gt;' &gt;&gt;&gt; re.match('&lt;input\s+type="hidden"\s+name="([A-Za-z0-9_]+)"\s+value="([A-Za-z0-9_\-]*)"\s*/&gt;', s).groups() ('fooId', '12-3456789-1111111111') </code></pre>
0
2008-09-11T09:41:15Z
[ "python", "regex", "screen-scraping" ]
Python regular expression for HTML parsing (BeautifulSoup)
55,391
<p>I want to grab the value of a hidden input field in HTML.</p> <pre><code>&lt;input type="hidden" name="fooId" value="12-3456789-1111111111" /&gt; </code></pre> <p>I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format</p> <pre><code>&lt;input type="hidden" name="fooId" value="**[id is here]**" /&gt; </code></pre> <p>Can someone provide an example in Python to parse the HTML for the value?</p>
9
2008-09-10T21:49:53Z
64,983
<p>I agree with Vinko <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> is the way to go. However I suggest using <code>fooId['value']</code> to <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#The%20attributes%20of%20Tags">get the attribute</a> rather than relying on value being the third attribute.</p> <pre><code>from BeautifulSoup import BeautifulSoup #Or retrieve it from the web, etc. html_data = open('/yourwebsite/page.html','r').read() #Create the soup object from the HTML data soup = BeautifulSoup(html_data) fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag value = fooId['value'] #The value attribute </code></pre>
18
2008-09-15T17:35:44Z
[ "python", "regex", "screen-scraping" ]
Python regular expression for HTML parsing (BeautifulSoup)
55,391
<p>I want to grab the value of a hidden input field in HTML.</p> <pre><code>&lt;input type="hidden" name="fooId" value="12-3456789-1111111111" /&gt; </code></pre> <p>I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format</p> <pre><code>&lt;input type="hidden" name="fooId" value="**[id is here]**" /&gt; </code></pre> <p>Can someone provide an example in Python to parse the HTML for the value?</p>
9
2008-09-10T21:49:53Z
1,421,480
<p>Pyparsing is a good interim step between BeautifulSoup and regex. It is more robust than just regexes, since its HTML tag parsing comprehends variations in case, whitespace, attribute presence/absence/order, but simpler to do this kind of basic tag extraction than using BS.</p> <p>Your example is especially simple, since everything you are looking for is in the attributes of the opening "input" tag. Here is a pyparsing example showing several variations on your input tag that would give regexes fits, and also shows how NOT to match a tag if it is within a comment:</p> <pre><code>html = """&lt;html&gt;&lt;body&gt; &lt;input type="hidden" name="fooId" value="**[id is here]**" /&gt; &lt;blah&gt; &lt;input name="fooId" type="hidden" value="**[id is here too]**" /&gt; &lt;input NAME="fooId" type="hidden" value="**[id is HERE too]**" /&gt; &lt;INPUT NAME="fooId" type="hidden" value="**[and id is even here TOO]**" /&gt; &lt;!-- &lt;input type="hidden" name="fooId" value="**[don't report this id]**" /&gt; --&gt; &lt;foo&gt; &lt;/body&gt;&lt;/html&gt;""" from pyparsing import makeHTMLTags, withAttribute, htmlComment # use makeHTMLTags to create tag expression - makeHTMLTags returns expressions for # opening and closing tags, we're only interested in the opening tag inputTag = makeHTMLTags("input")[0] # only want input tags with special attributes inputTag.setParseAction(withAttribute(type="hidden", name="fooId")) # don't report tags that are commented out inputTag.ignore(htmlComment) # use searchString to skip through the input foundTags = inputTag.searchString(html) # dump out first result to show all returned tags and attributes print foundTags[0].dump() print # print out the value attribute for all matched tags for inpTag in foundTags: print inpTag.value </code></pre> <p>Prints:</p> <pre><code>['input', ['type', 'hidden'], ['name', 'fooId'], ['value', '**[id is here]**'], True] - empty: True - name: fooId - startInput: ['input', ['type', 'hidden'], ['name', 'fooId'], ['value', '**[id is here]**'], True] - empty: True - name: fooId - type: hidden - value: **[id is here]** - type: hidden - value: **[id is here]** **[id is here]** **[id is here too]** **[id is HERE too]** **[and id is even here TOO]** </code></pre> <p>You can see that not only does pyparsing match these unpredictable variations, it returns the data in an object that makes it easy to read out the individual tag attributes and their values.</p>
1
2009-09-14T13:14:10Z
[ "python", "regex", "screen-scraping" ]
XML writing tools for Python
56,229
<p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p> <p>This is similar to what I'm actually doing:</p> <pre><code>import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love &amp;aacute; letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 &gt; 1" tree = ET.ElementTree(root) tree.write('foo.xhtml') # more foo.xhtml &lt;html&gt;&lt;head&gt;&lt;script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute; letters'&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
34
2008-09-11T10:35:37Z
56,262
<p>don't you actually want something like:</p> <pre><code>html(head(script(type='text/javascript', content='var a = ...')), body(h1('And I like the fact that 3 &lt; 1'), p('just some paragraph')) </code></pre> <p>I think I saw something like that somewhere. This would be wonderful.</p> <p><strong>EDIT:</strong> Actually, I went and wrote a library today to do <em>just that</em>: <a href="http://pypi.python.org/pypi/magictree" rel="nofollow">magictree</a></p> <p>You can use it like this:</p> <pre><code>from magictree import html, head, script, body, h1, p root = html( head( script('''var a = 'I love &amp;amp;aacute; letters''', type='text/javascript')), body( h1('And I like the fact that 3 &gt; 1'))) # root is a plain Element object, like those created with ET.Element... # so you can write it out using ElementTree :) tree = ET.ElementTree(root) tree.write('foo.xhtml') </code></pre> <p>The magic in <code>magictree</code> lies in how the importing works: The <code>Element</code> factories are created when needed. Have a <a href="http://code.google.com/p/pymagictree/source/browse/trunk/magictree.py" rel="nofollow">look at the source</a>, it is <a href="http://stackoverflow.com/questions/2447353/getattr-on-a-module">based on an answer to another StackOverflow question</a>.</p>
4
2008-09-11T10:55:44Z
[ "python", "xml", "xhtml" ]
XML writing tools for Python
56,229
<p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p> <p>This is similar to what I'm actually doing:</p> <pre><code>import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love &amp;aacute; letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 &gt; 1" tree = ET.ElementTree(root) tree.write('foo.xhtml') # more foo.xhtml &lt;html&gt;&lt;head&gt;&lt;script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute; letters'&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
34
2008-09-11T10:35:37Z
56,269
<p>Another way is using the <a href="http://codespeak.net/lxml/tutorial.html#the-e-factory" rel="nofollow">E Factory</a> builder from lxml (available in <a href="http://effbot.org/zone/element-builder.htm" rel="nofollow">Elementtree</a> too)</p> <pre><code>&gt;&gt;&gt; from lxml import etree &gt;&gt;&gt; from lxml.builder import E &gt;&gt;&gt; def CLASS(*args): # class is a reserved word in Python ... return {"class":' '.join(args)} &gt;&gt;&gt; html = page = ( ... E.html( # create an Element called "html" ... E.head( ... E.title("This is a sample document") ... ), ... E.body( ... E.h1("Hello!", CLASS("title")), ... E.p("This is a paragraph with ", E.b("bold"), " text in it!"), ... E.p("This is another paragraph, with a", "\n ", ... E.a("link", href="http://www.python.org"), "."), ... E.p("Here are some reserved characters: &lt;spam&amp;egg&gt;."), ... etree.XML("&lt;p&gt;And finally an embedded XHTML fragment.&lt;/p&gt;"), ... ) ... ) ... ) &gt;&gt;&gt; print(etree.tostring(page, pretty_print=True)) &lt;html&gt; &lt;head&gt; &lt;title&gt;This is a sample document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 class="title"&gt;Hello!&lt;/h1&gt; &lt;p&gt;This is a paragraph with &lt;b&gt;bold&lt;/b&gt; text in it!&lt;/p&gt; &lt;p&gt;This is another paragraph, with a &lt;a href="http://www.python.org"&gt;link&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;Here are some reservered characters: &amp;lt;spam&amp;amp;egg&amp;gt;.&lt;/p&gt; &lt;p&gt;And finally an embedded XHTML fragment.&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
28
2008-09-11T11:04:15Z
[ "python", "xml", "xhtml" ]
XML writing tools for Python
56,229
<p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p> <p>This is similar to what I'm actually doing:</p> <pre><code>import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love &amp;aacute; letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 &gt; 1" tree = ET.ElementTree(root) tree.write('foo.xhtml') # more foo.xhtml &lt;html&gt;&lt;head&gt;&lt;script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute; letters'&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
34
2008-09-11T10:35:37Z
56,470
<p>I assume that you're actually creating an XML DOM tree, because you want to validate that what goes into this file is valid XML, since otherwise you'd just write a static string to a file. If validating your output is indeed your goal, then I'd suggest</p> <pre><code>from xml.dom.minidom import parseString doc = parseString("""&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; var a = 'I love &amp;amp;aacute; letters' &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt;""") with open("foo.xhtml", "w") as f: f.write( doc.toxml() ) </code></pre> <p>This lets you just write the XML you want to output, validate that it's correct (since parseString will raise an exception if it's invalid) and have your code look much nicer.</p> <p>Presumably you're not just writing the same static XML every time and want some substitution. In this case I'd have lines like</p> <pre><code>var a = '%(message)s' </code></pre> <p>and then use the % operator to do the substitution, like</p> <pre><code>&lt;/html&gt;""" % {"message": "I love &amp;amp;aacute; letters"}) </code></pre>
10
2008-09-11T12:53:06Z
[ "python", "xml", "xhtml" ]
XML writing tools for Python
56,229
<p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p> <p>This is similar to what I'm actually doing:</p> <pre><code>import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love &amp;aacute; letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 &gt; 1" tree = ET.ElementTree(root) tree.write('foo.xhtml') # more foo.xhtml &lt;html&gt;&lt;head&gt;&lt;script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute; letters'&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
34
2008-09-11T10:35:37Z
58,460
<p>Try <a href="http://uche.ogbuji.net/tech/4suite/amara" rel="nofollow">http://uche.ogbuji.net/tech/4suite/amara</a>. It is quite complete and has a straight forward set of access tools. Normal Unicode support, etc. </p> <pre><code># #Output the XML entry # def genFileOLD(out,label,term,idval): filename=entryTime() + ".html" writer=MarkupWriter(out, indent=u"yes") writer.startDocument() #Test element and attribute writing ans=namespace=u'http://www.w3.org/2005/Atom' xns=namespace=u'http://www.w3.org/1999/xhtml' writer.startElement(u'entry', ans, extraNss={u'x':u'http://www.w3.org/1999/xhtml' , u'dc':u'http://purl.org/dc/elements/1.1'}) #u'a':u'http://www.w3.org/2005/Atom', #writer.attribute(u'xml:lang',unicode("en-UK")) writer.simpleElement(u'title',ans,content=unicode(label)) #writer.simpleElement(u'a:subtitle',ans,content=u' ') id=unicode("http://www.dpawson.co.uk/nodesets/"+afn.split(".")[0]) writer.simpleElement(u'id',ans,content=id) writer.simpleElement(u'updated',ans,content=unicode(dtime())) writer.startElement(u'author',ans) writer.simpleElement(u'name',ans,content=u'Dave ') writer.simpleElement(u'uri',ans, content=u'http://www.dpawson.co.uk/nodesets/'+afn+".xml") writer.endElement(u'author') writer.startElement(u'category', ans) if (prompt): label=unicode(raw_input("Enter label ")) writer.attribute(u'label',unicode(label)) if (prompt): term = unicode(raw_input("Enter term to use ")) writer.attribute(u'term', unicode(term)) writer.endElement(u'category') writer.simpleElement(u'rights',ans,content=u'\u00A9 Dave 2005-2008') writer.startElement(u'link',ans) writer.attribute(u'href', unicode("http://www.dpawson.co.uk/nodesets/entries/"+afn+".html")) writer.attribute(u'rel',unicode("alternate")) writer.endElement(u'link') writer.startElement(u'published', ans) dt=dtime() dtu=unicode(dt) writer.text(dtu) writer.endElement(u'published') writer.simpleElement(u'summary',ans,content=unicode(label)) writer.startElement(u'content',ans) writer.attribute(u'type',unicode("xhtml")) writer.startElement(u'div',xns) writer.simpleElement(u'h3',xns,content=unicode(label)) writer.endElement(u'div') writer.endElement(u'content') writer.endElement(u'entry') </code></pre>
0
2008-09-12T07:48:15Z
[ "python", "xml", "xhtml" ]
XML writing tools for Python
56,229
<p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p> <p>This is similar to what I'm actually doing:</p> <pre><code>import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love &amp;aacute; letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 &gt; 1" tree = ET.ElementTree(root) tree.write('foo.xhtml') # more foo.xhtml &lt;html&gt;&lt;head&gt;&lt;script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute; letters'&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
34
2008-09-11T10:35:37Z
62,157
<p>I ended up using saxutils.escape(str) to generate valid XML strings and then validating it with Eli's approach to be sure I didn't miss any tag</p> <pre><code>from xml.sax import saxutils from xml.dom.minidom import parseString from xml.parsers.expat import ExpatError xml = '''&lt;?xml version="1.0" encoding="%s"?&gt;\n &lt;contents title="%s" crawl_date="%s" in_text_date="%s" url="%s"&gt;\n&lt;main_post&gt;%s&lt;/main_post&gt;\n&lt;/contents&gt;''' % (self.encoding, saxutils.escape(title), saxutils.escape(time), saxutils.escape(date), saxutils.escape(url), saxutils.escape(contents)) try: minidoc = parseString(xml) catch ExpatError: print "Invalid xml" </code></pre>
3
2008-09-15T11:00:37Z
[ "python", "xml", "xhtml" ]
XML writing tools for Python
56,229
<p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p> <p>This is similar to what I'm actually doing:</p> <pre><code>import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love &amp;aacute; letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 &gt; 1" tree = ET.ElementTree(root) tree.write('foo.xhtml') # more foo.xhtml &lt;html&gt;&lt;head&gt;&lt;script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute; letters'&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
34
2008-09-11T10:35:37Z
3,098,902
<p>There's always <a href="http://effbot.org/zone/xml-writer.htm">SimpleXMLWriter</a>, part of the ElementTree toolkit. The interface is dead simple.</p> <p>Here's an example: </p> <pre><code>from elementtree.SimpleXMLWriter import XMLWriter import sys w = XMLWriter(sys.stdout) html = w.start("html") w.start("head") w.element("title", "my document") w.element("meta", name="generator", value="my application 1.0") w.end() w.start("body") w.element("h1", "this is a heading") w.element("p", "this is a paragraph") w.start("p") w.data("this is ") w.element("b", "bold") w.data(" and ") w.element("i", "italic") w.data(".") w.end("p") w.close(html) </code></pre>
24
2010-06-23T04:16:17Z
[ "python", "xml", "xhtml" ]
XML writing tools for Python
56,229
<p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p> <p>This is similar to what I'm actually doing:</p> <pre><code>import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love &amp;aacute; letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 &gt; 1" tree = ET.ElementTree(root) tree.write('foo.xhtml') # more foo.xhtml &lt;html&gt;&lt;head&gt;&lt;script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute; letters'&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
34
2008-09-11T10:35:37Z
7,060,046
<p><a href="https://github.com/galvez/xmlwitch">https://github.com/galvez/xmlwitch</a>:</p> <pre><code>import xmlwitch xml = xmlwitch.Builder(version='1.0', encoding='utf-8') with xml.feed(xmlns='http://www.w3.org/2005/Atom'): xml.title('Example Feed') xml.updated('2003-12-13T18:30:02Z') with xml.author: xml.name('John Doe') xml.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6') with xml.entry: xml.title('Atom-Powered Robots Run Amok') xml.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a') xml.updated('2003-12-13T18:30:02Z') xml.summary('Some text.') print(xml) </code></pre>
7
2011-08-14T22:09:27Z
[ "python", "xml", "xhtml" ]
XML writing tools for Python
56,229
<p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p> <p>This is similar to what I'm actually doing:</p> <pre><code>import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love &amp;aacute; letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 &gt; 1" tree = ET.ElementTree(root) tree.write('foo.xhtml') # more foo.xhtml &lt;html&gt;&lt;head&gt;&lt;script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute; letters'&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
34
2008-09-11T10:35:37Z
19,728,898
<p>For anyone encountering this now, there's actually a way to do this hidden away in Python's standard library in <a href="http://docs.python.org/2.7/library/xml.sax.utils.html" rel="nofollow">xml.sax.utils.XMLGenerator</a>. Here's an example of it in action:</p> <pre><code>&gt;&gt;&gt; from xml.sax.saxutils import XMLGenerator &gt;&gt;&gt; import StringIO &gt;&gt;&gt; w = XMLGenerator(out, 'utf-8') &gt;&gt;&gt; w.startDocument() &gt;&gt;&gt; w.startElement("test", {'bar': 'baz'}) &gt;&gt;&gt; w.characters("Foo") &gt;&gt;&gt; w.endElement("test") &gt;&gt;&gt; w.endDocument() &gt;&gt;&gt; print out.getvalue() &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;test bar="baz"&gt;Foo&lt;/test&gt; </code></pre>
2
2013-11-01T14:36:08Z
[ "python", "xml", "xhtml" ]
Anyone used Dabo for a medium-big project?
56,417
<p>We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects?<br /> Thanks for your time!</p>
18
2008-09-11T12:29:09Z
103,212
<p>I have no Dabo experience at all but this question is on the top of the list fo such a long time that I decided to give it a shot:</p> <h2>Framework selection</h2> <h2>Assumptions:</h2> <ol> <li>medium-to-big project: we're talking about a team of more than 20 people working on something for about a year for the first phase. This is usually an expensive and very important effort for the client.</li> <li>this project will have significant amount of users (around a hundred) so performance is essential</li> <li>it's an ERP project so the application will work with large amounts of information</li> <li>you have no prior Dabo experience in your team</li> </ol> <h2>Considerations:</h2> <ol> <li>I could not open Dabo project site right now. There seems to be some server problem. That alone would make me think twice about using it for a big project.</li> <li>It's not a well-known framework. Typing Dabo in Google returns almost no useful results, it does not have a Wikipedia page, all-in-all it's quite obscure. It means that when you will have problems with it (and you will have problems with it) you will have almost no place to go. Your question was unanswered for 8 days on SO, this alone would make me re-consider. If you base your project on an obscure technology you have no previous experience with - it's a huge risk.</li> <li>You don't have people who know that framework in your team. It means that you have to learn it to get any results at all and to master it will require quite significant amount of time. You will have to factor that time into your project plan. Do you really need it?</li> <li>What does this framework give you that you cannot do yourself? Quite a lot of time my team tried to use some third-party component or tool only to find that building a custom one would be faster than dealing with third-party problems and limitations. There are brilliant tools available to people nowadays and we would be lost without them - but you have to carefully consider if this tool is one of them</li> <li>Dabo project version is 0.84. Do you know if they spend time optimising their code for performance at this stage? Did you run any tests to see it will sustain the load you have in your NFRs.</li> </ol> <p>Hope that helps :) Good luck with your project</p>
1
2008-09-19T15:56:41Z
[ "python", "erp", "dabo" ]
Anyone used Dabo for a medium-big project?
56,417
<p>We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects?<br /> Thanks for your time!</p>
18
2008-09-11T12:29:09Z
106,464
<p>I'm one of the authors of the Dabo framework. One of our users pointed out to me the extremely negative answer you received, and so I thought I had better chime in and clear up some of the incorrect assumptions in the first reply.</p> <p>Dabo is indeed well-known in the Python community. I have presented it at 3 of the last 4 US PyCons, and we have several hundred users who subscribe to our email lists. Our website (<a href="http://dabodev.com">http://dabodev.com</a>) has not had any service interruptions; I don't know why the first responder claimed to have trouble. Support is through our email lists, and we pride ourselves on helping people quickly and efficiently. Many of the newbie questions help us to identify places where our docs are lacking, so we strongly encourage newcomers to ask questions!</p> <p>Dabo has been around for 4 years. The fact that it is still a few days away from a 0.9 release is more of a reflection of the rather conservative version numbering of my partner, Paul McNett, than any instabilities in the framework. I know of Dabo apps that have been in production since 2006; I have used it for my own projects since 2004. Whatever importance you attach to release numbers, we are at revision 4522, with consistent work being done to add more and more stuff to the framework; refactor and streamline some of the older code, and yes, clean up some bugs.</p> <p>Please sign up for our free email support list:</p> <p><a href="http://leafe.com/mailman/listinfo/dabo-users">http://leafe.com/mailman/listinfo/dabo-users</a></p> <p>...and ask any questions you may have about Dabo there. Not many people have discovered Stack Overflow yet, so I wouldn't expect very informed answers here yet. There are several regular contributors there who use Dabo on a daily basis, and are usually more than happy to offer their opinions and their help.</p>
24
2008-09-19T23:55:08Z
[ "python", "erp", "dabo" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
56,832
<p>What about:</p> <pre><code>round(n,1)+epsilon </code></pre>
-4
2008-09-11T15:11:04Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
56,833
<p>can't help the way it's stored, but at least formatting works correctly: </p> <pre><code>'%.1f' % round(n, 1) # gives you '5.6' </code></pre>
66
2008-09-11T15:11:41Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
56,840
<p>You can switch the data type to a integer:</p> <pre><code>&gt;&gt;&gt; n = 5.59 &gt;&gt;&gt; int(n * 10) / 10.0 5.5 &gt;&gt;&gt; int(n * 10 + 0.5) 56 </code></pre> <p>And then display the number by inserting the locale's decimal separator.</p> <p>However, <a href="http://stackoverflow.com/questions/56820/round-in-python-doesnt-seem-to-be-rounding-properly#56833" rel="nofollow">Jimmy's answer</a> is better.</p>
5
2008-09-11T15:12:19Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
56,841
<p>You can use the string format operator <code>%</code>, similar to sprintf.</p> <pre><code>mystring = "%.2f" % 5.5999 </code></pre>
3
2008-09-11T15:12:25Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
56,844
<p>You get '5.6' if you do <code>str(round(n, 1))</code> instead of just <code>round(n, 1)</code>.</p>
9
2008-09-11T15:13:28Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
56,845
<p>Floating point math is vulnerable to slight, but annoying, precision inaccuracies. If you can work with integer or fixed point, you will be guaranteed precision.</p>
5
2008-09-11T15:13:32Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
56,849
<p><strong>printf</strong> the sucker.</p> <pre><code>print '%.1f' % 5.59 # returns 5.6 </code></pre>
3
2008-09-11T15:14:15Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
56,850
<p>Formatting works correctly even without having to round:</p> <pre><code>"%.1f" % n </code></pre>
81
2008-09-11T15:14:22Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
57,704
<p><code>round(5.59, 1)</code> is working fine. The problem is that 5.6 cannot be represented exactly in binary floating point.</p> <pre><code>&gt;&gt;&gt; 5.6 5.5999999999999996 &gt;&gt;&gt; </code></pre> <p>As Vinko says, you can use string formatting to do rounding for display.</p> <p>Python has a <a href="http://docs.python.org/lib/module-decimal.html">module for decimal arithmetic</a> if you need that.</p>
15
2008-09-11T21:27:35Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
3,225,829
<p>Take a look at the <a href="http://docs.python.org/library/decimal.html" rel="nofollow">Decimal module</a></p> <blockquote> <p>Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – excerpt from the decimal arithmetic specification.</p> </blockquote> <p>and </p> <blockquote> <p>Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have an exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.</p> </blockquote> <p>Decimal provides the kind of operations that make it easy to write apps that require floating point operations and <em>also</em> need to present those results in a human readable format, e.g., accounting.</p>
3
2010-07-12T04:12:38Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
15,398,691
<p>If you use the Decimal module you can approximate without the use of the 'round' function. Here is what I've been using for rounding especially when writing monetary applications: </p> <pre><code>Decimal(str(16.2)).quantize(Decimal('.01'), rounding=ROUND_UP) </code></pre> <p>This will return a Decimal Number which is 16.20. </p>
11
2013-03-13T23:48:33Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
17,296,776
<p>It's a big problem indeed. Try out this code:</p> <pre><code>print "%.2f" % (round((2*4.4+3*5.6+3*4.4)/8,2),) </code></pre> <p>It displays 4.85. Then you do: </p> <pre><code>print "Media = %.1f" % (round((2*4.4+3*5.6+3*4.4)/8,1),) </code></pre> <p>and it shows 4.8. Do you calculations by hand the exact answer is 4.85, but if you try: </p> <pre><code>print "Media = %.20f" % (round((2*4.4+3*5.6+3*4.4)/8,20),) </code></pre> <p>you can see the truth: the float point is stored as the nearest finite sum of fractions whose denominators are powers of two.</p>
2
2013-06-25T12:00:58Z
[ "python", "floating-point" ]
round() in Python doesn't seem to be rounding properly
56,820
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
71
2008-09-11T15:08:09Z
33,771,679
<p>Works Perfect </p> <pre><code>format(5.59, '.1f') # to display float(format(5.59, '.1f')) #to round </code></pre>
1
2015-11-18T04:10:22Z
[ "python", "floating-point" ]
Convert XML/HTML Entities into Unicode String in Python
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
60
2008-09-11T21:28:46Z
57,745
<p>You could find an answer here -- <a href="http://stackoverflow.com/questions/53224/getting-international-characters-from-a-web-page#53246">Getting international characters from a web page?</a></p> <p><strong>EDIT</strong>: It seems like <code>BeautifulSoup</code> doesn't convert entities written in hexadecimal form. It can be fixed:</p> <pre><code>import copy, re from BeautifulSoup import BeautifulSoup hexentityMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE) # replace hexadecimal character reference by decimal one hexentityMassage += [(re.compile('&amp;#x([^;]+);'), lambda m: '&amp;#%d;' % int(m.group(1), 16))] def convert(html): return BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES, markupMassage=hexentityMassage).contents[0].string html = '&lt;html&gt;&amp;#x01ce;&amp;#462;&lt;/html&gt;' print repr(convert(html)) # u'\u01ce\u01ce' </code></pre> <p><strong>EDIT</strong>: </p> <p><a href="http://effbot.org/zone/re-sub.htm#unescape-html" rel="nofollow"><code>unescape()</code></a> function mentioned by <a href="http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python/58125#58125">@dF</a> which uses <code>htmlentitydefs</code> standard module and <code>unichr()</code> might be more appropriate in this case.</p>
7
2008-09-11T21:52:28Z
[ "python", "html", "entities" ]
Convert XML/HTML Entities into Unicode String in Python
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
60
2008-09-11T21:28:46Z
57,877
<p>Use the builtin <code>unichr</code> -- BeautifulSoup isn't necessary:</p> <pre><code>&gt;&gt;&gt; entity = '&amp;#x01ce' &gt;&gt;&gt; unichr(int(entity[3:],16)) u'\u01ce' </code></pre>
18
2008-09-11T23:09:08Z
[ "python", "html", "entities" ]
Convert XML/HTML Entities into Unicode String in Python
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
60
2008-09-11T21:28:46Z
58,125
<p>Python has the <a href="https://docs.python.org/2/library/htmllib.html#module-htmlentitydefs">htmlentitydefs</a> module, but this doesn't include a function to unescape HTML entities.</p> <p>Python developer Fredrik Lundh (author of elementtree, among other things) has such a function <a href="http://effbot.org/zone/re-sub.htm#unescape-html">on his website</a>, which works with decimal, hex and named entities:</p> <pre><code>import re, htmlentitydefs ## # Removes HTML or XML character references and entities from a text string. # # @param text The HTML (or XML) source text. # @return The plain text, as a Unicode string, if necessary. def unescape(text): def fixup(m): text = m.group(0) if text[:2] == "&amp;#": # character reference try: if text[:3] == "&amp;#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("&amp;#?\w+;", fixup, text) </code></pre>
55
2008-09-12T01:40:41Z
[ "python", "html", "entities" ]
Convert XML/HTML Entities into Unicode String in Python
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
60
2008-09-11T21:28:46Z
573,629
<p>This is a function which should help you to get it right and convert entities back to utf-8 characters.</p> <pre><code>def unescape(text): """Removes HTML or XML character references and entities from a text string. @param text The HTML (or XML) source text. @return The plain text, as a Unicode string, if necessary. from Fredrik Lundh 2008-01-03: input only unicode characters string. http://effbot.org/zone/re-sub.htm#unescape-html """ def fixup(m): text = m.group(0) if text[:2] == "&amp;#": # character reference try: if text[:3] == "&amp;#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: print "Value Error" pass else: # named entity # reescape the reserved characters. try: if text[1:-1] == "amp": text = "&amp;amp;amp;" elif text[1:-1] == "gt": text = "&amp;amp;gt;" elif text[1:-1] == "lt": text = "&amp;amp;lt;" else: print text[1:-1] text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: print "keyerror" pass return text # leave as is return re.sub("&amp;#?\w+;", fixup, text) </code></pre>
6
2009-02-21T19:45:58Z
[ "python", "html", "entities" ]
Convert XML/HTML Entities into Unicode String in Python
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
60
2008-09-11T21:28:46Z
4,438,857
<p>Not sure why the Stack Overflow thread does not include the ';' in the search/replace (i.e. lambda m: '&amp;#%d*<em>;</em>*') If you don't, BeautifulSoup can barf because the adjacent character can be interpreted as part of the HTML code (i.e. &amp;#39B for &amp;#39Blackout). </p> <p>This worked better for me:</p> <pre><code>import re from BeautifulSoup import BeautifulSoup html_string='&lt;a href="/cgi-bin/article.cgi?f=/c/a/2010/12/13/BA3V1GQ1CI.DTL"title=""&gt;&amp;#x27;Blackout in a can; on some shelves despite ban&lt;/a&gt;' hexentityMassage = [(re.compile('&amp;#x([^;]+);'), lambda m: '&amp;#%d;' % int(m.group(1), 16))] soup = BeautifulSoup(html_string, convertEntities=BeautifulSoup.HTML_ENTITIES, markupMassage=hexentityMassage) </code></pre> <ol> <li>The int(m.group(1), 16) converts the number (specified in base-16) format back to an integer. </li> <li>m.group(0) returns the entire match, m.group(1) returns the regexp capturing group </li> <li>Basically using markupMessage is the same as:<br> html_string = re.sub('&amp;#x([^;]+);', lambda m: '&amp;#%d;' % int(m.group(1), 16), html_string) </li> </ol>
3
2010-12-14T11:52:26Z
[ "python", "html", "entities" ]
Convert XML/HTML Entities into Unicode String in Python
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
60
2008-09-11T21:28:46Z
9,216,990
<p>An alternative, if you have lxml:</p> <pre><code>&gt;&gt;&gt; import lxml.html &gt;&gt;&gt; lxml.html.fromstring('&amp;#x01ce').text u'\u01ce' </code></pre>
14
2012-02-09T18:55:48Z
[ "python", "html", "entities" ]
Convert XML/HTML Entities into Unicode String in Python
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
60
2008-09-11T21:28:46Z
12,614,706
<p>The standard lib’s very own HTMLParser has an undocumented function unescape() which does exactly what you think it does:</p> <pre><code>import HTMLParser h = HTMLParser.HTMLParser() h.unescape('&amp;copy; 2010') # u'\xa9 2010' h.unescape('&amp;#169; 2010') # u'\xa9 2010' </code></pre>
45
2012-09-27T05:34:44Z
[ "python", "html", "entities" ]
Convert XML/HTML Entities into Unicode String in Python
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
60
2008-09-11T21:28:46Z
27,424,874
<p>If you are on Python 3.4 you can just do:</p> <pre><code>s = html.unescape(s) </code></pre> <p><a href="https://docs.python.org/3.4/library/html.html#html.unescape">https://docs.python.org/3.4/library/html.html#html.unescape</a></p>
5
2014-12-11T14:12:00Z
[ "python", "html", "entities" ]
Convert XML/HTML Entities into Unicode String in Python
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
60
2008-09-11T21:28:46Z
33,486,253
<p>Another solution is the builtin library xml.sax.saxutils (both for html and xml). However, it will convert only &amp;gt, &amp;amp and &amp;lt.</p> <pre><code>from xml.sax.saxutils import unescape escaped_text = unescape(text_to_escape) </code></pre>
1
2015-11-02T20:28:35Z
[ "python", "html", "entities" ]
Convert XML/HTML Entities into Unicode String in Python
57,708
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
60
2008-09-11T21:28:46Z
34,463,462
<p>Here is the Python 3 version of <a href="http://stackoverflow.com/a/58125/2086547">dF's answer</a>:</p> <pre><code>import re import html.entities def unescape(text): """ Removes HTML or XML character references and entities from a text string. :param text: The HTML (or XML) source text. :return: The plain text, as a Unicode string, if necessary. """ def fixup(m): text = m.group(0) if text[:2] == "&amp;#": # character reference try: if text[:3] == "&amp;#x": return chr(int(text[3:-1], 16)) else: return chr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = chr(html.entities.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("&amp;#?\w+;", fixup, text) </code></pre> <p>The main changes concern <code>htmlentitydefs</code> that is now <code>html.entities</code> and <code>unichr</code> that is now <code>chr</code>. See this <a href="http://docs.pythonsprints.com/python3_porting/py-porting.html#reorganization" rel="nofollow">Python 3 porting guide</a>.</p>
0
2015-12-25T13:55:16Z
[ "python", "html", "entities" ]
Does re.compile() or any given Python library call throw an exception?
58,119
<p>I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are? </p>
11
2008-09-12T01:35:33Z
58,129
<p>Well, <code>re.compile</code> certainly may:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.compile('he(lo') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python25\lib\re.py", line 180, in compile return _compile(pattern, flags) File "C:\Python25\lib\re.py", line 233, in _compile raise error, v # invalid expression sre_constants.error: unbalanced parenthesis </code></pre> <p><a href="http://docs.python.org/lib/node46.html#l2h-408">The documentation</a> does support this, in a roundabout way - check the bottom of the "Module Contents" page for (brief) description of the <code>error</code> exception.</p> <p>Unfortunately, I don't have any answer to the general question. I suppose the documentation for the various modules varies in quality and thoroughness. If there were particular modules you were interested in, you might be able to <a href="http://www.depython.net/">decompile</a> them (if written in Python) or even <a href="http://www.python.org/download/">look at the source</a>, if they're in the standard library.</p>
9
2008-09-12T01:42:38Z
[ "python", "regex", "exception" ]
Does re.compile() or any given Python library call throw an exception?
58,119
<p>I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are? </p>
11
2008-09-12T01:35:33Z
58,168
<p>Unlike Java, where there are exceptions that must be declared to be raised (and some that don't have to be, but that's another story), any Python code may raise any exception at any time.</p> <p>There are a list of <a href="http://docs.python.org/lib/module-exceptions.html">built-in exceptions</a>, which generally has some description of when these exceptions might be raised. Its up to you as to how much exception handling you will do, and if you will handle stuff gracefully, or just fail with a traceback.</p>
6
2008-09-12T02:10:16Z
[ "python", "regex", "exception" ]
How do I get the external IP of a socket in Python?
58,294
<p>When I call <code>socket.getsockname()</code> on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?</p>
8
2008-09-12T04:21:51Z
58,296
<p>This isn't possible without cooperation from an external server, because there could be any number of NATs between you and the other computer. If it's a custom protocol, you could ask the other system to report what address it's connected to.</p>
7
2008-09-12T04:23:53Z
[ "python", "sockets" ]
How do I get the external IP of a socket in Python?
58,294
<p>When I call <code>socket.getsockname()</code> on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?</p>
8
2008-09-12T04:21:51Z
58,299
<p>The only way I can think of that's guaranteed to give it to you is to hit a service like <a href="http://whatismyip.com/" rel="nofollow">http://whatismyip.com/</a> to get it.</p>
4
2008-09-12T04:24:34Z
[ "python", "sockets" ]
How do I get the external IP of a socket in Python?
58,294
<p>When I call <code>socket.getsockname()</code> on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?</p>
8
2008-09-12T04:21:51Z
256,358
<p>import socket</p> <p>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</p> <p>s.connect(("msn.com",80))</p> <p>s.getsockname()</p>
1
2008-11-02T01:17:04Z
[ "python", "sockets" ]
How do I get the external IP of a socket in Python?
58,294
<p>When I call <code>socket.getsockname()</code> on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?</p>
8
2008-09-12T04:21:51Z
2,646,313
<p>Using the address suggested in the source of <a href="http://whatismyip.com" rel="nofollow">http://whatismyip.com</a></p> <pre><code>import urllib def get_my_ip_address(): whatismyip = 'http://www.whatismyip.com/automation/n09230945.asp' return urllib.urlopen(whatismyip).readlines()[0] </code></pre>
0
2010-04-15T14:46:48Z
[ "python", "sockets" ]
How do I get the external IP of a socket in Python?
58,294
<p>When I call <code>socket.getsockname()</code> on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?</p>
8
2008-09-12T04:21:51Z
8,305,740
<p><a href="https://github.com/bobeirasa/mini-scripts/blob/master/externalip.py" rel="nofollow">https://github.com/bobeirasa/mini-scripts/blob/master/externalip.py</a></p> <pre><code>''' Finds your external IP address ''' import urllib import re def get_ip(): group = re.compile(u'(?P&lt;ip&gt;\d+\.\d+\.\d+\.\d+)').search(urllib.URLopener().open('http://jsonip.com/').read()).groupdict() return group['ip'] if __name__ == '__main__': print get_ip() </code></pre>
3
2011-11-29T04:11:24Z
[ "python", "sockets" ]
How do I get the external IP of a socket in Python?
58,294
<p>When I call <code>socket.getsockname()</code> on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?</p>
8
2008-09-12T04:21:51Z
8,848,856
<pre><code>print (urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()) </code></pre>
1
2012-01-13T10:10:36Z
[ "python", "sockets" ]
Can I document Python code with doxygen (and does it make sense)?
58,622
<p>I like doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /* .. */ comments and also has its own self-documentation facility which seems to be the pythonic way to document.</p> <p>Can I just use doxygen? Anything particular to be aware of?</p> <p>I have done some coding in Python but so far only on small projects where I was to lazy to document at all (yeah, I know ... but let's just pretend that's OK for now).</p>
49
2008-09-12T10:26:40Z
58,701
<p>This is <a href="http://www.stack.nl/~dimitri/doxygen/docblocks.html#pythonblocks">documented on the doxygen website</a>, but to summarize here:</p> <p>You can use doxygen to document your Python code. You can either use the Python documentation string syntax:</p> <pre><code>"""@package docstring Documentation for this module. More details. """ def func(): """Documentation for a function. More details. """ pass </code></pre> <p>In which case the comments will be extracted by doxygen, but you won't be able to use any of the <a href="http://www.stack.nl/~dimitri/doxygen/commands.html#cmd_intro">special doxygen commands</a>.</p> <p><strong>Or</strong> you can (similar to C-style languages under doxygen) double up the comment marker (<code>#</code>) on the first line before the member:</p> <pre><code>## @package pyexample # Documentation for this module. # # More details. ## Documentation for a function. # # More details. def func(): pass </code></pre> <p>In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting <code>OPTMIZE_OUTPUT_JAVA</code> to <code>YES</code>.</p> <p>Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?</p>
30
2008-09-12T11:11:03Z
[ "python", "documentation", "doxygen", "docstring", "python-sphinx" ]
Can I document Python code with doxygen (and does it make sense)?
58,622
<p>I like doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /* .. */ comments and also has its own self-documentation facility which seems to be the pythonic way to document.</p> <p>Can I just use doxygen? Anything particular to be aware of?</p> <p>I have done some coding in Python but so far only on small projects where I was to lazy to document at all (yeah, I know ... but let's just pretend that's OK for now).</p>
49
2008-09-12T10:26:40Z
59,018
<p>An other very good documentation tool is <a href="http://sphinx.pocoo.org/">sphinx</a>. It will be used for the upcoming python 2.6 <a href="http://docs.python.org/dev/">documentation</a> and is used by <a href="http://docs.djangoproject.com/en/dev/">django</a> and a lot of other python projects.</p> <p>From the sphinx website:</p> <ul> <li><strong>Output formats</strong>: HTML (including Windows HTML Help) and LaTeX, for printable PDF versions</li> <li><strong>Extensive cross-references</strong>: semantic markup and automatic links for functions, classes, glossary terms and similar pieces of information</li> <li><strong>Hierarchical structure</strong>: easy definition of a document tree, with automatic links to siblings, parents and children</li> <li><strong>Automatic indices</strong>: general index as well as a module index</li> <li><strong>Code handling</strong>: automatic highlighting using the Pygments highlighter</li> <li><strong>Extensions</strong>: automatic testing of code snippets, inclusion of docstrings from Python modules, and more</li> </ul>
11
2008-09-12T13:48:59Z
[ "python", "documentation", "doxygen", "docstring", "python-sphinx" ]
Can I document Python code with doxygen (and does it make sense)?
58,622
<p>I like doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /* .. */ comments and also has its own self-documentation facility which seems to be the pythonic way to document.</p> <p>Can I just use doxygen? Anything particular to be aware of?</p> <p>I have done some coding in Python but so far only on small projects where I was to lazy to document at all (yeah, I know ... but let's just pretend that's OK for now).</p>
49
2008-09-12T10:26:40Z
59,955
<p>Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.</p> <p>For generating API docs from Python docstrings, the leading tools are <a href="https://github.com/BurntSushi/pdoc" rel="nofollow">pdoc</a> and <a href="https://launchpad.net/pydoctor" rel="nofollow">pydoctor</a>. Here's pydoctor's generated API docs for <a href="http://twistedmatrix.com/documents/current/api" rel="nofollow">Twisted</a> and <a href="http://starship.python.net/crew/mwh/bzrlibapi/" rel="nofollow">Bazaar</a>.</p> <p>Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the "<a href="https://docs.python.org/2/library/pydoc.html" rel="nofollow">pydoc</a>" command line tool and as well as the <code>help()</code> function available in the interactive interpreter.</p>
18
2008-09-12T21:04:48Z
[ "python", "documentation", "doxygen", "docstring", "python-sphinx" ]
Can I document Python code with doxygen (and does it make sense)?
58,622
<p>I like doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /* .. */ comments and also has its own self-documentation facility which seems to be the pythonic way to document.</p> <p>Can I just use doxygen? Anything particular to be aware of?</p> <p>I have done some coding in Python but so far only on small projects where I was to lazy to document at all (yeah, I know ... but let's just pretend that's OK for now).</p>
49
2008-09-12T10:26:40Z
497,322
<p>The <a href="https://pypi.python.org/pypi/doxypy/">doxypy</a> input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.</p>
48
2009-01-30T21:30:02Z
[ "python", "documentation", "doxygen", "docstring", "python-sphinx" ]
Can I document Python code with doxygen (and does it make sense)?
58,622
<p>I like doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /* .. */ comments and also has its own self-documentation facility which seems to be the pythonic way to document.</p> <p>Can I just use doxygen? Anything particular to be aware of?</p> <p>I have done some coding in Python but so far only on small projects where I was to lazy to document at all (yeah, I know ... but let's just pretend that's OK for now).</p>
49
2008-09-12T10:26:40Z
35,377,654
<p>In the end, you only have two options:</p> <p>You generate your content using Doxygen, or you generate your content using Sphinx*.</p> <ol> <li><p><strong>Doxygen</strong>: It is not the tool of choice for most Python projects. But if you have to deal with other related projects written in C or C++ it could make sense. For this you can improve the integration between Doxygen and Python using <a href="https://github.com/Feneric/doxypypy" rel="nofollow">doxypypy</a>.</p></li> <li><p><strong>Sphinx</strong>: The defacto tool for documenting a Python project. You have three options here: manual, semi-automatic (stub generation) and fully automatic (Doxygen like). </p> <ol> <li>For manual API documentation you have Sphinx <a href="http://www.sphinx-doc.org/en/stable/ext/autodoc.html" rel="nofollow">autodoc</a>. This is great to write a user guide with embedded API generated elements.</li> <li>For semi-automatic you have Sphinx <a href="http://www.sphinx-doc.org/en/stable/ext/autosummary.html" rel="nofollow">autosummary</a>. You can either setup your build system to call sphinx-autogen or setup your Sphinx with the <code>autosummary_generate</code> config. You will require to setup a page with the autosummaries, and then manually edit the pages. You have options, but my experience with this approach is that it requires way too much configuration, and at the end even after creating new templates, I found bugs and the impossibility to determine exactly what was exposed as public API and what not. My opinion is this tool is good for stub generation that will require manual editing, and nothing more. Is like a shortcut to end up in manual.</li> <li>Fully automatic. This have been criticized many times and for long we didn't have a good fully automatic Python API generator integrated with Sphinx until <a href="http://autoapi.readthedocs.org/" rel="nofollow">AutoAPI</a> came, which is a new kid in the block. This is by far the best for automatic API generation in Python (note: shameless self-promotion).</li> </ol></li> </ol> <p>There are other options to note:</p> <ul> <li><a href="https://breathe.readthedocs.org/" rel="nofollow">Breathe</a>: this started as a very good idea, and makes sense when you work with several related project in other languages that use Doxygen. The idea is to use Doxygen XML output and feed it to Sphinx to generate your API. So, you can keep all the goodness of Doxygen and unify the documentation system in Sphinx. Awesome in theory. Now, in practice, the last time I checked the project wasn't ready for production.</li> <li><a href="https://github.com/twisted/pydoctor" rel="nofollow">pydoctor</a>*: Very particular. Generates its own output. It has some basic integration with Sphinx, and some nice features.</li> </ul>
4
2016-02-13T08:16:17Z
[ "python", "documentation", "doxygen", "docstring", "python-sphinx" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
58,917
<p>You could actually pull this off, but it would require using metaclasses, which are <em>deep</em> magic (there be dragons). If you want an intro to metaclasses, there's a series of <a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html" rel="nofollow">articles from IBM</a> which manage to introduce the ideas without melting your brain.</p> <p>The source code from an ORM like SQLObject might help, too, since it uses this same kind of declarative syntax.</p>
7
2008-09-12T13:13:57Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
58,990
<p>Maybe not as slick as the Ruby version, but how about something like this:</p> <pre><code>from Boots import App, Para, Button, alert def Shoeless(App): t = Para(text = 'Not Clicked') b = Button(label = 'The label') def on_b_clicked(self): alert('You clicked the button!') self.t.text = 'Clicked!' </code></pre> <p><a href="http://stackoverflow.com/questions/58711/how-would-you-design-a-very-pythonic-ui-framework#58917" rel="nofollow">Like Justin said</a>, to implement this you would need to use a custom metaclass on class <code>App</code>, and a bunch of properties on <code>Para</code> and <code>Button</code>. This actually wouldn't be too hard.</p> <p>The problem you run into next is: how do you keep track of the <em>order</em> that things appear in the class definition? In Python 2.x, there is no way to know if <code>t</code> should be above <code>b</code> or the other way around, since you receive the contents of the class definition as a python <code>dict</code>.</p> <p>However, in Python 3.0 <a href="http://www.python.org/dev/peps/pep-3115/" rel="nofollow">metaclasses are being changed</a> in a couple of (minor) ways. One of them is the <code>__prepare__</code> method, which allows you to supply your own custom dictionary-like object to be used instead -- this means you'll be able to track the order in which items are defined, and position them accordingly in the window.</p>
2
2008-09-12T13:40:35Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
60,563
<p>This could be an oversimplification, i don't think it would be a good idea to try to make a general purpose ui library this way. On the other hand you could use this approach (metaclasses and friends) to simplify the definition of certain classes of user interfaces for an existing ui library and depending of the application that could actually save you a significant amount of time and code lines.</p>
2
2008-09-13T14:20:42Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
62,780
<p>With some Metaclass magic to keep the ordering I have the following working. I'm not sure how pythonic it is but it is good fun for creating simple things. </p> <pre><code>class w(Wndw): title='Hello World' class txt(Txt): # either a new class text='Insert name here' lbl=Lbl(text='Hello') # or an instance class greet(Bbt): text='Greet' def click(self): #on_click method self.frame.lbl.text='Hello %s.'%self.frame.txt.text app=w() </code></pre>
3
2008-09-15T13:18:54Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
334,828
<p>I have this same problem. I wan to to create a wrapper around any GUI toolkit for Python that is easy to use, and inspired by Shoes, but needs to be a OOP approach (against ruby blocks).</p> <p>More information in: <a href="http://wiki.alcidesfonseca.com/blog/python-universal-gui-revisited" rel="nofollow">http://wiki.alcidesfonseca.com/blog/python-universal-gui-revisited</a></p> <p>Anyone's welcome to join the project.</p>
1
2008-12-02T17:48:06Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
334,938
<p>The only attempt to do this that I know of is <a href="http://zephyrfalcon.org/labs/dope_on_wax.html" rel="nofollow">Hans Nowak's Wax</a> (which is unfortunately dead).</p>
3
2008-12-02T18:23:10Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
335,077
<p>The closest you can get to rubyish blocks is the with statement from pep343: </p> <p><a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow">http://www.python.org/dev/peps/pep-0343/</a></p>
3
2008-12-02T19:09:45Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
335,132
<p>I was never satisfied with David Mertz's articles at IBM on metaclsses so I recently wrote my own <a href="http://askawizard.blogspot.com/2008/09/metaclasses-python-saga-part-4_30.html" rel="nofollow">metaclass article</a>. Enjoy.</p>
4
2008-12-02T19:30:23Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
335,358
<p>If you really want to code UI, you could try to get something similar to django's ORM; sth like this to get a simple help browser:</p> <pre><code>class MyWindow(Window): class VBox: entry = Entry() bigtext = TextView() def on_entry_accepted(text): bigtext.value = eval(text).__doc__ </code></pre> <p>The idea would be to interpret some containers (like windows) as simple classes, some containers (like tables, v/hboxes) recognized by object names, and simple widgets as objects.</p> <p>I dont think one would have to name all containers inside a window, so some shortcuts (like old-style classes being recognized as widgets by names) would be desirable.</p> <p>About the order of elements: in MyWindow above you don't have to track this (window is conceptually a one-slot container). In other containers you can try to keep track of the order assuming that each widget constructor have access to some global widget list. This is how it is done in django (AFAIK).</p> <p>Few hacks here, few tweaks there... There are still few things to think of, but I believe it is possible... and usable, as long as you don't build complicated UIs.</p> <p>However I am pretty happy with PyGTK+Glade. UI is just kind of data for me and it should be treated as data. There's just too much parameters to tweak (like spacing in different places) and it is better to manage that using a GUI tool. Therefore I build my UI in glade, save as xml and parse using gtk.glade.XML().</p>
1
2008-12-02T20:37:49Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
335,400
<p>Declarative is not necessarily more (or less) pythonic than functional IMHO. I think a layered approach would be the best (from buttom up):</p> <ol> <li>A native layer that accepts and returns python data types.</li> <li>A functional dynamic layer.</li> <li>One or more declarative/object-oriented layers.</li> </ol> <p>Similar to <a href="http://elixir.ematia.de/trac/wiki" rel="nofollow">Elixir</a> + <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>.</p>
1
2008-12-02T20:48:23Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
335,443
<p>Personally, I would try to implement <a href="http://docs.jquery.com/Main_Page" rel="nofollow">JQuery</a> like API in a GUI framework.</p> <pre><code>class MyWindow(Window): contents = ( para('Hello World!'), button('Click Me', id='ok'), para('Epilog'), ) def __init__(self): self['#ok'].click(self.message) self['para'].hover(self.blend_in, self.blend_out) def message(self): print 'You clicked!' def blend_in(self, object): object.background = '#333333' def blend_out(self, object): object.background = 'WindowBackground' </code></pre>
1
2008-12-02T21:03:49Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
335,887
<p>This is extremely contrived and not pythonic at all, but here's my attempt at a semi-literal translation using the new "with" statement.</p> <pre><code>with Shoes(): t = Para("Not clicked!") with Button("The Label"): Alert("You clicked the button!") t.replace("Clicked!") </code></pre> <p>The hardest part is dealing with the fact that python will not give us anonymous functions with more than one statement in them. To get around that, we could create a list of commands and run through those...</p> <p>Anyway, here's the backend code I ran this with:</p> <pre><code>context = None class Nestable(object): def __init__(self,caption=None): self.caption = caption self.things = [] global context if context: context.add(self) def __enter__(self): global context self.parent = context context = self def __exit__(self, type, value, traceback): global context context = self.parent def add(self,thing): self.things.append(thing) print "Adding a %s to %s" % (thing,self) def __str__(self): return "%s(%s)" % (self.__class__.__name__, self.caption) class Shoes(Nestable): pass class Button(Nestable): pass class Alert(Nestable): pass class Para(Nestable): def replace(self,caption): Command(self,"replace",caption) class Command(Nestable): def __init__(self, target, command, caption): self.command = command self.target = target Nestable.__init__(self,caption) def __str__(self): return "Command(%s text of %s with \"%s\")" % (self.command, self.target, self.caption) def execute(self): self.target.caption = self.caption </code></pre>
4
2008-12-03T00:15:11Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
336,089
<p>Here's an approach that goes about GUI definitions a bit differently using class-based meta-programming rather than inheritance.</p> <p>This is largley Django/SQLAlchemy inspired in that it is heavily based on meta-programming and separates your GUI code from your "code code". I also think it should make heavy use of layout managers like Java does because when you're dropping code, no one wants to constantly tweak pixel alignment. I also think it would be cool if we could have CSS-like properties.</p> <p>Here is a rough brainstormed example that will show a column with a label on top, then a text box, then a button to click on the bottom which shows a message.</p> <pre> from happygui.controls import * MAIN_WINDOW = Window(width="500px", height="350px", my_layout=ColumnLayout(padding="10px", my_label=Label(text="What's your name kiddo?", bold=True, align="center"), my_edit=EditBox(placeholder=""), my_btn=Button(text="CLICK ME!", on_click=Handler('module.file.btn_clicked')), ), ) MAIN_WINDOW.show() def btn_clicked(sender): # could easily be in a handlers.py file name = MAIN_WINDOW.my_layout.my_edit.text # same thing: name = sender.parent.my_edit.text # best practice, immune to structure change: MAIN_WINDOW.find('my_edit').text MessageBox("Your name is '%s'" % ()).show(modal=True) </pre> <p>One cool thing to notice is the way you can reference the input of my_edit by saying <code>MAIN_WINDOW.my_layout.my_edit.text</code>. In the declaration for the window, I think it's important to be able to arbitrarily name controls in the function kwargs.</p> <p>Here is the same app only using absolute positioning (the controls will appear in different places because we're not using a fancy layout manager):</p> <pre> from happygui.controls import * MAIN_WINDOW = Window(width="500px", height="350px", my_label=Label(text="What's your name kiddo?", bold=True, align="center", x="10px", y="10px", width="300px", height="100px"), my_edit=EditBox(placeholder="", x="10px", y="110px", width="300px", height="100px"), my_btn=Button(text="CLICK ME!", on_click=Handler('module.file.btn_clicked'), x="10px", y="210px", width="300px", height="100px"), ) MAIN_WINDOW.show() def btn_clicked(sender): # could easily be in a handlers.py file name = MAIN_WINDOW.my_edit.text # same thing: name = sender.parent.my_edit.text # best practice, immune to structure change: MAIN_WINDOW.find('my_edit').text MessageBox("Your name is '%s'" % ()).show(modal=True) </pre> <p>I'm not entirely sure yet if this is a super great approach, but I definitely think it's on the right path. I don't have time to explore this idea more, but if someone took this up as a project, I would love them.</p>
1
2008-12-03T02:37:06Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
336,525
<pre><code>## All you need is this class: class MainWindow(Window): my_button = Button('Click Me') my_paragraph = Text('This is the text you wish to place') my_alert = AlertBox('What what what!!!') @my_button.clicked def my_button_clicked(self, button, event): self.my_paragraph.text.append('And now you clicked on it, the button that is.') @my_paragraph.text.changed def my_paragraph_text_changed(self, text, event): self.button.text = 'No more clicks!' @my_button.text.changed def my_button_text_changed(self, text, event): self.my_alert.show() ## The Style class is automatically gnerated by the framework ## but you can override it by defining it in the class: ## ## class MainWindow(Window): ## class Style: ## my_blah = {'style-info': 'value'} ## ## or like you see below: class Style: my_button = { 'background-color': '#ccc', 'font-size': '14px'} my_paragraph = { 'background-color': '#fff', 'color': '#000', 'font-size': '14px', 'border': '1px solid black', 'border-radius': '3px'} MainWindow.Style = Style ## The layout class is automatically generated ## by the framework but you can override it by defining it ## in the class, same as the Style class above, or by ## defining it like this: class MainLayout(Layout): def __init__(self, style): # It takes the custom or automatically generated style class upon instantiation style.window.pack(HBox().pack(style.my_paragraph, style.my_button)) MainWindow.Layout = MainLayout if __name__ == '__main__': run(App(main=MainWindow)) </code></pre> <p>It would be relatively easy to do in python with a bit of that metaclass python magic know how. Which I have. And a knowledge of PyGTK. Which I also have. Gets ideas?</p>
5
2008-12-03T08:48:06Z
[ "python", "user-interface", "frameworks" ]
How would you design a very "Pythonic" UI framework?
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
11
2008-09-12T11:18:04Z
336,583
<p>If you use <a href="http://www.pygtk.org/" rel="nofollow">PyGTK</a> with <a href="http://glade.gnome.org/" rel="nofollow">glade</a> and <a href="http://www.pixelbeat.org/libs/libglade.py" rel="nofollow">this glade wrapper</a>, then PyGTK actually becomes somewhat pythonic. A little at least.</p> <p>Basically, you create the GUI layout in Glade. You also specify event callbacks in glade. Then you write a class for your window like this:</p> <pre><code>class MyWindow(GladeWrapper): GladeWrapper.__init__(self, "my_glade_file.xml", "mainWindow") self.GtkWindow.show() def button_click_event (self, *args): self.button1.set_label("CLICKED") </code></pre> <p>Here, I'm assuming that I have a GTK Button somewhere called <em>button1</em> and that I specified *button_click_event* as the <em>clicked</em> callback. The glade wrapper takes a lot of effort out of event mapping.</p> <p>If I were to design a Pythonic GUI library, I would support something similar, to aid rapid development. The only difference is that I would ensure that the widgets have a more pythonic interface too. The current PyGTK classes seem very C to me, except that I use foo.bar(...) instead of bar(foo, ...) though I'm not sure exactly what I'd do differently. Probably allow for a Django models style declarative means of specifying widgets and events in code and allowing you to access data though iterators (where it makes sense, eg widget lists perhaps), though I haven't really thought about it.</p>
3
2008-12-03T09:18:40Z
[ "python", "user-interface", "frameworks" ]
Storing multiple arrays in Python
59,648
<p>I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: www.gallup.com and www.rassmussenreports.com</p> <p>I'm using a brute force method, where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers. (Most companies poll numbers are three day averages)</p> <p>Currently, it works well for one iteration, but my goal is to have it produce the most common simulation that matches the average polling data. I could then change the code of anywhere from 1 to 1000 iterations. </p> <p>And this is my problem. At the end of the test I have an array in a single variable that looks something like this:</p> <pre><code>[40.1, 39.4, 56.7, 60.0, 20.0 ..... 19.0] </code></pre> <p>The program currently produces one array for each correct simulation. <em>I can store each array in a single variable, but I then have to have a program that could generate 1 to 1000 variables depending on how many iterations I requested!?</em> </p> <p>How do I avoid this? I know there is an intelligent way of doing this that doesn't require the program to generate variables to store arrays depending on how many simulations I want.</p> <p>Code testing for McCain:</p> <pre><code> test = [] while x &lt; 5: test = round(100*random.random()) mctest.append(test) x = x +1 mctestavg = (mctest[0] + mctest[1] + mctest[2])/3 #mcavg is real data if mctestavg == mcavg[2]: mcwork = mctest </code></pre> <p>How do I repeat without creating multiple mcwork vars?</p>
1
2008-09-12T18:09:02Z
59,662
<p>Are you talking about doing this?</p> <pre><code>&gt;&gt;&gt; a = [ ['a', 'b'], ['c', 'd'] ] &gt;&gt;&gt; a[1] ['c', 'd'] &gt;&gt;&gt; a[1][1] 'd' </code></pre>
2
2008-09-12T18:14:01Z
[ "python", "arrays" ]
Storing multiple arrays in Python
59,648
<p>I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: www.gallup.com and www.rassmussenreports.com</p> <p>I'm using a brute force method, where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers. (Most companies poll numbers are three day averages)</p> <p>Currently, it works well for one iteration, but my goal is to have it produce the most common simulation that matches the average polling data. I could then change the code of anywhere from 1 to 1000 iterations. </p> <p>And this is my problem. At the end of the test I have an array in a single variable that looks something like this:</p> <pre><code>[40.1, 39.4, 56.7, 60.0, 20.0 ..... 19.0] </code></pre> <p>The program currently produces one array for each correct simulation. <em>I can store each array in a single variable, but I then have to have a program that could generate 1 to 1000 variables depending on how many iterations I requested!?</em> </p> <p>How do I avoid this? I know there is an intelligent way of doing this that doesn't require the program to generate variables to store arrays depending on how many simulations I want.</p> <p>Code testing for McCain:</p> <pre><code> test = [] while x &lt; 5: test = round(100*random.random()) mctest.append(test) x = x +1 mctestavg = (mctest[0] + mctest[1] + mctest[2])/3 #mcavg is real data if mctestavg == mcavg[2]: mcwork = mctest </code></pre> <p>How do I repeat without creating multiple mcwork vars?</p>
1
2008-09-12T18:09:02Z
59,663
<p>Lists in python can contain any type of object -- If I understand the question correctly, will a <code>list</code> of <code>list</code>s do the job? Something like this (assuming you have a function <code>generate_poll_data()</code> which creates your data:</p> <pre><code>data = [] for in xrange(num_iterations): data.append(generate_poll_data()) </code></pre> <p>Then, <code>data[n]</code> will be the list of data from the <code>(n-1)</code>th run.</p>
1
2008-09-12T18:14:04Z
[ "python", "arrays" ]
Storing multiple arrays in Python
59,648
<p>I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: www.gallup.com and www.rassmussenreports.com</p> <p>I'm using a brute force method, where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers. (Most companies poll numbers are three day averages)</p> <p>Currently, it works well for one iteration, but my goal is to have it produce the most common simulation that matches the average polling data. I could then change the code of anywhere from 1 to 1000 iterations. </p> <p>And this is my problem. At the end of the test I have an array in a single variable that looks something like this:</p> <pre><code>[40.1, 39.4, 56.7, 60.0, 20.0 ..... 19.0] </code></pre> <p>The program currently produces one array for each correct simulation. <em>I can store each array in a single variable, but I then have to have a program that could generate 1 to 1000 variables depending on how many iterations I requested!?</em> </p> <p>How do I avoid this? I know there is an intelligent way of doing this that doesn't require the program to generate variables to store arrays depending on how many simulations I want.</p> <p>Code testing for McCain:</p> <pre><code> test = [] while x &lt; 5: test = round(100*random.random()) mctest.append(test) x = x +1 mctestavg = (mctest[0] + mctest[1] + mctest[2])/3 #mcavg is real data if mctestavg == mcavg[2]: mcwork = mctest </code></pre> <p>How do I repeat without creating multiple mcwork vars?</p>
1
2008-09-12T18:09:02Z
59,709
<p>since you are thinking in <em>variables</em>, you might prefer a dictionary over a list of lists:</p> <pre><code>data = {} data['a'] = [generate_poll_data()] data['b'] = [generate_poll_data()] </code></pre> <p>etc.</p>
1
2008-09-12T18:31:04Z
[ "python", "arrays" ]