title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Multiprocessing or Multithreading?
731,993
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p> <p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p> <p>Should I use multiple processes or multiple threads or what? People told me to use the <code>multiprocessing</code> package, I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information (and I think my program will need to share a lot of information.) Additionally I also heard about Stackless Python: Is it a separate option? I have no idea.</p> <p>Please advise.</p>
24
2009-04-08T21:44:44Z
732,199
<p>A process has its own memory space. It makes it more difficult to share information, but also makes the program safer (less need for explicit synchronization). That being said, processes can share the same memory in read-only mode. </p> <p>A thread is cheaper to create or kill, but the main difference is that it shares memory with other threads in the same process. This is sometimes risky, and in addition crashing the process would kill all threads.</p> <p>One advantage of using multiple processes over multiple threads is that it would be easier to scale your program to work with multiple machines that communicate via network protocols. </p> <p>For example, you could potentially run 16 processes on 8 dual-core machines, but would not have a benefit from more than 4 threads on a quad-core machine. If the amount of information you need to communicate is low, multiprocessing may make more sense. </p> <p>As for the youtube-style you've described, I would say that suggests multiprocessing. If you follow MVC approaches, your GUI should not also contain the model (calculation result). With multiprocess, you can then communicate to a work manager that can report what data is already available.</p>
10
2009-04-08T22:48:35Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
Multiprocessing or Multithreading?
731,993
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p> <p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p> <p>Should I use multiple processes or multiple threads or what? People told me to use the <code>multiprocessing</code> package, I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information (and I think my program will need to share a lot of information.) Additionally I also heard about Stackless Python: Is it a separate option? I have no idea.</p> <p>Please advise.</p>
24
2009-04-08T21:44:44Z
732,462
<p>There was a good talk on multiprocessing at Pycon this year. The takeaway message was "Only use multiprocessing unless you're sure you have a problem that it will solve, that cannot be solved with threads; otherwise, use threads." </p> <p>Processes have a lot of overhead, and all data to be shared among processes must be serializable (ie pickleable). </p> <p>You can see the slides and video here: <a href="http://blip.tv/pycon-us-videos-2009-2010-2011/introduction-to-multiprocessing-in-python-1957019" rel="nofollow">http://blip.tv/pycon-us-videos-2009-2010-2011/introduction-to-multiprocessing-in-python-1957019</a></p> <p><s>http://us.pycon.org/2009/conference/schedule/event/31/</s></p>
14
2009-04-09T01:21:33Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
Multiprocessing or Multithreading?
731,993
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p> <p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p> <p>Should I use multiple processes or multiple threads or what? People told me to use the <code>multiprocessing</code> package, I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information (and I think my program will need to share a lot of information.) Additionally I also heard about Stackless Python: Is it a separate option? I have no idea.</p> <p>Please advise.</p>
24
2009-04-08T21:44:44Z
734,919
<p>It sounds like you'd want threading. </p> <p>The way you described it, it sounded like there was one single thing that actually took a lot of CPU...the actual running of the simulation. </p> <p>What you're trying to get is more responsive displays, by allowing user interaction and graphics updates while the simulation is running. This is exactly what python's threading was built for. </p> <p>What this will NOT get you is the ability to take advantage of multiple cores/processors on your system. I have no idea what your simulation looks like, but if it is that CPU intensive, it might be a good candidate for splitting up. In this case, you can use multiprocessing to run separate parts of the simulation on separate cores/processors. However, this isn't trivial...you now need some way to pass data back and fourth between the processes, as the separate processes can't easily access the same memory space.</p>
0
2009-04-09T16:17:00Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
Multiprocessing or Multithreading?
731,993
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p> <p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p> <p>Should I use multiple processes or multiple threads or what? People told me to use the <code>multiprocessing</code> package, I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information (and I think my program will need to share a lot of information.) Additionally I also heard about Stackless Python: Is it a separate option? I have no idea.</p> <p>Please advise.</p>
24
2009-04-08T21:44:44Z
748,397
<p>If you would like to read a lengthy discussion of multi-threading in Mozilla, consider having a look at <a href="https://bugzilla.mozilla.org/show%5Fbug.cgi?id=40848" rel="nofollow">this discussion</a> which started in 2000. The discussion doesn't necessarily answer your question. However, it's an indepth discussion that I believe is interesting and informative, which I suggest may be quite valuable because you've asked a difficult question. Hopefully it'll help you make an informed decision.</p> <p>Incidentally, several members of the Mozilla project (notably Brendan Eich, Mozilla's CTO and the creator of JavaScript) were quite critical of multi-threading in particular. Some of the material referenced <a href="http://weblogs.mozillazine.org/roadmap/archives/2007/02/threads%5Fsuck.html" rel="nofollow">here</a>, <a href="http://weblogs.mozillazine.org/roc/archives/2005/12/night%5Fof%5Fthe%5Fliving%5Fthreads.html" rel="nofollow">here</a>, <a href="http://weblogs.mozillazine.org/roc/archives/2006/12/parallelism%5F1.html" rel="nofollow">here</a>, and <a href="http://weblogs.mozillazine.org/roc/archives/2007/05/performance%5Fobs.html" rel="nofollow">here</a> supports such a conclusion.</p> <p>Hope that helps and good luck.</p>
4
2009-04-14T16:35:01Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
Multiprocessing or Multithreading?
731,993
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p> <p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p> <p>Should I use multiple processes or multiple threads or what? People told me to use the <code>multiprocessing</code> package, I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information (and I think my program will need to share a lot of information.) Additionally I also heard about Stackless Python: Is it a separate option? I have no idea.</p> <p>Please advise.</p>
24
2009-04-08T21:44:44Z
35,972,455
<p>Very puzzled. Bastien Léonard rightly pointed out that the GIL will stop any ability to use threading in any useful way. His reference states:</p> <blockquote> <p>"Use of a global interpreter lock in a language effectively limits the amount of parallelism reachable through concurrency of a single interpreter process with multiple threads. If the process is almost purely made up of interpreted code and does not make calls outside of the interpreter for long periods of time (which can release the lock on the GIL on that thread while it processes), there is likely to be very little increase in speed when running the process on a multiprocessor machine. Due to signaling with a CPU-bound thread, it can cause a significant slowdown, even on single processors."</p> </blockquote> <p>This being the case, multi-processing is then the sensible choice. From my own experience Python + MT is of no noticeable benefit to the user. </p>
0
2016-03-13T16:01:39Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
Serving static files with mod_wsgi and Django
732,190
<p>I have a django application using mod_python, fairly typical configuration except that media files are being served by a (I know, not recommended) 'media' directory in the document root. I would like to test and maybe deploy with mod_wsgi but I cannot figure out how to create something simple to serve static files. mod_python allows the use of Apache directives like:</p> <pre><code>&lt;Location '/'&gt; SetHandler MyApplication.xyz..... &lt;/Location&gt; &lt;Location '/media'&gt; SetHandler None &lt;/Location&gt; </code></pre> <p>The django docs seem to point to the second block above as the correct way to make a similar exception for mod_wsgi, but in my tests everything below root is still being sent to the wsgi app. Is there a good way set a static media directory with mod_wsgi, or is what I am trying to do intentionally unsupported for compelling technical reasons? Answers that point to entirely different approaches are welcome.</p>
8
2009-04-08T22:47:16Z
732,692
<p>I run a a dozen or so Django sites on the same server and here's how I configure the media URL's.</p> <p>Each VirtualHost has the following configuration:</p> <pre><code>Alias /media /path/to/media/ &lt;Directory /path/to/media&gt; Include /etc/apache2/vhosts.d/media.include &lt;/Directory&gt; </code></pre> <p>This way I can make any changes to the media handling in one file.</p> <p>Then, my media.include file looks like this:</p> <pre><code>Order allow,deny Allow from all SetHandler None FileETag none Options FollowSymLinks &lt;IfModule mod_expires.c&gt; ExpiresActive On ExpiresByType image/gif "access plus 30 days" ExpiresByType image/jpg "access plus 30 days" ExpiresByType image/png "access plus 30 days" ExpiresByType image/jpeg "access plus 30 days" ExpiresByType text/css "access plus 30 days" ExpiresByType application/x-javascript "modification plus 2 years" &lt;/IfModule&gt; &lt;IfModule mod_headers.c&gt; Header append Vary Accept-Encoding &lt;/IfModule&gt; AddOutputFilterByType DEFLATE text/html text/css text/plain </code></pre> <p>This has worked very well for me, and gets an <strong>A</strong> grade from <a href="https://addons.mozilla.org/en-US/firefox/addon/5369">YSlow</a> (also see <a href="http://www.codinghorror.com/blog/archives/000932.html">Jeff Atwood on YSlow</a>).</p> <p>Also note, for the root dir I use the following configuration:</p> <pre><code>WSGIScriptAlias / /path/to/app.wsgi &lt;Directory /path/to&gt; Options +ExecCGI Allow from all &lt;/Directory&gt; </code></pre> <p>... which should be <strong>after</strong> the Alias /media in your configuration file (because Apache looks at the aliases in order)</p>
16
2009-04-09T03:42:00Z
[ "python", "django", "mod-wsgi", "mod-python" ]
Serving static files with mod_wsgi and Django
732,190
<p>I have a django application using mod_python, fairly typical configuration except that media files are being served by a (I know, not recommended) 'media' directory in the document root. I would like to test and maybe deploy with mod_wsgi but I cannot figure out how to create something simple to serve static files. mod_python allows the use of Apache directives like:</p> <pre><code>&lt;Location '/'&gt; SetHandler MyApplication.xyz..... &lt;/Location&gt; &lt;Location '/media'&gt; SetHandler None &lt;/Location&gt; </code></pre> <p>The django docs seem to point to the second block above as the correct way to make a similar exception for mod_wsgi, but in my tests everything below root is still being sent to the wsgi app. Is there a good way set a static media directory with mod_wsgi, or is what I am trying to do intentionally unsupported for compelling technical reasons? Answers that point to entirely different approaches are welcome.</p>
8
2009-04-08T22:47:16Z
1,037,869
<p>The mod_wsgi documentation explains how to setup static files which appear at a URL underneath that which the WSGI application is mounted at. See:</p> <p><a href="http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#Hosting%5FOf%5FStatic%5FFiles">http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#Hosting_Of_Static_Files</a></p> <p>Note that 'Options +ExecCGI' is not need when using WSGIScriptAlias directive to mount the WSGI application. The 'ExecCGI' option is only required when using AddHandler to mount applications as resources.</p>
13
2009-06-24T11:50:44Z
[ "python", "django", "mod-wsgi", "mod-python" ]
Get Tk winfo_rgb() without having a window instantiated
732,192
<p>I know I can call Tkinter.Tk().winfo_rgb(color) to get a tuple of values that represent the named color.</p> <p>for instance Tkinter.Tk().winfo_rgb("red") returns (65535, 0, 0)</p> <p>The problem is it also opens a window. I was hoping to abstract some color calculations into a generic color class, and handle whether or not the class was instantiated with "red" or "#ff0000" or maybe even some other formats.</p> <p>With the class abstracted, I don't have a tk parent to pull this info from without instantiating a new window, or passing in a parent.</p> <p>Is there any way to get this kind of colorname to hex value conversion without having an instantiated Tk window?</p>
2
2009-04-08T22:47:25Z
732,229
<p>You should look at the PIL (Python Imaging Library), and in particular the <a href="http://www.pythonware.com/library/pil/handbook/imagedraw.htm" rel="nofollow">ImageDraw module</a>, which support Hex, RGB, HSL and common color names. You should be able to get the information you need there.</p>
0
2009-04-08T23:04:30Z
[ "python", "colors", "tkinter" ]
Get Tk winfo_rgb() without having a window instantiated
732,192
<p>I know I can call Tkinter.Tk().winfo_rgb(color) to get a tuple of values that represent the named color.</p> <p>for instance Tkinter.Tk().winfo_rgb("red") returns (65535, 0, 0)</p> <p>The problem is it also opens a window. I was hoping to abstract some color calculations into a generic color class, and handle whether or not the class was instantiated with "red" or "#ff0000" or maybe even some other formats.</p> <p>With the class abstracted, I don't have a tk parent to pull this info from without instantiating a new window, or passing in a parent.</p> <p>Is there any way to get this kind of colorname to hex value conversion without having an instantiated Tk window?</p>
2
2009-04-08T22:47:25Z
732,452
<p>Instantiate Tk(), run the code once, and then stick the information into your source as a dict literal?</p>
0
2009-04-09T01:05:56Z
[ "python", "colors", "tkinter" ]
Get Tk winfo_rgb() without having a window instantiated
732,192
<p>I know I can call Tkinter.Tk().winfo_rgb(color) to get a tuple of values that represent the named color.</p> <p>for instance Tkinter.Tk().winfo_rgb("red") returns (65535, 0, 0)</p> <p>The problem is it also opens a window. I was hoping to abstract some color calculations into a generic color class, and handle whether or not the class was instantiated with "red" or "#ff0000" or maybe even some other formats.</p> <p>With the class abstracted, I don't have a tk parent to pull this info from without instantiating a new window, or passing in a parent.</p> <p>Is there any way to get this kind of colorname to hex value conversion without having an instantiated Tk window?</p>
2
2009-04-08T22:47:25Z
12,434,606
<p>Both Tkinter and the Python Imaging Library say they use the X Window colour names, so if you can get Shane's suggestion of the ImageDraw module to work, that sounds best. I wasn't sure I could rely on ImageDraw being available, so I parsed the list from the <a href="http://www.tcl.tk/man/tcl8.5/TkCmd/colors.htm" rel="nofollow">Tk documentation</a> to declare a hash table for looking up the colours. I'm not sure why the names are mixed case in the documentation, but I used case-insensitive look ups.</p> <pre><code>color_map = { 'alice blue': '#F0F8FF', 'AliceBlue': '#F0F8FF', 'antique white': '#FAEBD7', 'AntiqueWhite': '#FAEBD7', 'AntiqueWhite1': '#FFEFDB', 'AntiqueWhite2': '#EEDFCC', 'AntiqueWhite3': '#CDC0B0', 'AntiqueWhite4': '#8B8378', 'aquamarine': '#7FFFD4', 'aquamarine1': '#7FFFD4', 'aquamarine2': '#76EEC6', 'aquamarine3': '#66CDAA', 'aquamarine4': '#458B74', 'azure': '#F0FFFF', 'azure1': '#F0FFFF', 'azure2': '#E0EEEE', 'azure3': '#C1CDCD', 'azure4': '#838B8B', 'beige': '#F5F5DC', 'bisque': '#FFE4C4', 'bisque1': '#FFE4C4', 'bisque2': '#EED5B7', 'bisque3': '#CDB79E', 'bisque4': '#8B7D6B', 'black': '#000000', 'blanched almond': '#FFEBCD', 'BlanchedAlmond': '#FFEBCD', 'blue': '#0000FF', 'blue violet': '#8A2BE2', 'blue1': '#0000FF', 'blue2': '#0000EE', 'blue3': '#0000CD', 'blue4': '#00008B', 'BlueViolet': '#8A2BE2', 'brown': '#A52A2A', 'brown1': '#FF4040', 'brown2': '#EE3B3B', 'brown3': '#CD3333', 'brown4': '#8B2323', 'burlywood': '#DEB887', 'burlywood1': '#FFD39B', 'burlywood2': '#EEC591', 'burlywood3': '#CDAA7D', 'burlywood4': '#8B7355', 'cadet blue': '#5F9EA0', 'CadetBlue': '#5F9EA0', 'CadetBlue1': '#98F5FF', 'CadetBlue2': '#8EE5EE', 'CadetBlue3': '#7AC5CD', 'CadetBlue4': '#53868B', 'chartreuse': '#7FFF00', 'chartreuse1': '#7FFF00', 'chartreuse2': '#76EE00', 'chartreuse3': '#66CD00', 'chartreuse4': '#458B00', 'chocolate': '#D2691E', 'chocolate1': '#FF7F24', 'chocolate2': '#EE7621', 'chocolate3': '#CD661D', 'chocolate4': '#8B4513', 'coral': '#FF7F50', 'coral1': '#FF7256', 'coral2': '#EE6A50', 'coral3': '#CD5B45', 'coral4': '#8B3E2F', 'cornflower blue': '#6495ED', 'CornflowerBlue': '#6495ED', 'cornsilk': '#FFF8DC', 'cornsilk1': '#FFF8DC', 'cornsilk2': '#EEE8CD', 'cornsilk3': '#CDC8B1', 'cornsilk4': '#8B8878', 'cyan': '#00FFFF', 'cyan1': '#00FFFF', 'cyan2': '#00EEEE', 'cyan3': '#00CDCD', 'cyan4': '#008B8B', 'dark blue': '#00008B', 'dark cyan': '#008B8B', 'dark goldenrod': '#B8860B', 'dark gray': '#A9A9A9', 'dark green': '#006400', 'dark grey': '#A9A9A9', 'dark khaki': '#BDB76B', 'dark magenta': '#8B008B', 'dark olive green': '#556B2F', 'dark orange': '#FF8C00', 'dark orchid': '#9932CC', 'dark red': '#8B0000', 'dark salmon': '#E9967A', 'dark sea green': '#8FBC8F', 'dark slate blue': '#483D8B', 'dark slate gray': '#2F4F4F', 'dark slate grey': '#2F4F4F', 'dark turquoise': '#00CED1', 'dark violet': '#9400D3', 'DarkBlue': '#00008B', 'DarkCyan': '#008B8B', 'DarkGoldenrod': '#B8860B', 'DarkGoldenrod1': '#FFB90F', 'DarkGoldenrod2': '#EEAD0E', 'DarkGoldenrod3': '#CD950C', 'DarkGoldenrod4': '#8B6508', 'DarkGray': '#A9A9A9', 'DarkGreen': '#006400', 'DarkGrey': '#A9A9A9', 'DarkKhaki': '#BDB76B', 'DarkMagenta': '#8B008B', 'DarkOliveGreen': '#556B2F', 'DarkOliveGreen1': '#CAFF70', 'DarkOliveGreen2': '#BCEE68', 'DarkOliveGreen3': '#A2CD5A', 'DarkOliveGreen4': '#6E8B3D', 'DarkOrange': '#FF8C00', 'DarkOrange1': '#FF7F00', 'DarkOrange2': '#EE7600', 'DarkOrange3': '#CD6600', 'DarkOrange4': '#8B4500', 'DarkOrchid': '#9932CC', 'DarkOrchid1': '#BF3EFF', 'DarkOrchid2': '#B23AEE', 'DarkOrchid3': '#9A32CD', 'DarkOrchid4': '#68228B', 'DarkRed': '#8B0000', 'DarkSalmon': '#E9967A', 'DarkSeaGreen': '#8FBC8F', 'DarkSeaGreen1': '#C1FFC1', 'DarkSeaGreen2': '#B4EEB4', 'DarkSeaGreen3': '#9BCD9B', 'DarkSeaGreen4': '#698B69', 'DarkSlateBlue': '#483D8B', 'DarkSlateGray': '#2F4F4F', 'DarkSlateGray1': '#97FFFF', 'DarkSlateGray2': '#8DEEEE', 'DarkSlateGray3': '#79CDCD', 'DarkSlateGray4': '#528B8B', 'DarkSlateGrey': '#2F4F4F', 'DarkTurquoise': '#00CED1', 'DarkViolet': '#9400D3', 'deep pink': '#FF1493', 'deep sky blue': '#00BFFF', 'DeepPink': '#FF1493', 'DeepPink1': '#FF1493', 'DeepPink2': '#EE1289', 'DeepPink3': '#CD1076', 'DeepPink4': '#8B0A50', 'DeepSkyBlue': '#00BFFF', 'DeepSkyBlue1': '#00BFFF', 'DeepSkyBlue2': '#00B2EE', 'DeepSkyBlue3': '#009ACD', 'DeepSkyBlue4': '#00688B', 'dim gray': '#696969', 'dim grey': '#696969', 'DimGray': '#696969', 'DimGrey': '#696969', 'dodger blue': '#1E90FF', 'DodgerBlue': '#1E90FF', 'DodgerBlue1': '#1E90FF', 'DodgerBlue2': '#1C86EE', 'DodgerBlue3': '#1874CD', 'DodgerBlue4': '#104E8B', 'firebrick': '#B22222', 'firebrick1': '#FF3030', 'firebrick2': '#EE2C2C', 'firebrick3': '#CD2626', 'firebrick4': '#8B1A1A', 'floral white': '#FFFAF0', 'FloralWhite': '#FFFAF0', 'forest green': '#228B22', 'ForestGreen': '#228B22', 'gainsboro': '#DCDCDC', 'ghost white': '#F8F8FF', 'GhostWhite': '#F8F8FF', 'gold': '#FFD700', 'gold1': '#FFD700', 'gold2': '#EEC900', 'gold3': '#CDAD00', 'gold4': '#8B7500', 'goldenrod': '#DAA520', 'goldenrod1': '#FFC125', 'goldenrod2': '#EEB422', 'goldenrod3': '#CD9B1D', 'goldenrod4': '#8B6914', 'gray': '#BEBEBE', 'gray0': '#000000', 'gray1': '#030303', 'gray2': '#050505', 'gray3': '#080808', 'gray4': '#0A0A0A', 'gray5': '#0D0D0D', 'gray6': '#0F0F0F', 'gray7': '#121212', 'gray8': '#141414', 'gray9': '#171717', 'gray10': '#1A1A1A', 'gray11': '#1C1C1C', 'gray12': '#1F1F1F', 'gray13': '#212121', 'gray14': '#242424', 'gray15': '#262626', 'gray16': '#292929', 'gray17': '#2B2B2B', 'gray18': '#2E2E2E', 'gray19': '#303030', 'gray20': '#333333', 'gray21': '#363636', 'gray22': '#383838', 'gray23': '#3B3B3B', 'gray24': '#3D3D3D', 'gray25': '#404040', 'gray26': '#424242', 'gray27': '#454545', 'gray28': '#474747', 'gray29': '#4A4A4A', 'gray30': '#4D4D4D', 'gray31': '#4F4F4F', 'gray32': '#525252', 'gray33': '#545454', 'gray34': '#575757', 'gray35': '#595959', 'gray36': '#5C5C5C', 'gray37': '#5E5E5E', 'gray38': '#616161', 'gray39': '#636363', 'gray40': '#666666', 'gray41': '#696969', 'gray42': '#6B6B6B', 'gray43': '#6E6E6E', 'gray44': '#707070', 'gray45': '#737373', 'gray46': '#757575', 'gray47': '#787878', 'gray48': '#7A7A7A', 'gray49': '#7D7D7D', 'gray50': '#7F7F7F', 'gray51': '#828282', 'gray52': '#858585', 'gray53': '#878787', 'gray54': '#8A8A8A', 'gray55': '#8C8C8C', 'gray56': '#8F8F8F', 'gray57': '#919191', 'gray58': '#949494', 'gray59': '#969696', 'gray60': '#999999', 'gray61': '#9C9C9C', 'gray62': '#9E9E9E', 'gray63': '#A1A1A1', 'gray64': '#A3A3A3', 'gray65': '#A6A6A6', 'gray66': '#A8A8A8', 'gray67': '#ABABAB', 'gray68': '#ADADAD', 'gray69': '#B0B0B0', 'gray70': '#B3B3B3', 'gray71': '#B5B5B5', 'gray72': '#B8B8B8', 'gray73': '#BABABA', 'gray74': '#BDBDBD', 'gray75': '#BFBFBF', 'gray76': '#C2C2C2', 'gray77': '#C4C4C4', 'gray78': '#C7C7C7', 'gray79': '#C9C9C9', 'gray80': '#CCCCCC', 'gray81': '#CFCFCF', 'gray82': '#D1D1D1', 'gray83': '#D4D4D4', 'gray84': '#D6D6D6', 'gray85': '#D9D9D9', 'gray86': '#DBDBDB', 'gray87': '#DEDEDE', 'gray88': '#E0E0E0', 'gray89': '#E3E3E3', 'gray90': '#E5E5E5', 'gray91': '#E8E8E8', 'gray92': '#EBEBEB', 'gray93': '#EDEDED', 'gray94': '#F0F0F0', 'gray95': '#F2F2F2', 'gray96': '#F5F5F5', 'gray97': '#F7F7F7', 'gray98': '#FAFAFA', 'gray99': '#FCFCFC', 'gray100': '#FFFFFF', 'green': '#00FF00', 'green yellow': '#ADFF2F', 'green1': '#00FF00', 'green2': '#00EE00', 'green3': '#00CD00', 'green4': '#008B00', 'GreenYellow': '#ADFF2F', 'grey': '#BEBEBE', 'grey0': '#000000', 'grey1': '#030303', 'grey2': '#050505', 'grey3': '#080808', 'grey4': '#0A0A0A', 'grey5': '#0D0D0D', 'grey6': '#0F0F0F', 'grey7': '#121212', 'grey8': '#141414', 'grey9': '#171717', 'grey10': '#1A1A1A', 'grey11': '#1C1C1C', 'grey12': '#1F1F1F', 'grey13': '#212121', 'grey14': '#242424', 'grey15': '#262626', 'grey16': '#292929', 'grey17': '#2B2B2B', 'grey18': '#2E2E2E', 'grey19': '#303030', 'grey20': '#333333', 'grey21': '#363636', 'grey22': '#383838', 'grey23': '#3B3B3B', 'grey24': '#3D3D3D', 'grey25': '#404040', 'grey26': '#424242', 'grey27': '#454545', 'grey28': '#474747', 'grey29': '#4A4A4A', 'grey30': '#4D4D4D', 'grey31': '#4F4F4F', 'grey32': '#525252', 'grey33': '#545454', 'grey34': '#575757', 'grey35': '#595959', 'grey36': '#5C5C5C', 'grey37': '#5E5E5E', 'grey38': '#616161', 'grey39': '#636363', 'grey40': '#666666', 'grey41': '#696969', 'grey42': '#6B6B6B', 'grey43': '#6E6E6E', 'grey44': '#707070', 'grey45': '#737373', 'grey46': '#757575', 'grey47': '#787878', 'grey48': '#7A7A7A', 'grey49': '#7D7D7D', 'grey50': '#7F7F7F', 'grey51': '#828282', 'grey52': '#858585', 'grey53': '#878787', 'grey54': '#8A8A8A', 'grey55': '#8C8C8C', 'grey56': '#8F8F8F', 'grey57': '#919191', 'grey58': '#949494', 'grey59': '#969696', 'grey60': '#999999', 'grey61': '#9C9C9C', 'grey62': '#9E9E9E', 'grey63': '#A1A1A1', 'grey64': '#A3A3A3', 'grey65': '#A6A6A6', 'grey66': '#A8A8A8', 'grey67': '#ABABAB', 'grey68': '#ADADAD', 'grey69': '#B0B0B0', 'grey70': '#B3B3B3', 'grey71': '#B5B5B5', 'grey72': '#B8B8B8', 'grey73': '#BABABA', 'grey74': '#BDBDBD', 'grey75': '#BFBFBF', 'grey76': '#C2C2C2', 'grey77': '#C4C4C4', 'grey78': '#C7C7C7', 'grey79': '#C9C9C9', 'grey80': '#CCCCCC', 'grey81': '#CFCFCF', 'grey82': '#D1D1D1', 'grey83': '#D4D4D4', 'grey84': '#D6D6D6', 'grey85': '#D9D9D9', 'grey86': '#DBDBDB', 'grey87': '#DEDEDE', 'grey88': '#E0E0E0', 'grey89': '#E3E3E3', 'grey90': '#E5E5E5', 'grey91': '#E8E8E8', 'grey92': '#EBEBEB', 'grey93': '#EDEDED', 'grey94': '#F0F0F0', 'grey95': '#F2F2F2', 'grey96': '#F5F5F5', 'grey97': '#F7F7F7', 'grey98': '#FAFAFA', 'grey99': '#FCFCFC', 'grey100': '#FFFFFF', 'honeydew': '#F0FFF0', 'honeydew1': '#F0FFF0', 'honeydew2': '#E0EEE0', 'honeydew3': '#C1CDC1', 'honeydew4': '#838B83', 'hot pink': '#FF69B4', 'HotPink': '#FF69B4', 'HotPink1': '#FF6EB4', 'HotPink2': '#EE6AA7', 'HotPink3': '#CD6090', 'HotPink4': '#8B3A62', 'indian red': '#CD5C5C', 'IndianRed': '#CD5C5C', 'IndianRed1': '#FF6A6A', 'IndianRed2': '#EE6363', 'IndianRed3': '#CD5555', 'IndianRed4': '#8B3A3A', 'ivory': '#FFFFF0', 'ivory1': '#FFFFF0', 'ivory2': '#EEEEE0', 'ivory3': '#CDCDC1', 'ivory4': '#8B8B83', 'khaki': '#F0E68C', 'khaki1': '#FFF68F', 'khaki2': '#EEE685', 'khaki3': '#CDC673', 'khaki4': '#8B864E', 'lavender': '#E6E6FA', 'lavender blush': '#FFF0F5', 'LavenderBlush': '#FFF0F5', 'LavenderBlush1': '#FFF0F5', 'LavenderBlush2': '#EEE0E5', 'LavenderBlush3': '#CDC1C5', 'LavenderBlush4': '#8B8386', 'lawn green': '#7CFC00', 'LawnGreen': '#7CFC00', 'lemon chiffon': '#FFFACD', 'LemonChiffon': '#FFFACD', 'LemonChiffon1': '#FFFACD', 'LemonChiffon2': '#EEE9BF', 'LemonChiffon3': '#CDC9A5', 'LemonChiffon4': '#8B8970', 'light blue': '#ADD8E6', 'light coral': '#F08080', 'light cyan': '#E0FFFF', 'light goldenrod': '#EEDD82', 'light goldenrod yellow': '#FAFAD2', 'light gray': '#D3D3D3', 'light green': '#90EE90', 'light grey': '#D3D3D3', 'light pink': '#FFB6C1', 'light salmon': '#FFA07A', 'light sea green': '#20B2AA', 'light sky blue': '#87CEFA', 'light slate blue': '#8470FF', 'light slate gray': '#778899', 'light slate grey': '#778899', 'light steel blue': '#B0C4DE', 'light yellow': '#FFFFE0', 'LightBlue': '#ADD8E6', 'LightBlue1': '#BFEFFF', 'LightBlue2': '#B2DFEE', 'LightBlue3': '#9AC0CD', 'LightBlue4': '#68838B', 'LightCoral': '#F08080', 'LightCyan': '#E0FFFF', 'LightCyan1': '#E0FFFF', 'LightCyan2': '#D1EEEE', 'LightCyan3': '#B4CDCD', 'LightCyan4': '#7A8B8B', 'LightGoldenrod': '#EEDD82', 'LightGoldenrod1': '#FFEC8B', 'LightGoldenrod2': '#EEDC82', 'LightGoldenrod3': '#CDBE70', 'LightGoldenrod4': '#8B814C', 'LightGoldenrodYellow': '#FAFAD2', 'LightGray': '#D3D3D3', 'LightGreen': '#90EE90', 'LightGrey': '#D3D3D3', 'LightPink': '#FFB6C1', 'LightPink1': '#FFAEB9', 'LightPink2': '#EEA2AD', 'LightPink3': '#CD8C95', 'LightPink4': '#8B5F65', 'LightSalmon': '#FFA07A', 'LightSalmon1': '#FFA07A', 'LightSalmon2': '#EE9572', 'LightSalmon3': '#CD8162', 'LightSalmon4': '#8B5742', 'LightSeaGreen': '#20B2AA', 'LightSkyBlue': '#87CEFA', 'LightSkyBlue1': '#B0E2FF', 'LightSkyBlue2': '#A4D3EE', 'LightSkyBlue3': '#8DB6CD', 'LightSkyBlue4': '#607B8B', 'LightSlateBlue': '#8470FF', 'LightSlateGray': '#778899', 'LightSlateGrey': '#778899', 'LightSteelBlue': '#B0C4DE', 'LightSteelBlue1': '#CAE1FF', 'LightSteelBlue2': '#BCD2EE', 'LightSteelBlue3': '#A2B5CD', 'LightSteelBlue4': '#6E7B8B', 'LightYellow': '#FFFFE0', 'LightYellow1': '#FFFFE0', 'LightYellow2': '#EEEED1', 'LightYellow3': '#CDCDB4', 'LightYellow4': '#8B8B7A', 'lime green': '#32CD32', 'LimeGreen': '#32CD32', 'linen': '#FAF0E6', 'magenta': '#FF00FF', 'magenta1': '#FF00FF', 'magenta2': '#EE00EE', 'magenta3': '#CD00CD', 'magenta4': '#8B008B', 'maroon': '#B03060', 'maroon1': '#FF34B3', 'maroon2': '#EE30A7', 'maroon3': '#CD2990', 'maroon4': '#8B1C62', 'medium aquamarine': '#66CDAA', 'medium blue': '#0000CD', 'medium orchid': '#BA55D3', 'medium purple': '#9370DB', 'medium sea green': '#3CB371', 'medium slate blue': '#7B68EE', 'medium spring green': '#00FA9A', 'medium turquoise': '#48D1CC', 'medium violet red': '#C71585', 'MediumAquamarine': '#66CDAA', 'MediumBlue': '#0000CD', 'MediumOrchid': '#BA55D3', 'MediumOrchid1': '#E066FF', 'MediumOrchid2': '#D15FEE', 'MediumOrchid3': '#B452CD', 'MediumOrchid4': '#7A378B', 'MediumPurple': '#9370DB', 'MediumPurple1': '#AB82FF', 'MediumPurple2': '#9F79EE', 'MediumPurple3': '#8968CD', 'MediumPurple4': '#5D478B', 'MediumSeaGreen': '#3CB371', 'MediumSlateBlue': '#7B68EE', 'MediumSpringGreen': '#00FA9A', 'MediumTurquoise': '#48D1CC', 'MediumVioletRed': '#C71585', 'midnight blue': '#191970', 'MidnightBlue': '#191970', 'mint cream': '#F5FFFA', 'MintCream': '#F5FFFA', 'misty rose': '#FFE4E1', 'MistyRose': '#FFE4E1', 'MistyRose1': '#FFE4E1', 'MistyRose2': '#EED5D2', 'MistyRose3': '#CDB7B5', 'MistyRose4': '#8B7D7B', 'moccasin': '#FFE4B5', 'navajo white': '#FFDEAD', 'NavajoWhite': '#FFDEAD', 'NavajoWhite1': '#FFDEAD', 'NavajoWhite2': '#EECFA1', 'NavajoWhite3': '#CDB38B', 'NavajoWhite4': '#8B795E', 'navy': '#000080', 'navy blue': '#000080', 'NavyBlue': '#000080', 'old lace': '#FDF5E6', 'OldLace': '#FDF5E6', 'olive drab': '#6B8E23', 'OliveDrab': '#6B8E23', 'OliveDrab1': '#C0FF3E', 'OliveDrab2': '#B3EE3A', 'OliveDrab3': '#9ACD32', 'OliveDrab4': '#698B22', 'orange': '#FFA500', 'orange red': '#FF4500', 'orange1': '#FFA500', 'orange2': '#EE9A00', 'orange3': '#CD8500', 'orange4': '#8B5A00', 'OrangeRed': '#FF4500', 'OrangeRed1': '#FF4500', 'OrangeRed2': '#EE4000', 'OrangeRed3': '#CD3700', 'OrangeRed4': '#8B2500', 'orchid': '#DA70D6', 'orchid1': '#FF83FA', 'orchid2': '#EE7AE9', 'orchid3': '#CD69C9', 'orchid4': '#8B4789', 'pale goldenrod': '#EEE8AA', 'pale green': '#98FB98', 'pale turquoise': '#AFEEEE', 'pale violet red': '#DB7093', 'PaleGoldenrod': '#EEE8AA', 'PaleGreen': '#98FB98', 'PaleGreen1': '#9AFF9A', 'PaleGreen2': '#90EE90', 'PaleGreen3': '#7CCD7C', 'PaleGreen4': '#548B54', 'PaleTurquoise': '#AFEEEE', 'PaleTurquoise1': '#BBFFFF', 'PaleTurquoise2': '#AEEEEE', 'PaleTurquoise3': '#96CDCD', 'PaleTurquoise4': '#668B8B', 'PaleVioletRed': '#DB7093', 'PaleVioletRed1': '#FF82AB', 'PaleVioletRed2': '#EE799F', 'PaleVioletRed3': '#CD687F', 'PaleVioletRed4': '#8B475D', 'papaya whip': '#FFEFD5', 'PapayaWhip': '#FFEFD5', 'peach puff': '#FFDAB9', 'PeachPuff': '#FFDAB9', 'PeachPuff1': '#FFDAB9', 'PeachPuff2': '#EECBAD', 'PeachPuff3': '#CDAF95', 'PeachPuff4': '#8B7765', 'peru': '#CD853F', 'pink': '#FFC0CB', 'pink1': '#FFB5C5', 'pink2': '#EEA9B8', 'pink3': '#CD919E', 'pink4': '#8B636C', 'plum': '#DDA0DD', 'plum1': '#FFBBFF', 'plum2': '#EEAEEE', 'plum3': '#CD96CD', 'plum4': '#8B668B', 'powder blue': '#B0E0E6', 'PowderBlue': '#B0E0E6', 'purple': '#A020F0', 'purple1': '#9B30FF', 'purple2': '#912CEE', 'purple3': '#7D26CD', 'purple4': '#551A8B', 'red': '#FF0000', 'red1': '#FF0000', 'red2': '#EE0000', 'red3': '#CD0000', 'red4': '#8B0000', 'rosy brown': '#BC8F8F', 'RosyBrown': '#BC8F8F', 'RosyBrown1': '#FFC1C1', 'RosyBrown2': '#EEB4B4', 'RosyBrown3': '#CD9B9B', 'RosyBrown4': '#8B6969', 'royal blue': '#4169E1', 'RoyalBlue': '#4169E1', 'RoyalBlue1': '#4876FF', 'RoyalBlue2': '#436EEE', 'RoyalBlue3': '#3A5FCD', 'RoyalBlue4': '#27408B', 'saddle brown': '#8B4513', 'SaddleBrown': '#8B4513', 'salmon': '#FA8072', 'salmon1': '#FF8C69', 'salmon2': '#EE8262', 'salmon3': '#CD7054', 'salmon4': '#8B4C39', 'sandy brown': '#F4A460', 'SandyBrown': '#F4A460', 'sea green': '#2E8B57', 'SeaGreen': '#2E8B57', 'SeaGreen1': '#54FF9F', 'SeaGreen2': '#4EEE94', 'SeaGreen3': '#43CD80', 'SeaGreen4': '#2E8B57', 'seashell': '#FFF5EE', 'seashell1': '#FFF5EE', 'seashell2': '#EEE5DE', 'seashell3': '#CDC5BF', 'seashell4': '#8B8682', 'sienna': '#A0522D', 'sienna1': '#FF8247', 'sienna2': '#EE7942', 'sienna3': '#CD6839', 'sienna4': '#8B4726', 'sky blue': '#87CEEB', 'SkyBlue': '#87CEEB', 'SkyBlue1': '#87CEFF', 'SkyBlue2': '#7EC0EE', 'SkyBlue3': '#6CA6CD', 'SkyBlue4': '#4A708B', 'slate blue': '#6A5ACD', 'slate gray': '#708090', 'slate grey': '#708090', 'SlateBlue': '#6A5ACD', 'SlateBlue1': '#836FFF', 'SlateBlue2': '#7A67EE', 'SlateBlue3': '#6959CD', 'SlateBlue4': '#473C8B', 'SlateGray': '#708090', 'SlateGray1': '#C6E2FF', 'SlateGray2': '#B9D3EE', 'SlateGray3': '#9FB6CD', 'SlateGray4': '#6C7B8B', 'SlateGrey': '#708090', 'snow': '#FFFAFA', 'snow1': '#FFFAFA', 'snow2': '#EEE9E9', 'snow3': '#CDC9C9', 'snow4': '#8B8989', 'spring green': '#00FF7F', 'SpringGreen': '#00FF7F', 'SpringGreen1': '#00FF7F', 'SpringGreen2': '#00EE76', 'SpringGreen3': '#00CD66', 'SpringGreen4': '#008B45', 'steel blue': '#4682B4', 'SteelBlue': '#4682B4', 'SteelBlue1': '#63B8FF', 'SteelBlue2': '#5CACEE', 'SteelBlue3': '#4F94CD', 'SteelBlue4': '#36648B', 'tan': '#D2B48C', 'tan1': '#FFA54F', 'tan2': '#EE9A49', 'tan3': '#CD853F', 'tan4': '#8B5A2B', 'thistle': '#D8BFD8', 'thistle1': '#FFE1FF', 'thistle2': '#EED2EE', 'thistle3': '#CDB5CD', 'thistle4': '#8B7B8B', 'tomato': '#FF6347', 'tomato1': '#FF6347', 'tomato2': '#EE5C42', 'tomato3': '#CD4F39', 'tomato4': '#8B3626', 'turquoise': '#40E0D0', 'turquoise1': '#00F5FF', 'turquoise2': '#00E5EE', 'turquoise3': '#00C5CD', 'turquoise4': '#00868B', 'violet': '#EE82EE', 'violet red': '#D02090', 'VioletRed': '#D02090', 'VioletRed1': '#FF3E96', 'VioletRed2': '#EE3A8C', 'VioletRed3': '#CD3278', 'VioletRed4': '#8B2252', 'wheat': '#F5DEB3', 'wheat1': '#FFE7BA', 'wheat2': '#EED8AE', 'wheat3': '#CDBA96', 'wheat4': '#8B7E66', 'white': '#FFFFFF', 'white smoke': '#F5F5F5', 'WhiteSmoke': '#F5F5F5', 'yellow': '#FFFF00', 'yellow green': '#9ACD32', 'yellow1': '#FFFF00', 'yellow2': '#EEEE00', 'yellow3': '#CDCD00', 'yellow4': '#8B8B00', 'YellowGreen': '#9ACD32', } </code></pre>
1
2012-09-15T04:50:27Z
[ "python", "colors", "tkinter" ]
Python HTTP server that supports chunked encoding?
732,222
<p>I'm looking for a well-supported multithreaded Python HTTP server that supports chunked encoding replies. (I.e. "Transfer-Encoding: chunked" on responses). What's the best HTTP server base to start with for this purpose?</p>
5
2009-04-08T22:58:19Z
732,257
<p>I am pretty sure that WSGI compliant servers should support that. Essentially, WSGI applications return iterable chunks, which the webserver returns. I don't have first hand experience with this, but here is a <a href="http://www.wsgi.org/wsgi/Servers" rel="nofollow">list of compliant servers</a>.</p> <p>I should think that it would be fairly easy to roll your own though, if WSGI servers dont meet what you are looking for, using the Python's builtin <a href="http://docs.python.org/library/cgihttpserver.html" rel="nofollow">CGIHTTPServer</a>. It is already multithreaded, so it would just be up to you to chunk the responses.</p>
0
2009-04-08T23:18:10Z
[ "python", "http", "chunked-encoding" ]
Python HTTP server that supports chunked encoding?
732,222
<p>I'm looking for a well-supported multithreaded Python HTTP server that supports chunked encoding replies. (I.e. "Transfer-Encoding: chunked" on responses). What's the best HTTP server base to start with for this purpose?</p>
5
2009-04-08T22:58:19Z
732,266
<p>Twisted supports <a href="http://twistedmatrix.com/documents/current/api/twisted.web.http.%5FChunkedTransferEncoding.html" rel="nofollow">chunked transfer encoding (API link)</a> (see also the API doc for <a href="http://twistedmatrix.com/documents/current/api/twisted.web.http.HTTPChannel.html" rel="nofollow">HTTPChannel</a>). There are a number of production-grade projects using Twisted (for example, Apple uses it for the iCalendar server in Mac OS X Server), so it's quite well supported and very robust. </p>
5
2009-04-08T23:22:39Z
[ "python", "http", "chunked-encoding" ]
Python HTTP server that supports chunked encoding?
732,222
<p>I'm looking for a well-supported multithreaded Python HTTP server that supports chunked encoding replies. (I.e. "Transfer-Encoding: chunked" on responses). What's the best HTTP server base to start with for this purpose?</p>
5
2009-04-08T22:58:19Z
9,326,192
<p>Twisted supports chunked transfer and it does so transparently. i.e., if your request handler does not specify a response length, twisted will automatically switch to chunked transfer and it will generate one chunk per call to Request.write.</p>
2
2012-02-17T10:00:40Z
[ "python", "http", "chunked-encoding" ]
Django Model: Returning username from currently logged in user
732,405
<p>I'm working on a Django app for hosting media (specifically audio and images). I have image galleries and photos separate in my model, and have them linked with a <code>ForeignKey</code> (not sure if that's correct, but still learning). What I need is for the Album class's <code>__unicode__</code> to return the album owner's username.</p> <pre><code>class Album(models.Model): artist = models.ForeignKey(User, unique=True, related_name='artpunk') def __unicode__(self): return self.artist.username </code></pre> <p>I know the username property exists, and confirmed it by inserting a <code>dir()</code> and checking the console output. The problem is when I enter the image section of the admin panel, it simply states "Unrecognised command." Can <code>User</code> properties not be accessed by models? Or am I doing something else wrong?</p> <p>EDIT: Forgot to mention, using Python 2.6 with Django 1.0.2. The exact text of the error is, as above, simply "Unrecognised command" in bold, and I've already run <code>syncdb</code> without issue. However, I reran <code>syncdb</code> (gave no output) this morning just to try again and now it seems to be working fine.</p> <p>It's reproducible by changing the following:</p> <pre><code> def __unicode__(self): return self.artist.username </code></pre> <p>To something like this:</p> <pre><code> def __unicode__(self): return self.artist.username+'\'s Gallery' </code></pre>
0
2009-04-09T00:39:06Z
732,683
<p>There should be no problem accessing the user (even as a foreign key) from a model. I just finished testing it out myself, and there doesn't appear to be any significant difference.</p> <pre><code>def __unicode__(self): return self.user.username </code></pre> <p>On a side note, you should also just be able to return self.artist, since I believe that <code>User.__unicode__()</code> returns the username anyway.</p> <p>What are the exact details of the error? What version of Django/Python are you using? Did you make a change to your model that's not yet reflected in the database? Sometimes I've noticed you just need to restart the test server for things to work well. Particularly in the admin.</p> <p>In response to your edit, try casting the username as a string:</p> <pre><code>str(self.user.username) </code></pre>
1
2009-04-09T03:36:27Z
[ "python", "django", "django-models", "django-admin" ]
HTML Rich Textbox
732,429
<p>I'm writing a web-app using Python and Pylons. I need a textbox that is rich (ie, provides the ability to bold/underline/add bullets..etc...). Does anyone know a library or widget I can use?</p> <p>It doesn't have to be Python/Pylons specific, as it can be a Javascript implementation as well.</p> <p>Thanks!</p>
4
2009-04-09T00:52:57Z
732,439
<p>There are several very mature javascript implementations that are server-framework agnostic:</p> <ul> <li><a href="http://www.fckeditor.net/">http://www.fckeditor.net/</a></li> <li><a href="http://tinymce.moxiecode.com/">TinyMCE</a></li> <li><a href="http://wmd-editor.com/">WMD</a> (used by SO)</li> </ul> <p>The wikipedia article on <a href="http://en.wikipedia.org/wiki/Category:Free%5FHTML%5Feditors">Free HTML editors</a> has a good overview, though note that not all are for application embedding.</p>
5
2009-04-09T00:59:43Z
[ "javascript", "python", "http", "pylons", "widget" ]
HTML Rich Textbox
732,429
<p>I'm writing a web-app using Python and Pylons. I need a textbox that is rich (ie, provides the ability to bold/underline/add bullets..etc...). Does anyone know a library or widget I can use?</p> <p>It doesn't have to be Python/Pylons specific, as it can be a Javascript implementation as well.</p> <p>Thanks!</p>
4
2009-04-09T00:52:57Z
732,441
<p>ExtJS's HtmlEditor was the best I found (license issues aside):</p> <p><a href="http://extjs.com/deploy/dev/docs/?class=Ext.form.HtmlEditor" rel="nofollow">http://extjs.com/deploy/dev/docs/?class=Ext.form.HtmlEditor</a></p> <p>ExtJS is a bit heavy-weight, but that HtmlEditor was the most responsive and best-looking out of the box that I found. It's worth running the output through HTMLTidy, which there are python libraries for.</p>
2
2009-04-09T01:02:24Z
[ "javascript", "python", "http", "pylons", "widget" ]
HTML Rich Textbox
732,429
<p>I'm writing a web-app using Python and Pylons. I need a textbox that is rich (ie, provides the ability to bold/underline/add bullets..etc...). Does anyone know a library or widget I can use?</p> <p>It doesn't have to be Python/Pylons specific, as it can be a Javascript implementation as well.</p> <p>Thanks!</p>
4
2009-04-09T00:52:57Z
732,453
<p>webkit-gtk is getting very stable, and i believe has python bindings now so technically you could use that (then your text editor merely needs to be <code>&lt;body contenteditable&gt;&lt;/body&gt;</code> and you'd be done. Unfortunately i'm not sure how complete its bindings are at present</p>
1
2009-04-09T01:06:35Z
[ "javascript", "python", "http", "pylons", "widget" ]
skip over HTML tags in Regular Expression patterns
732,465
<p>I'm trying to write a regular expression pattern (in python) for reformatting these template engine files.</p> <p>Basically the scheme looks like this:</p> <pre><code>[$$price$$] { &lt;h3 class="price"&gt; $12.99 &lt;/h3&gt; } </code></pre> <p>I'm trying to make it remove any extra tabs\spaces\new lines so it should look like this:</p> <pre><code>[$$price$$]{&lt;h3 class="price"&gt;$12.99&lt;/h3&gt;} </code></pre> <p>I wrote this: (\t|\s)+? which works except it matches within the html tags, so h3 becomes h3class and I am unable to figure out how to make it ignore anything inside the tags.</p>
0
2009-04-09T01:26:22Z
732,477
<p>Using regular expressions to deal with HTML is extremely error-prone; they're simply not the right tool.</p> <p>Instead, use a HTML/XML-aware library (such as <A HREF="http://codespeak.net/lxml/" rel="nofollow">lxml</A>) to build a DOM-style object tree; modify the text segments within the tree in-place, and generate your output again using said library.</p>
5
2009-04-09T01:33:31Z
[ "python", "regex" ]
skip over HTML tags in Regular Expression patterns
732,465
<p>I'm trying to write a regular expression pattern (in python) for reformatting these template engine files.</p> <p>Basically the scheme looks like this:</p> <pre><code>[$$price$$] { &lt;h3 class="price"&gt; $12.99 &lt;/h3&gt; } </code></pre> <p>I'm trying to make it remove any extra tabs\spaces\new lines so it should look like this:</p> <pre><code>[$$price$$]{&lt;h3 class="price"&gt;$12.99&lt;/h3&gt;} </code></pre> <p>I wrote this: (\t|\s)+? which works except it matches within the html tags, so h3 becomes h3class and I am unable to figure out how to make it ignore anything inside the tags.</p>
0
2009-04-09T01:26:22Z
732,482
<p>Try this:</p> <pre><code>\r?\n[ \t]* </code></pre> <p>EDIT: The idea is to remove all newlines (either Unix: "\n", or Windows: "\r\n") plus any horizontal whitespace (TABs or spaces) that immediately follow them.</p>
0
2009-04-09T01:36:59Z
[ "python", "regex" ]
skip over HTML tags in Regular Expression patterns
732,465
<p>I'm trying to write a regular expression pattern (in python) for reformatting these template engine files.</p> <p>Basically the scheme looks like this:</p> <pre><code>[$$price$$] { &lt;h3 class="price"&gt; $12.99 &lt;/h3&gt; } </code></pre> <p>I'm trying to make it remove any extra tabs\spaces\new lines so it should look like this:</p> <pre><code>[$$price$$]{&lt;h3 class="price"&gt;$12.99&lt;/h3&gt;} </code></pre> <p>I wrote this: (\t|\s)+? which works except it matches within the html tags, so h3 becomes h3class and I am unable to figure out how to make it ignore anything inside the tags.</p>
0
2009-04-09T01:26:22Z
932,863
<p>Alan,</p> <p>I have to agree with Charles that the safest way is to parse the HTML, then work on the Text nodes only. Sounds overkill but that's the safest.</p> <p>On the other hand, there is a way in regex to do that as long as you trust that the HTML code is correct (i.e. does not include invalid &lt; and > in the tags as in: &lt;a title="&lt;this is a test>" href="look here">...)</p> <p>Then, you know that any text has to be between > and &lt; except at the very beginning and end (if you just get a snapshot of the page, otherwise there is the HTML tag minimum.)</p> <p>So... You still need two regex's: find the text '>[^&lt;]+&lt;', then apply the other regex as you mentioned.</p> <p>The other way, is to have an or with something like this (not tested!):</p> <p>'(&lt;[^>]*>)|([\r\n\f ]+)'</p> <p>This will either find a tag or spaces. When you find a tag, do not replace, if you don't find a tag, replace with an empty string.</p>
0
2009-05-31T21:04:54Z
[ "python", "regex" ]
How do I make this progress bar close when it is done
732,829
<p>I commonly write Python scipts to do conversion tasks for me and whenever I write one that takes a while I use this little progress bar to check on it</p> <pre><code>import sys import time from PyQt4 import QtGui app = QtGui.QApplication(sys.argv) barra = QtGui.QProgressBar() barra.show() barra.setMinimum(0) barra.setMaximum(10) for a in range(10): time.sleep(1) barra.setValue(a) app.exec_() </code></pre> <p>I have 2 questions:</p> <p>How do I make it close itself when it reaches 100% (It stays open and if you close the python shell before clicking the X button you crash it.)</p> <p>also, When it loses and regains focus, it stops painting correctly. the process will continue to completion but the progress bar space is all white. How do I handle this?</p>
1
2009-04-09T04:42:59Z
734,139
<p>Well, because you set your Maximum to 10, your progress bar shouldn't reach 100% because </p> <pre><code>for a in range(10): time.sleep(1) barra.setValue(a) </code></pre> <p>will only iterate up to 9.</p> <p>Progress bars don't close automatically. You will have to call </p> <pre><code>barra.hide() </code></pre> <p>after your loop.</p> <p>As for the paint problem, it's likely because whatever script you ran this script from is in the same thread as the progress bar. So when you switch away and back the paint events are delayed by the actual processing of the parent script. You can either set a timer to periodically call .update() or .repaint() on 'barra' (update() is recommended over repaint()) <strong>OR</strong> you would want your main processing code to run in a QThread, which is also available in the PyQt code, but that will require some reading on your part :)</p> <p>The doc is for Qt, but it applies to PyQt as well:</p> <p><a href="http://doc.trolltech.com/4.4/threads.html" rel="nofollow">http://doc.trolltech.com/4.4/threads.html</a></p>
3
2009-04-09T13:06:58Z
[ "python", "pyqt", "progress-bar" ]
Get Primary Key after Saving a ModelForm in Django
732,952
<p>How do I get the primary key after saving a ModelForm? After the form has been validated and saved, I would like to redirect the user to the contact_details view which requires the primary key of the contact. </p> <pre><code>def contact_create(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(contact_details, args=(form.pk,))) else: form = ContactForm() </code></pre>
21
2009-04-09T05:38:47Z
732,973
<p>The <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelform">ModelForm</a>'s <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method">save</a> method returns the saved object.</p> <p>Try this:</p> <pre><code>def contact_create(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): new_contact = form.save() return HttpResponseRedirect(reverse(contact_details, args=(new_contact.pk,))) else: form = ContactForm() </code></pre>
31
2009-04-09T05:50:11Z
[ "python", "django", "django-models", "django-forms" ]
Get Primary Key after Saving a ModelForm in Django
732,952
<p>How do I get the primary key after saving a ModelForm? After the form has been validated and saved, I would like to redirect the user to the contact_details view which requires the primary key of the contact. </p> <pre><code>def contact_create(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(contact_details, args=(form.pk,))) else: form = ContactForm() </code></pre>
21
2009-04-09T05:38:47Z
6,247,910
<p>In the case where you have set form.save(commit=False) because you want to modify data and you have a many-to-many relation, then the answer is a little bit different:</p> <pre><code>def contact_create(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): new_contact = form.save(commit=False) new_contact.data1 = "gets modified" new_contact.save() form.save_m2m() return HttpResponseRedirect(reverse(contact_details, args=(new_contact.pk,))) else: form = ContactFrom() </code></pre> <p><a href="https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#the-save-method">https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#the-save-method</a></p>
6
2011-06-06T04:58:11Z
[ "python", "django", "django-models", "django-forms" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } </code></pre> <p>Is there a function that can do this?</p>
113
2009-04-09T09:15:33Z
733,461
<p>You most likely just need to format your integer:</p> <pre><code>'%0*d' % (fill, your_int) </code></pre> <p>For example,</p> <pre><code>&gt;&gt;&gt; '%0*d' % (3, 4) '004' </code></pre>
57
2009-04-09T09:16:59Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } </code></pre> <p>Is there a function that can do this?</p>
113
2009-04-09T09:15:33Z
733,478
<p>You can use the <code>zfill()</code> method to pad a string with zeros:</p> <pre><code>In [3]: str(1).zfill(2) Out[3]: '01' </code></pre>
288
2009-04-09T09:23:23Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } </code></pre> <p>Is there a function that can do this?</p>
113
2009-04-09T09:15:33Z
733,512
<p>This is my Python function:</p> <pre><code>def add_nulls(num, cnt=2): cnt = cnt - len(str(num)) nulls = '0' * cnt return '%s%s' % (nulls, num) </code></pre>
0
2009-04-09T09:36:21Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } </code></pre> <p>Is there a function that can do this?</p>
113
2009-04-09T09:15:33Z
733,525
<p>A straightforward conversion would be (again with a function):</p> <pre><code>def add_nulls2(int, cnt): nulls = str(int) for i in range(cnt - len(str(int))): nulls = '0' + nulls return nulls </code></pre>
1
2009-04-09T09:40:57Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } </code></pre> <p>Is there a function that can do this?</p>
113
2009-04-09T09:15:33Z
733,576
<p>Python 2.6 allows this:</p> <pre><code>add_nulls = lambda number, zero_count : "{0:0{1}d}".format(number, zero_count) &gt;&gt;&gt;add_nulls(2,3) '002' </code></pre>
16
2009-04-09T09:59:49Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } </code></pre> <p>Is there a function that can do this?</p>
113
2009-04-09T09:15:33Z
733,825
<p>You have at least two options:</p> <ul> <li>str.zfill: <code>lambda n, cnt=2: str(n).zfill(cnt)</code></li> <li><code>%</code> formatting: <code>lambda n, cnt=2: "%0*d" % (cnt, n)</code></li> </ul> <p>If on Python >2.5, see a third option in clorz's answer.</p>
4
2009-04-09T11:36:57Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } </code></pre> <p>Is there a function that can do this?</p>
113
2009-04-09T09:15:33Z
733,939
<p>Just for the culture, on PHP, you have the function <a href="http://fr3.php.net/str%5Fpad" rel="nofollow" title="str_pad"><code>str_pad</code></a> which makes exactly the job of your function <code>add_nulls</code>.</p> <pre><code>str_pad($int, $cnt, '0', STR_PAD_LEFT); </code></pre>
0
2009-04-09T12:07:24Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } </code></pre> <p>Is there a function that can do this?</p>
113
2009-04-09T09:15:33Z
12,098,091
<h3>One-liner alternative to the built-in <code>zfill</code>.</h3> <p>This function takes <code>x</code> and converts it to a string, and adds zeros in the beginning only and only if the length is too short:</p> <pre><code>def zfill_alternative(x,len=4): return ( (('0'*len)+str(x))[-l:] if len(str(x))&lt;len else str(x) ) </code></pre> <p>To sum it up - build-in: <code>zfill</code> is good enough, but if someone is curious on how to implement this by hand, here is one more example.</p>
1
2012-08-23T18:42:00Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } </code></pre> <p>Is there a function that can do this?</p>
113
2009-04-09T09:15:33Z
13,919,632
<p>The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.</p> <pre><code>i = random.randint(0,99999) print "%05d" % i </code></pre> <p>which will output an string of length 5.</p> <hr> <p>Edit: In Python2.6 and above, there is also:</p> <pre><code>print '{0:05d}'.format(i) </code></pre> <p>See: <a href="https://docs.python.org/2/library/string.html">https://docs.python.org/2/library/string.html</a></p>
104
2012-12-17T18:10:33Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } </code></pre> <p>Is there a function that can do this?</p>
113
2009-04-09T09:15:33Z
36,558,670
<p>For Python 3 and beyond: str.zfill() is still the most readable option</p> <p>But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?</p> <pre><code> # if we want to pad 22 with zeros in front, to be 5 digits in length: str_output = '{:0&gt;5}'.format(22) print(str_output) # &gt;&gt;&gt; 00022 # {:0&gt;5} meaning: ":0" means: pad with 0, "&gt;" means move 22 to right most, "5" means the total length is 5 # another example for comparision str_output = '{:#&lt;4}'.format(11) print(str_output) # &gt;&gt;&gt; 11## # to put it in a less hard-coded format: int_inputArg = 22 int_desiredLength = 5 str_output = '{str_0:0&gt;{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength) print(str_output) # &gt;&gt;&gt; 00022 </code></pre>
2
2016-04-11T20:30:23Z
[ "python", "string-formatting" ]
Best way to format integer as string with leading zeros?
733,454
<p>I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:</p> <pre><code>function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i&lt;($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } </code></pre> <p>Is there a function that can do this?</p>
113
2009-04-09T09:15:33Z
36,881,673
<p>Initially, find the digits in the number of Cases /Folders. According to the length of the maximum / highest number of Cases / Folder, a format is created and added as suffix. For example. No of Cases = 9. Case_1. Case_2...Case_9 are generated. For No of Cases = 99, Case_01, Case_02...Case_99.. for 999, Case_001, Case_002....Case_999 and so on. Hope it helps</p> <pre><code>NoOfCases = 9 #99 # 999 digits = len(str(NoOfCases)) if digits == 1: caseFolderformat = "Case_{0:&gt;"+str(digits)+"}" else: caseFolderformat = "Case_{0:0&gt;"+str(digits)+"}" count = 0 for i in range(NoOfCases): count = count + 1 print caseFolderformat.format(count) </code></pre>
-3
2016-04-27T06:12:06Z
[ "python", "string-formatting" ]
Access list of tuples
733,574
<p>I have a list that contains several tuples, like:</p> <pre><code>[('a_key', 'a value'), ('another_key', 'another value')] </code></pre> <p>where the first tuple-values act as dictionary-keys. I'm now searching for a python-like way to access the key/value-pairs, like:</p> <p><code>"mylist.a_key"</code> or <code>"mylist['a_key']"</code></p> <p>without iterating over the list. any ideas?</p>
3
2009-04-09T09:59:02Z
733,582
<p>You can't do it without any iteration. You will either need iteration to convert it into a dict, at which point key access will become possible sans iteration, or you will need to iterate over it for each key access. Converting to a dict seems the better idea-- in the long run it is more efficient, but more importantly, it represents how you actually see this data structure-- as pairs of keys and values.</p> <pre><code>&gt;&gt;&gt; x = [('a_key', 'a value'), ('another_key', 'another value')] &gt;&gt;&gt; y = dict(x) &gt;&gt;&gt; y['a_key'] 'a value' &gt;&gt;&gt; y['another_key'] 'another value' </code></pre>
14
2009-04-09T10:03:41Z
[ "python" ]
Access list of tuples
733,574
<p>I have a list that contains several tuples, like:</p> <pre><code>[('a_key', 'a value'), ('another_key', 'another value')] </code></pre> <p>where the first tuple-values act as dictionary-keys. I'm now searching for a python-like way to access the key/value-pairs, like:</p> <p><code>"mylist.a_key"</code> or <code>"mylist['a_key']"</code></p> <p>without iterating over the list. any ideas?</p>
3
2009-04-09T09:59:02Z
733,596
<p>If you're generating the list yourself, you might be able to create it as a dictionary at source (which allows for key, value pairs).</p> <p>Otherwise, Van Gale's defaultdict is the way to go I would think.</p> <p>Edit:</p> <p>As mentioned in the comments, defaultdict is not required here unless you need to deal with corner cases like several values with the same key in your list. Still, if you can originally generate the "list" as a dictionary, you save yourself having to iterate back over it afterwards.</p>
3
2009-04-09T10:07:28Z
[ "python" ]
Pygame: Sprite changing due to direction of movement
733,916
<p>I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty fast into 3D modeling with out instructing how to make changing sprites for movement of up down left and right and how to cycle through animating images.</p> <p>I've spent all today trying to get a sprite to display and be able to move around with up down left and right. But because of the simple script it uses a static image and refuses to change.</p> <p>Can anyone give me some knowledge on how to change the sprites. Or send me to a tutorial that does?</p> <p>Every reference and person experimenting with it ha always been using generated shapes so I'm never able to work with them.</p> <p>Any help is very appreciated.</p> <p>Added: before figuring out how to place complex animations in my scene I'd like to know how I can make my 'player' change to unmoving images in regards to my pressing up down left or right. maybe diagonal if people know its something really complicated.</p> <p>Add: This is what I've put together so far. <a href="http://animania1.ca/ShowFriends/dev/dirmove.rar" rel="nofollow">http://animania1.ca/ShowFriends/dev/dirmove.rar</a> would there be a possibility of making the direction/action set the column of the action and have the little column setting code also make it cycle down in a loop to do the animation? (or would that be a gross miss use of efficiency?)</p>
1
2009-04-09T12:01:58Z
734,150
<p>I don't know much about Pygame, but I've used SDL (on which Pygame is based).</p> <p>If you use <code>Surface.blit()</code>: <a href="http://www.pygame.org/docs/ref/surface.html#Surface.blit" rel="nofollow">link text</a></p> <p>You can use the optional <code>area</code> argument to select which part of the surface to draw. So if you put all the images that are part of the animation inside a single file, you can select which image will be drawn. It's called "clipping".</p> <p>I guess you will have a game loop that will update the game state (changing the current image of the sprite if necessary), then draw the sprites using their state.</p>
0
2009-04-09T13:10:39Z
[ "python", "2d", "pygame", "sprite" ]
Pygame: Sprite changing due to direction of movement
733,916
<p>I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty fast into 3D modeling with out instructing how to make changing sprites for movement of up down left and right and how to cycle through animating images.</p> <p>I've spent all today trying to get a sprite to display and be able to move around with up down left and right. But because of the simple script it uses a static image and refuses to change.</p> <p>Can anyone give me some knowledge on how to change the sprites. Or send me to a tutorial that does?</p> <p>Every reference and person experimenting with it ha always been using generated shapes so I'm never able to work with them.</p> <p>Any help is very appreciated.</p> <p>Added: before figuring out how to place complex animations in my scene I'd like to know how I can make my 'player' change to unmoving images in regards to my pressing up down left or right. maybe diagonal if people know its something really complicated.</p> <p>Add: This is what I've put together so far. <a href="http://animania1.ca/ShowFriends/dev/dirmove.rar" rel="nofollow">http://animania1.ca/ShowFriends/dev/dirmove.rar</a> would there be a possibility of making the direction/action set the column of the action and have the little column setting code also make it cycle down in a loop to do the animation? (or would that be a gross miss use of efficiency?)</p>
1
2009-04-09T12:01:58Z
734,772
<p>Here is a dumb example which alernates between two first images of the spritesheet when you press left/right:</p> <pre><code>import pygame quit = False pygame.init() display = pygame.display.set_mode((640,480)) sprite_sheet = pygame.image.load('sprite.bmp').convert() # by default, display the first sprite image_number = 0 while quit == False: event = pygame.event.poll() no_more_events = True if event == pygame.NOEVENT else False # handle events (update game state) while no_more_events == False: if event.type == pygame.QUIT: quit = True break elif event.type == pygame.NOEVENT: no_more_events = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: image_number = 0 elif event.key == pygame.K_RIGHT: image_number = 1 event = pygame.event.poll() if quit == False: # redraw the screen display.fill(pygame.Color('white')) area = pygame.Rect(image_number * 100, 0, 100, 150) display.blit(sprite_sheet, (0,0), area) pygame.display.flip() </code></pre> <p>I've never really used Pygame before so maybe this code shoudln't really be taken as an example. I hope it shows the basics though.</p> <p>To be more complete I should wait some time before updating, e.g. control that I update only 60 times per second.</p> <p>It would also be handy to write a sprite class which would simplify your work. You would pass the size of a sprite frame in the constructor, and you'd have methodes like <code>update()</code> and <code>draw()</code> which would automatically do the work of selecting the next frame, blitting the sprite and so on.</p> <p>Pygame seems to provide a base class for that purpose: <a href="http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite" rel="nofollow">link text</a>.</p>
1
2009-04-09T15:38:23Z
[ "python", "2d", "pygame", "sprite" ]
Pygame: Sprite changing due to direction of movement
733,916
<p>I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty fast into 3D modeling with out instructing how to make changing sprites for movement of up down left and right and how to cycle through animating images.</p> <p>I've spent all today trying to get a sprite to display and be able to move around with up down left and right. But because of the simple script it uses a static image and refuses to change.</p> <p>Can anyone give me some knowledge on how to change the sprites. Or send me to a tutorial that does?</p> <p>Every reference and person experimenting with it ha always been using generated shapes so I'm never able to work with them.</p> <p>Any help is very appreciated.</p> <p>Added: before figuring out how to place complex animations in my scene I'd like to know how I can make my 'player' change to unmoving images in regards to my pressing up down left or right. maybe diagonal if people know its something really complicated.</p> <p>Add: This is what I've put together so far. <a href="http://animania1.ca/ShowFriends/dev/dirmove.rar" rel="nofollow">http://animania1.ca/ShowFriends/dev/dirmove.rar</a> would there be a possibility of making the direction/action set the column of the action and have the little column setting code also make it cycle down in a loop to do the animation? (or would that be a gross miss use of efficiency?)</p>
1
2009-04-09T12:01:58Z
1,766,294
<p>dude the only thing you have to do is offcourse </p> <p>import pygame and all the other stuff needed type code and stuff..........then when it comes to you making a spri</p> <pre><code>class .your class nam here. (pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.init(self) self.image=pygame.image.load(your image and path) self.rect=self.image.get_rect() x=0 y=0 # any thing else is what you want like posistion and other variables def update(self): self.rect.move_ip((x,y)) </code></pre> <p>and thats it!!!! but thats not the end. if you do this you will ony have made the sprite to move it you need</p>
-1
2009-11-19T20:29:26Z
[ "python", "2d", "pygame", "sprite" ]
What is the difference between a site and an app in Django?
734,255
<p>I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. </p> <p>Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mysite with one app called StackOverflow?</p>
23
2009-04-09T13:35:00Z
734,271
<p>As you said, you'd have a site called StackOverflow with an auth app, questions app, etc.</p> <p>You should have a look at the <a href="http://pinaxproject.com/" rel="nofollow">Pinax project</a> to see how they lay things out. It's one of the better ways to do it since it will increase the modularity and portability of your apps.</p>
0
2009-04-09T13:38:13Z
[ "python", "django" ]
What is the difference between a site and an app in Django?
734,255
<p>I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. </p> <p>Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mysite with one app called StackOverflow?</p>
23
2009-04-09T13:35:00Z
734,297
<p>From the <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/">Django documentation</a>:</p> <blockquote> <h2>Projects vs. apps</h2> <p>What’s the difference between a project and an app? An app is a Web application that does something — e.g., a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.</p> </blockquote> <p>From <a href="http://www.b-list.org/weblog/2006/sep/10/django-tips-laying-out-application/">this link</a>:</p> <blockquote> <h2>Projects versus applications</h2> <p>This is really more of a separate (though related) question, but understanding the distinction Django draws between a “project” and an “application” is a big part of good code layout. Roughly speaking, this is what the two terms mean:</p> <ul> <li><p>An application tries to provide a single, relatively self-contained set of related functions. An application is allowed to define a set of models (though it doesn’t have to) and to define and register custom template tags and filters (though, again, it doesn’t have to).</p></li> <li><p>A project is a collection of applications, installed into the same database, and all using the same settings file. In a sense, the defining aspect of a project is that it supplies a settings file which specifies the database to use, the applications to install, and other bits of configuration. A project may correspond to a single web site, but doesn’t have to — multiple projects can run on the same site. The project is also responsible for the root URL configuration, though in most cases it’s useful to just have that consist of calls to include which pull in URL configurations from inidividual applications.</p></li> </ul> <p>Views, custom manipulators, custom context processors and most other things Django lets you create can all be defined either at the level of the project or of the application, and where you do that should depend on what’s most effective for you; in general, though, they’re best placed inside an application (this increases their portability across projects). </p> </blockquote>
8
2009-04-09T13:43:20Z
[ "python", "django" ]
What is the difference between a site and an app in Django?
734,255
<p>I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. </p> <p>Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mysite with one app called StackOverflow?</p>
23
2009-04-09T13:35:00Z
734,321
<p>Django actually has 3 concepts here:</p> <ul> <li><p><strong>Project</strong> (I think this is what you're calling site): This is the directory that contains all the apps. They share a common runtime invocation and can refer to each other.</p></li> <li><p><strong>App</strong>: This is a set of views, models, and templates. Apps are often designed so they can be plugged into another project.</p></li> <li><p><strong>Site</strong>: You can designate different behaviour for an app based on the site (ie: URL) being visited. This way, the same "App" can customize itself based on whether or not the user has visited 'StackOverflow.com' or 'RackOverflow.com' (or whatever the IT-targeted version will be called), even though it's the same codebase that's handling the request.</p></li> </ul> <p>How you arrange these is really up to your project. In a complicated case, you might do:</p> <pre><code>Project: StackOverflowProject App: Web Version Site: StackOverflow.com Site: RackOverflow.com App: XML API Version Site: StackOverflow.com Site: RackOverflow.com Common non-app settings, libraries, auth, etc </code></pre> <p>Or, for a simpler project that wants to leverage an open-source plugin:</p> <pre><code>Project: StackOverflowProject App: Stackoverflow (No specific use of the sites feature... it's just one site) App: Plug-in TinyMCE editor with image upload (No specific use of the sites feature) </code></pre> <p>Aside from the fact that there needs to be a Project, and at least one app, the arrangement is very flexible; you can adapt however suits best to help abstract and manage the complexity (or simplicity) of your deployment.</p>
24
2009-04-09T13:48:52Z
[ "python", "django" ]
What is the difference between a site and an app in Django?
734,255
<p>I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. </p> <p>Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mysite with one app called StackOverflow?</p>
23
2009-04-09T13:35:00Z
2,665,181
<p>The answer to would you have a project with a single app called StackOverflow is an unequivocal no. A site like this might have 20+ apps.</p> <p>See James Bennett's "<a href="http://www.youtube.com/watch?v=A-S0tqpPga4" rel="nofollow" title="DjangoCon 2008: Reusable Apps">DjangoCon 2008: Reusable Apps</a>" video presentation which explains this nicely.</p>
2
2010-04-19T04:21:29Z
[ "python", "django" ]
Pretty-printing C# from Python
734,413
<p>Suppose I wrote a compiler in Python or Ruby that translates a language into a C# AST.</p> <p>How do I pretty-print this AST from Python or Ruby to get nicely indented C# code?</p> <pre><code>Thanks, Joel </code></pre>
-1
2009-04-09T14:05:37Z
734,442
<p>In python the <a href="http://docs.python.org/library/pprint.html" rel="nofollow">pprint</a> module is available.</p> <p>Depending on how your data is structured it may not return the result your looking for.</p>
1
2009-04-09T14:14:26Z
[ "c#", "python", "ruby", "parsing", "pretty-print" ]
Pretty-printing C# from Python
734,413
<p>Suppose I wrote a compiler in Python or Ruby that translates a language into a C# AST.</p> <p>How do I pretty-print this AST from Python or Ruby to get nicely indented C# code?</p> <pre><code>Thanks, Joel </code></pre>
-1
2009-04-09T14:05:37Z
734,690
<p>One way would be to just print it and then invoke a code formatter.</p>
-1
2009-04-09T15:17:35Z
[ "c#", "python", "ruby", "parsing", "pretty-print" ]
Pretty-printing C# from Python
734,413
<p>Suppose I wrote a compiler in Python or Ruby that translates a language into a C# AST.</p> <p>How do I pretty-print this AST from Python or Ruby to get nicely indented C# code?</p> <pre><code>Thanks, Joel </code></pre>
-1
2009-04-09T14:05:37Z
739,358
<p>Once you have an AST, this should be very easy. When you walk your AST, all you have to do is keep track of what your current indent level is -- you could use a global for this. The code that's walking the tree simply needs to increment the indent level every time you enter a block, and decrement it when you exit a block. Then, whenever you print a line of code, you call it like this:</p> <pre><code>print "\t"*indentlevel + code </code></pre> <p>You should end up with nicely formatted code. However, I'm a bit confused that you're asking this question -- if you have the skills to parse C# into an AST, I can't imagine you wouldn't be able to write a pretty-printing output function. :-)</p>
1
2009-04-11T01:50:20Z
[ "c#", "python", "ruby", "parsing", "pretty-print" ]
Python mechanize - two buttons of type 'submit'
734,893
<p>I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the forum and do br.submit(), it clicks on the 'attach' button instead of 'create'. Extensive Googling has yielded nothing useful for selecting a specific button in a form. Does anyone know of any methods for skipping over the first 'submit' button and clicking the second?</p>
27
2009-04-09T16:11:15Z
734,962
<p>I can talk from experience using HTTP, rather than mechanize, but I think this is probably what you want.</p> <p>When there are two submit buttons in a form, a server can determine which one was pressed, because the client should have added an argument for the submit button. So:</p> <pre><code>&lt;form action="blah" method="get"&gt; &lt;p&gt; &lt;input type="submit" name="button_1" value="One" /&gt; &lt;input type="submit" name="button_2" value="Two" /&gt; &lt;/p&gt; &lt;/form&gt; </code></pre> <p>Will take you either the URL:</p> <pre><code>blah?button_1=One </code></pre> <p>or:</p> <pre><code>blah?button_2=Two </code></pre> <p>Depending on which button was pressed.</p> <p>If you're programatically determining what arguments are going to be sent, you need to add an argument with the name of the submit button that was pressed, and it's value.</p>
2
2009-04-09T16:28:42Z
[ "python", "mechanize" ]
Python mechanize - two buttons of type 'submit'
734,893
<p>I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the forum and do br.submit(), it clicks on the 'attach' button instead of 'create'. Extensive Googling has yielded nothing useful for selecting a specific button in a form. Does anyone know of any methods for skipping over the first 'submit' button and clicking the second?</p>
27
2009-04-09T16:11:15Z
735,031
<p>I would suggest you to use Twill which uses mechanize (mostly monkeypatched). So say you have form with some fields and two submit buttons with <strong>names</strong> "submit_to_preview" and "real_submit". Following code should work.</p> <p>BTW remember this is not threadsafe so you might want to use locks in case if you want to use the code in a threaded env.</p> <pre><code>import twill.commands b = twill.get_browser() url = "http://site/myform" twill.commands.go(url) twill.commands.fv("2", "name", "Me") twill.commands.fv("2", "age", "32") twill.commands.fv("2", "comment", "useful article") twill.commands.browser.submit("real_submit") </code></pre> <p>Hope that helps. Cheers.</p>
7
2009-04-09T16:50:55Z
[ "python", "mechanize" ]
Python mechanize - two buttons of type 'submit'
734,893
<p>I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the forum and do br.submit(), it clicks on the 'attach' button instead of 'create'. Extensive Googling has yielded nothing useful for selecting a specific button in a form. Does anyone know of any methods for skipping over the first 'submit' button and clicking the second?</p>
27
2009-04-09T16:11:15Z
1,263,476
<p>Use the 'click' method. E.g.</p> <pre><code>mybrowser.select_form(nr=0) req = mybrowser.click(type="submit", nr=1) mybrowser.open(req) </code></pre> <p>Should work.</p>
4
2009-08-11T23:10:18Z
[ "python", "mechanize" ]
Python mechanize - two buttons of type 'submit'
734,893
<p>I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the forum and do br.submit(), it clicks on the 'attach' button instead of 'create'. Extensive Googling has yielded nothing useful for selecting a specific button in a form. Does anyone know of any methods for skipping over the first 'submit' button and clicking the second?</p>
27
2009-04-09T16:11:15Z
1,685,753
<p>I tried using the nr parameter, without any luck.</p> <p>I was able to get it to work with a combination of the name and label parameters, where "label" seems to correspond to the "value" in the HTML:</p> <p>Here are my two submit buttons:</p> <pre><code>&lt;input type="submit" name="Preview" value="Preview" /&gt; &lt;input type="submit" name="Create" value="Create New Page" /&gt; </code></pre> <p>... and here's the code that clicks the first one, goes back, and then clicks the second:</p> <pre><code>from mechanize import Browser self.br = Browser() self.br.open('http://foo.com/path/to/page.html') self.br.select_form(name='my_form') self.br['somefieldname'] = 'Foo' submit_response = self.br.submit(name='Preview', label='Preview') self.br.back() self.br.select_form(name='my_form') self.br['somefieldname'] = 'Bar' submit_response = self.br.submit(name='Create', label='Create New Page') </code></pre> <p>There's a variant that also worked for me, where the "name" of the submit button is the same, such as:</p> <pre><code>&lt;input type="submit" name="action" value="Preview" /&gt; &lt;input type="submit" name="action" value="Save" /&gt; &lt;input type="submit" name="action" value="Cancel" /&gt; </code></pre> <p>and</p> <pre><code>self.br.select_form(name='my_form') submit_response = self.br.submit(name='action', label='Preview') self.br.back() submit_response = self.br.submit(name='action', label='Save') </code></pre> <p>IMPORTANT NOTE - I was <em>only</em> able to get any of this multiple-submit-button code to work <strong>after</strong> cleaning up some HTML in the rest of the page.</p> <p>Specifically, I could not have <code>&lt;br/&gt;</code> - instead I had to have <code>&lt;br /&gt;</code> ... and, making even less sense, I could not have anything between the two submit buttons.</p> <p>It frustrated me to no end that the mechanize/ClientForm bug I hunted for over two hours boiled down to this:</p> <pre><code>&lt;tr&gt;&lt;td colspan="2"&gt;&lt;br/&gt;&lt;input type="submit" name="Preview" value="Preview" /&gt;&amp;nbsp;&lt;input type="submit" name="Create" value="Create New Page" /&gt;&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>(all on one line) did not work, but</p> <pre><code>&lt;tr&gt;&lt;td colspan="2"&gt;&lt;br /&gt; &lt;input type="submit" name="Preview" value="Preview" /&gt; &lt;input type="submit" name="Create" value="Create New Page" /&gt;&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>worked fine (on multiple lines, which also shouldn't have mattered).</p> <p>I like mechanize because it was easy to install (just copy the files into my include directory) and because it's pretty simple to use, but unless I'm missing something major, I think that bugs like this are kind of awful - I can't think of a good reason at all why the first example there should fail and the second should work.</p> <p>And, incidentally, I also found another mechanize bug where a <code>&lt;textarea&gt;</code> which is contained within a <code>&lt;p&gt;</code> is not recognized as a valid control, but once you take it out of the <code>&lt;p&gt;</code> container it's recognized just fine. And I checked, textarea <strong>is</strong> allowed to be included in other block-level elements like <code>&lt;p&gt;</code>.</p>
19
2009-11-06T06:17:16Z
[ "python", "mechanize" ]
Python: Reference to a class from a string?
734,970
<p>How to use a string containing a class name to reference a class itself?<br /> See this (not working) exemple...</p> <pre><code>class WrapperClass: def display_var(self): #FIXME: self.__class_name__.__name__ is a string print self.__class__.__name__.the_var class SomeSubClass(WrapperClass): var = "abc" class AnotherSubClass(WrapperClass): var = "def" </code></pre> <p>And an obvious error message:</p> <pre> >>> b = SomeSubClass() >>> b.display_var() Traceback (most recent call last): File "", line 1, in File "", line 4, in display_var AttributeError: 'str' object has no attribute 'the_var' >>> </pre> <p>Thanks!</p>
0
2009-04-09T16:29:49Z
734,984
<p>Your example would work if you called <code>print self.__class__.var</code>. I don't think there's any need to use the name.</p>
1
2009-04-09T16:33:35Z
[ "python" ]
Python: Reference to a class from a string?
734,970
<p>How to use a string containing a class name to reference a class itself?<br /> See this (not working) exemple...</p> <pre><code>class WrapperClass: def display_var(self): #FIXME: self.__class_name__.__name__ is a string print self.__class__.__name__.the_var class SomeSubClass(WrapperClass): var = "abc" class AnotherSubClass(WrapperClass): var = "def" </code></pre> <p>And an obvious error message:</p> <pre> >>> b = SomeSubClass() >>> b.display_var() Traceback (most recent call last): File "", line 1, in File "", line 4, in display_var AttributeError: 'str' object has no attribute 'the_var' >>> </pre> <p>Thanks!</p>
0
2009-04-09T16:29:49Z
734,995
<p>Depending on where you get this string, any general method may be insecure (one such method is to simply use <code>eval(string)</code>. The best method is to define a dict mapping names to classes:</p> <pre><code>class WrapperClass: def display_var(self): #FIXME: self.__class_name__.__name__ is a string print d[self.__class__.__name__].the_var class SomeSubClass(WrapperClass): the_var = "abc" class AnotherSubClass(WrapperClass): the_var = "def" d = {'WrapperClass': WrapperClass, 'SomeSubClass': SomeSubClass, 'AnotherSubClass': AnotherSubClass} AnotherSubClass().display_var() # prints 'def' </code></pre>
2
2009-04-09T16:36:52Z
[ "python" ]
Python: Reference to a class from a string?
734,970
<p>How to use a string containing a class name to reference a class itself?<br /> See this (not working) exemple...</p> <pre><code>class WrapperClass: def display_var(self): #FIXME: self.__class_name__.__name__ is a string print self.__class__.__name__.the_var class SomeSubClass(WrapperClass): var = "abc" class AnotherSubClass(WrapperClass): var = "def" </code></pre> <p>And an obvious error message:</p> <pre> >>> b = SomeSubClass() >>> b.display_var() Traceback (most recent call last): File "", line 1, in File "", line 4, in display_var AttributeError: 'str' object has no attribute 'the_var' >>> </pre> <p>Thanks!</p>
0
2009-04-09T16:29:49Z
735,014
<blockquote> <p>How to use a string containing a class name to reference a class itself?</p> </blockquote> <p>Classes aren't special, they're just values contained in variables. If you've said:</p> <pre><code>class X(object): pass </code></pre> <p>in global scope, then the variable ‘X’ will be a reference to the class object.</p> <p>You can get the current script/module's global variables as a dictionary using ‘globals()’, so:</p> <pre><code>classobj= globals()[self.__class__.__name__] print classobj.var </code></pre> <p>(<code>locals()</code> is also available for local variables; between them you shouldn't ever need to use the awful <code>eval()</code> to access variables.)</p> <p>However as David notes, <code>self.__class__</code> is <em>already</em> the <code>classobj</code>, so there's no need to go running about fetching it from the global variables by name; <code>self.__class__.var</code> is fine. Although really:</p> <pre><code>print self.var </code></pre> <p>would be the usual simple way to do it. Class members are available as members of their instances, as long as the instance doesn't overwrite the name with something else.</p>
5
2009-04-09T16:46:09Z
[ "python" ]
Propagating application settings
735,337
<p>Probably a very common question, but couldn't find suitable answer yet.. </p> <p>I have a (Python w/ C++ modules) application that makes heavy use of an SQLite database and its path gets supplied by user on application start-up. </p> <p>Every time some part of application needs access to database, I plan to acquire a new session and discard it when done. For that to happen, I obviously need access to the path supplied on startup. Couple of ways that I see it happening:</p> <p><strong>1. Explicit arguments</strong></p> <p>The database path is passed everywhere it needs to be through an explicit parameter and database session is instantiated with that explicit path. This is perhaps the most modular, but seems to be incredibly awkward.</p> <p><strong>2. Database path singleton</strong></p> <p>The database session object would look like:</p> <pre><code>import foo.options class DatabaseSession(object): def __init__(self, path=foo.options.db_path): ... </code></pre> <p>I consider this to be the lesser-evil singleton, since we're storing only constant strings, which don't change during application runtime. This leaves it possible to override the default and unit test the <code>DatabaseSession</code> class if necessary.</p> <p><strong>3. Database path singleton + static factory method</strong></p> <p>Perhaps slight improvement over the above:</p> <pre><code>def make_session(path=None): import foo.options if path is None: path = foo.options.db_path return DatabaseSession(path) class DatabaseSession(object): def __init__(self, path): ... </code></pre> <p>This way the module doesn't depend on <code>foo.options</code> at all, unless we're using the factory method. Additionally, the method can perform stuff like session caching or whatnot.</p> <p>And then there are other patterns, which I don't know of. I vaguely saw something similar in web frameworks, but I don't have any experience with those. My example is quite specific, but I imagine it also expands to other application settings, hence the title of the post. </p> <p>I would like to hear your thoughts about what would be the best way to arrange this.</p>
4
2009-04-09T18:17:18Z
735,436
<p>Yes, there are others. Your option 3 though is very Pythonic. </p> <p>Use a standard Python module to encapsulate options (this is the way web frameworks like Django do it)</p> <p>Use a factory to emit properly configured sessions.</p> <p>Since SQLite already has a "connection", why not use that? What does your <code>DatabaseSession</code> class add that the built-in connection lacks?</p>
2
2009-04-09T18:43:09Z
[ "python", "singleton", "settings", "global" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
735,593
<p>See <a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation">http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation</a></p> <blockquote> <p>Secondly, once we have decided that the combined data in the two fields we are considering aren't valid, we must remember to remove them from the cleaned_data.</p> <p>In fact, Django will currently completely wipe out the cleaned_data dictionary if there are any errors in the form. However, this behaviour may change in the future, so it's not a bad idea to clean up after yourself in the first place.</p> </blockquote> <p>The original data is always available in <code>request.POST</code>.</p> <hr> <p>A Comment suggests that the point is to do something that sounds like more sophisticated field-level validation.</p> <p>Each field is given the unvalidated data, and either returns the valid data or raises an exception.</p> <p>In each field, any kind of validation can be done on the original contents.</p>
17
2009-04-09T19:27:13Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
1,285,554
<p>You access the data from either the field's clean() method, or from the form's clean() method. clean() is the function that determines whether the form is valid or not. It's called when is_valid() is called. In form's clean() you have the <code>cleaned_data</code> list when you can run through custom code to make sure it's all checked out. In the widget, you have a clean() also, but it uses a single passed variable. In order to access the field's clean() method, you'll have to subclass it. e.g.:</p> <pre><code>class BlankIntField(forms.IntegerField): def clean(self, value): if not value: value = 0 return int(value) </code></pre> <p>If you want an IntField that doesn't choke on an empty value, for instance, you'd use the above.</p> <p>clean() on a form kind of works like this:</p> <pre><code>def clean(self): if self.cleaned_data.get('total',-1) &lt;= 0.0: raise forms.ValidationError("'Total must be positive") return self.cleaned_data </code></pre> <p>Also you can have a clean_FIELD() function for each field so you can validate each field individually (after the field's clean() is called)</p>
1
2009-08-16T22:54:20Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
1,440,599
<p>You can use</p> <pre><code>form.data['field_name'] </code></pre> <p>This way you get the raw value assigned to the field.</p>
33
2009-09-17T18:36:49Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
6,152,128
<p>You can use this pattern:</p> <pre><code>class MyForm(forms.Form): ... def clean(self): self.saved_data=self.cleaned_data return self.cleaned_data </code></pre> <p>In your code:</p> <pre><code>if form.is_valid(): form.save() return django.http.HttpResponseRedirect(...) if form.is_bound: form.saved_data['....'] # cleaned_data does not exist any more, but saved_data does. </code></pre> <p>Using form.data is not a good solution. Reasons:</p> <ul> <li>If the form has a prefix, the dictionary keys will be prefixed with this prefix.</li> <li>The data in form.data is not cleaned: There are only string values.</li> </ul>
5
2011-05-27T12:17:15Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
9,807,131
<p>I ran into a similar problem using a formset. In my example, I wanted the user to select a 1st choice before a 2nd choice, but if the 1st choice hit another error, the 'select 1st choice before 2nd' error was also displayed. </p> <p>To grab the 1st field's uncleaned data, I used this within the form field's clean method:</p> <pre><code>dirty_rc1 = self.data[self.prefix + '-reg_choice_1'] </code></pre> <p>Then, I could test for the presence of data in that field:</p> <pre><code>if not dirty_rc1: raise ValidationError('Make a first choice before second') </code></pre> <p>Hope this helps!</p>
3
2012-03-21T14:57:22Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
11,005,988
<p>I was struggling with a similar issue, and came across a great discussion here: <a href="https://code.djangoproject.com/ticket/10427">https://code.djangoproject.com/ticket/10427</a></p> <p>It's not at all well documented, but for a live form, you can view a field's value -- as seen by widgets/users -- with the following:</p> <pre><code>form_name['field_name'].value() </code></pre>
12
2012-06-12T22:51:06Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
How to access data when form.is_valid() is false
735,545
<p>When I have a valid Django form, I can access the data with form.cleaned_data. But how do I get at the data a user entered when the form is not valid i.e., form.is_valid is false.</p> <p>I'm trying to access forms within a form set, so form.data seems to just give me a mess.</p>
36
2009-04-09T19:16:03Z
31,262,753
<p>I have many methods. All you can pick.</p> <p>I suppose the form is like as below:</p> <pre><code>class SignupForm(forms.Form): email = forms.CharField(label='email') password = forms.CharField(label='password', widget=forms.PasswordInput) </code></pre> <p>1-1. Get from <code>request</code></p> <pre><code>def signup(req): if req.method == 'POST': email = req.POST.get('email', '') password = req.POST.get('password', '') </code></pre> <p>2-1. Get the <code>raw value</code> assigned to the field and return the value of the <code>data</code> attribute of field</p> <pre><code>def signup(req): if req.method == 'POST': ... sf = SignupForm(req.POST) email = sf["email"].data password = sf["password"].data ... </code></pre> <p>2-2. Get the raw value assigned to the field and return the value of the <code>value</code> attribute of field</p> <pre><code>def signup(req): if req.method == 'POST': ... sf = SignupForm(req.POST) email = sf["email"].value() password = sf["password"].value() ... </code></pre> <p>2-3. Get the <code>dictionary</code> assigned to the fields</p> <pre><code>def signup(req): if req.method == 'POST': ... sf = SignupForm(req.POST) # print sf.data # &lt;QueryDict: {u'csrfmiddlewaretoken': [u'U0M9skekfcZiyk0DhlLVV1HssoLD6SGv'], u'password': [u''], u'email': [u'hello']}&gt; email = sf.data.get("email", '') password = sf.data.get("password", '') ... </code></pre>
2
2015-07-07T07:50:33Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
Looping through chars, generating words and checking if domain exists
735,743
<p>Hello<br> Is there any way to generate words based on characters and checking if a domain exists with this word (ping)?</p> <p>What I want to do is to generate words based on some characters, example "abcdefgh", and then ping generatedword.com to check if it exists. </p>
0
2009-04-09T20:03:11Z
735,784
<p>It seems like you are talking about permutations of character combinations. This has been a fairly well <a href="http://code.activestate.com/recipes/190465/" rel="nofollow">published recipe</a>. That link should get you started.</p> <p>One additional note, ping will not tell you if a server 'exists' or if the name is registered, only if it is online and is <em>not</em> behind a firewall that blocks ping traffic.</p>
0
2009-04-09T20:16:17Z
[ "python", "ping" ]
Looping through chars, generating words and checking if domain exists
735,743
<p>Hello<br> Is there any way to generate words based on characters and checking if a domain exists with this word (ping)?</p> <p>What I want to do is to generate words based on some characters, example "abcdefgh", and then ping generatedword.com to check if it exists. </p>
0
2009-04-09T20:03:11Z
735,801
<p>Just because a site fails a ping doesn't mean the domain is available. The domain could be reserved but not pointing anywhere, or the machine may not respond to pings, or it may just be down.</p>
3
2009-04-09T20:21:14Z
[ "python", "ping" ]
Looping through chars, generating words and checking if domain exists
735,743
<p>Hello<br> Is there any way to generate words based on characters and checking if a domain exists with this word (ping)?</p> <p>What I want to do is to generate words based on some characters, example "abcdefgh", and then ping generatedword.com to check if it exists. </p>
0
2009-04-09T20:03:11Z
735,810
<p>You don't want to use the ping command, but you can use Python's <a href="http://docs.python.org/library/socket.html#socket.gethostbyname" rel="nofollow"><code>socket.gethostbyname()</code> function</a> to determine whether a host exists.</p> <pre><code>def is_valid_host(hostname): try: addr = socket.gethostbyname(hostname) except socket.gaierror, ex: return False return True hosts = ['abc', 'yahoo.com', 'google.com', 'nosuchagency.gov'] filter(is_valid_host, hosts) </code></pre> <p>This is going to take tons of time and maybe make your ISP mad at you. You're better off either:</p> <ol> <li><p>Using a lower-level DNS interface such as <a href="http://www.dnspython.org/" rel="nofollow">dnspython</a>, or</p></li> <li><p>Finding a direct interface to domain registrars, such as <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=whois&amp;submit=search" rel="nofollow">whois</a>, and querying that. </p></li> </ol> <p>You aren't going to use this to spam people, are you?</p>
7
2009-04-09T20:24:52Z
[ "python", "ping" ]
Pass to python method based on length of a list
735,878
<p>I have a list called 'optionlist' which may change length from day to day, but I want a tkinter dropdown box to be able to select something from it. </p> <p>Here's an example of how to define a tkinter optionmenu:</p> <pre><code>opt1 = OptionMenu(root, var1, 'A', 'B', 'C') </code></pre> <p>A, B, and C are the options you can select. The problem presented here is that while the OptionMenu is flexible and allows as many options as you want, you have to know exactly how many you want when you write the code. This isn't a list or a tuple being passed.</p> <p>I'm wondering if anyone knows any kung-fu for making this so I don't have to do:</p> <pre><code>if len(optionlist) == 1: opt1 = OptionMenu(root, var1, optionlist[0]) if len(optionlist) == 2: opt1 = OptionMenu(root, var1, optionlist[0], optionlist[1]) etc, etc, etc </code></pre> <p>I know you can define a list like this:</p> <pre><code>elements = [client.get('element') for client in clientlist] </code></pre> <p>I'm hoping something similar can be done when passing to methods as well.</p>
1
2009-04-09T20:51:18Z
735,889
<p>You want the <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists"><code>*</code> operator</a>:</p> <pre><code>opt1 = OptionMenu(root, var1, *optionlist) </code></pre>
11
2009-04-09T20:53:59Z
[ "python", "parameters" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
735,976
<p>Yes, check out the <a href="http://docs.python.org/library/functions.html#staticmethod">staticmethod</a> decorator:</p> <pre><code>&gt;&gt;&gt; class C: ... @staticmethod ... def hello(): ... print "Hello World" ... &gt;&gt;&gt; C.hello() Hello World </code></pre>
58
2009-04-09T21:24:15Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
735,978
<p>Yep, using the <a href="https://docs.python.org/2/library/functions.html#staticmethod">staticmethod</a> decorator</p> <pre><code>class MyClass(object): @staticmethod def the_static_method(x): print x MyClass.the_static_method(2) # outputs 2 </code></pre> <p>Note that some code might use the old method of defining a static method, using <code>staticmethod</code> as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3)</p> <pre><code>class MyClass(object): def the_static_method(x): print x the_static_method = staticmethod(the_static_method) MyClass.the_static_method(2) # outputs 2 </code></pre> <p>This is entirely identical to the first example (using <code>@staticmethod</code>), just not using the nice decorator syntax</p> <p>Finally, use <a href="https://docs.python.org/2/library/functions.html#staticmethod"><code>staticmethod()</code></a> sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.</p> <hr> <p><a href="https://docs.python.org/2/library/functions.html#staticmethod">The following is verbatim from the documentation:</a>:</p> <blockquote> <p>A static method does not receive an implicit first argument. To declare a static method, use this idiom:</p> <pre><code>class C: @staticmethod def f(arg1, arg2, ...): ... </code></pre> <p>The @staticmethod form is a function <a href="https://docs.python.org/2/glossary.html#term-decorator"><em>decorator</em></a> – see the description of function definitions in <a href="https://docs.python.org/2/reference/compound_stmts.html#function"><em>Function definitions</em></a> for details.</p> <p>It can be called either on the class (such as <code>C.f()</code>) or on an instance (such as <code>C().f()</code>). The instance is ignored except for its class.</p> <p>Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see <a href="https://docs.python.org/2/library/functions.html#classmethod"><code>classmethod()</code></a>.</p> <p>For more information on static methods, consult the documentation on the standard type hierarchy in <a href="https://docs.python.org/2/reference/datamodel.html#types"><em>The standard type hierarchy</em></a>.</p> <p>New in version 2.2.</p> <p>Changed in version 2.4: Function decorator syntax added.</p> </blockquote>
1,215
2009-04-09T21:24:36Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
738,102
<p>You don't really need to use the <code>@staticmethod</code> decorator. Just declaring a method (that doesn't expect the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)</p> <p>Mostly, you just use functions though...</p>
20
2009-04-10T16:00:50Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
10,206,355
<p>I think that Steven is actually right. To answer the original question, then, in order to set up a class method, simply assume that the first argument is not going to be a calling instance, and then make sure that you only call the method from the class.</p> <p>(Note that this answer refers to Python 3.x. In Python 2.x you'll get a <code>TypeError</code> for calling the method on the class itself.)</p> <p>For example:</p> <pre><code>class Dog: count = 0 # this is a class variable dogs = [] # this is a class variable def __init__(self, name): self.name = name #self.name is an instance variable Dog.count += 1 Dog.dogs.append(name) def bark(self, n): # this is an instance method print("{} says: {}".format(self.name, "woof! " * n)) def rollCall(n): #this is implicitly a class method (see comments below) print("There are {} dogs.".format(Dog.count)) if n &gt;= len(Dog.dogs) or n &lt; 0: print("They are:") for dog in Dog.dogs: print(" {}".format(dog)) else: print("The dog indexed at {} is {}.".format(n, Dog.dogs[n])) fido = Dog("Fido") fido.bark(3) Dog.rollCall(-1) rex = Dog("Rex") Dog.rollCall(0) </code></pre> <p>In this code, the "rollCall" method assumes that the first argument is not an instance (as it would be if it were called by an instance instead of a class). As long as "rollCall" is called from the class rather than an instance, the code will work fine. If we try to call "rollCall" from an instance, e.g.:</p> <pre><code>rex.rollCall(-1) </code></pre> <p>however, it would cause an exception to be raised because it would send two arguments: itself and -1, and "rollCall" is only defined to accept one argument.</p> <p>Incidentally, rex.rollCall() would send the correct number of arguments, but would also cause an exception to be raised because now n would be representing a Dog instance (i.e., rex) when the function expects n to be numerical.</p> <p>This is where the decoration comes in: If we precede the "rollCall" method with</p> <pre><code>@staticmethod </code></pre> <p>then, by explicitly stating that the method is static, we can even call it from an instance. Now, </p> <pre><code>rex.rollCall(-1) </code></pre> <p>would work. The insertion of @staticmethod before a method definition, then, stops an instance from sending itself as an argument.</p> <p>You can verify this by trying the following code with and without the @staticmethod line commented out.</p> <pre><code>class Dog: count = 0 # this is a class variable dogs = [] # this is a class variable def __init__(self, name): self.name = name #self.name is an instance variable Dog.count += 1 Dog.dogs.append(name) def bark(self, n): # this is an instance method print("{} says: {}".format(self.name, "woof! " * n)) @staticmethod def rollCall(n): print("There are {} dogs.".format(Dog.count)) if n &gt;= len(Dog.dogs) or n &lt; 0: print("They are:") for dog in Dog.dogs: print(" {}".format(dog)) else: print("The dog indexed at {} is {}.".format(n, Dog.dogs[n])) fido = Dog("Fido") fido.bark(3) Dog.rollCall(-1) rex = Dog("Rex") Dog.rollCall(0) rex.rollCall(-1) </code></pre>
127
2012-04-18T09:16:03Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
14,085,311
<p>Aside from the particularities of how <a href="http://docs.python.org/2/reference/datamodel.html#types" rel="nofollow">static method objects</a> behave, there is a certain kind of beauty you can strike with them when it comes to organizing your module-level code.</p> <pre><code># garden.py def trim(a): pass def strip(a): pass def bunch(a, b): pass def _foo(foo): pass class powertools(object): """ Provides much regarded gardening power tools. """ @staticmethod def answer_to_the_ultimate_question_of_life_the_universe_and_everything(): return 42 @staticmethod def random(): return 13 @staticmethod def promise(): return True def _bar(baz, quux): pass class _Dice(object): pass class _6d(_Dice): pass class _12d(_Dice): pass class _Smarter: pass class _MagicalPonies: pass class _Samurai: pass class Foo(_6d, _Samurai): pass class Bar(_12d, _Smarter, _MagicalPonies): pass </code></pre> <p>...</p> <pre><code># tests.py import unittest import garden class GardenTests(unittest.TestCase): pass class PowertoolsTests(unittest.TestCase): pass class FooTests(unittest.TestCase): pass class BarTests(unittest.TestCase): pass </code></pre> <p>...</p> <pre><code># interactive.py from garden import trim, bunch, Foo f = trim(Foo()) bunch(f, Foo()) </code></pre> <p>...</p> <pre><code># my_garden.py import garden from garden import powertools class _Cowboy(garden._Samurai): def hit(): return powertools.promise() and powertools.random() or 0 class Foo(_Cowboy, garden.Foo): pass </code></pre> <p>It now becomes a bit more intuitive and self-documenting in which context certain components are meant to be used and it pans out ideally for naming distinct test cases as well as having a straightforward approach to how test modules map to actual modules under tests for purists.</p> <p>I frequently find it viable to apply this approach to organizing a project's utility code. Quite often, people immediately rush and create a <code>utils</code> package and end up with 9 modules of which one has 120 LOC and the rest are two dozen LOC at best. I prefer to start with this and convert it to a package and create modules only for the beasts that truly deserve them:</p> <pre><code># utils.py class socket(object): @staticmethod def check_if_port_available(port): pass @staticmethod def get_free_port(port) pass class image(object): @staticmethod def to_rgb(image): pass @staticmethod def to_cmyk(image): pass </code></pre>
6
2012-12-29T19:47:13Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
25,041,766
<p>Perhaps the simplest option is just to put those functions outside of the class:</p> <pre><code>class Dog(object): def __init__(self, name): self.name = name def bark(self): if self.name == "Doggy": return barking_sound() else: return "yip yip" def barking_sound(): return "woof woof" </code></pre> <p>Using this method, functions which modify or use internal object state (have side effects) can be kept in the class, and the reusable utility functions can be moved outside.</p> <p>Let's say this file is called <code>dogs.py</code>. To use these, you'd call <code>dogs.barking_sound()</code> instead of <code>dogs.Dog.barking_sound</code>.</p> <p>If you really need a static method to be part of the class, you can use the <a href="http://docs.python.org/library/functions.html#staticmethod" rel="nofollow">staticmethod</a> decorator.</p>
2
2014-07-30T16:10:48Z
[ "python", "static-methods" ]
Static methods in Python?
735,975
<p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod ( ) </code></pre>
956
2009-04-09T21:23:19Z
28,122,324
<blockquote> <p><strong>Static methods in Python?</strong></p> <p>Is it possible to have static methods in Python so I can call them without initializing a class, like:</p> <pre><code>ClassName.StaticMethod() </code></pre> </blockquote> <p>Yes, static methods can be created like this (although it's a bit more <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">Pythonic</a> to use underscores instead of CamelCase for methods):</p> <pre><code>class ClassName(object): @staticmethod def static_method(kwarg1=None): '''return a value that is a function of kwarg1''' </code></pre> <p>The above uses the decorator syntax. This syntax is equivalent to </p> <pre><code>class ClassName(object): def static_method(kwarg1=None): '''return a value that is a function of kwarg1''' static_method = staticmethod(static_method) </code></pre> <p>This can be used just as you described:</p> <pre><code>ClassName.static_method() </code></pre> <p>A builtin example of a static method is <code>str.maketrans()</code> in Python 3, which was a function in the <code>string</code> module in Python 2.</p> <hr> <p>Another option that can be used as you describe is the <code>classmethod</code>, the difference is that the classmethod gets the class as an implicit first argument, and if subclassed, then it gets the subclass as the implicit first argument.</p> <pre><code>class ClassName(object): @classmethod def class_method(cls, kwarg1=None): '''return a value that is a function of the class and kwarg1''' </code></pre> <p>Note that <code>cls</code> is not a required name for the first argument, but most experienced Python coders will consider it badly done if you use anything else.</p> <p>These are typically used as alternative constructors. </p> <pre><code>new_instance = ClassName.class_method() </code></pre> <p>A builtin example is <code>dict.fromkeys()</code>:</p> <pre><code>new_dict = dict.fromkeys(['key1', 'key2']) </code></pre>
18
2015-01-24T04:34:35Z
[ "python", "static-methods" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.</p> <pre><code>partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): newelement=float(element) </code></pre> <p>This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in <a href="http://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python">this question</a>.</p> <p>Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?</p>
55
2009-04-09T21:52:33Z
736,050
<p>I would just use..</p> <pre><code>try: float(element) except ValueError: print "Not a float" </code></pre> <p>..it's simple, and it works</p> <p>Another option would be a regular expression:</p> <pre><code>import re if re.match("^\d+?\.\d+?$", element) is None: print "Not float" </code></pre>
101
2009-04-09T21:55:39Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.</p> <pre><code>partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): newelement=float(element) </code></pre> <p>This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in <a href="http://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python">this question</a>.</p> <p>Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?</p>
55
2009-04-09T21:52:33Z
736,117
<p>This regex will check for scientific floating point numbers:</p> <pre><code>^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$ </code></pre> <p>However, I believe that your best bet is to use the parser in a try.</p>
2
2009-04-09T22:30:52Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.</p> <pre><code>partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): newelement=float(element) </code></pre> <p>This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in <a href="http://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python">this question</a>.</p> <p>Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?</p>
55
2009-04-09T21:52:33Z
736,179
<p>If you cared about performance (and I'm not suggesting you should), the try-based approach is the clear winner (compared with your partition-based approach or the regexp approach), as long as you don't expect a lot of invalid strings, in which case it's potentially slower (presumably due to the cost of exception handling).</p> <p>Again, I'm not suggesting you care about performance, just giving you the data in case you're doing this 10 billion times a second, or something. Also, the partition-based code doesn't handle at least one valid string.</p> <pre> $ ./floatstr.py F.. partition sad: 3.1102449894 partition happy: 2.09208488464 .. re sad: 7.76906108856 re happy: 7.09421992302 .. try sad: 12.1525540352 try happy: 1.44165301323 . ====================================================================== FAIL: test_partition (__main__.ConvertTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "./floatstr.py", line 48, in test_partition self.failUnless(is_float_partition("20e2")) AssertionError ---------------------------------------------------------------------- Ran 8 tests in 33.670s FAILED (failures=1) </pre> <p>Here's the code (Python 2.6, regexp taken from John Gietzen's <a href="http://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python/736117#736117">answer</a>):</p> <pre><code>def is_float_try(str): try: float(str) return True except ValueError: return False import re _float_regexp = re.compile(r"^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$") def is_float_re(str): return re.match(_float_regexp, str) def is_float_partition(element): partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and pa\ rtition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): return True if __name__ == '__main__': import unittest import timeit class ConvertTests(unittest.TestCase): def test_re(self): self.failUnless(is_float_re("20e2")) def test_try(self): self.failUnless(is_float_try("20e2")) def test_re_perf(self): print print 're sad:', timeit.Timer('floatstr.is_float_re("12.2x")', "import floatstr").timeit() print 're happy:', timeit.Timer('floatstr.is_float_re("12.2")', "import floatstr").timeit() def test_try_perf(self): print print 'try sad:', timeit.Timer('floatstr.is_float_try("12.2x")', "import floatstr").timeit() print 'try happy:', timeit.Timer('floatstr.is_float_try("12.2")', "import floatstr").timeit() def test_partition_perf(self): print print 'partition sad:', timeit.Timer('floatstr.is_float_partition("12.2x")', "import floatstr").timeit() print 'partition happy:', timeit.Timer('floatstr.is_float_partition("12.2")', "import floatstr").timeit() def test_partition(self): self.failUnless(is_float_partition("20e2")) def test_partition2(self): self.failUnless(is_float_partition(".2")) def test_partition3(self): self.failIf(is_float_partition("1234x.2")) unittest.main() </code></pre>
5
2009-04-09T22:56:46Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.</p> <pre><code>partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): newelement=float(element) </code></pre> <p>This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in <a href="http://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python">this question</a>.</p> <p>Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?</p>
55
2009-04-09T21:52:33Z
738,944
<p>Strictly, these regexp-style solutions should be checking the locale. Not all locales use dots as the separator.</p>
3
2009-04-10T21:34:47Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.</p> <pre><code>partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): newelement=float(element) </code></pre> <p>This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in <a href="http://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python">this question</a>.</p> <p>Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?</p>
55
2009-04-09T21:52:33Z
20,929,881
<h2>Python method to check for float:</h2> <pre><code>def isfloat(value): try: float(value) return True except ValueError: return False </code></pre> <h2>Don't get bit by the goblins hiding in the float boat! DO UNIT TESTING!</h2> <p>What is, and is not a float may surprise you:</p> <pre><code>Command to parse Is it a float? Comment -------------------------------------- --------------- ------------ print(isfloat("")) False print(isfloat("1234567")) True print(isfloat("NaN")) True nan is also float print(isfloat("NaNananana BATMAN")) False print(isfloat("123.456")) True print(isfloat("123.E4")) True print(isfloat(".1")) True print(isfloat("1,234")) False print(isfloat("NULL")) False case insensitive print(isfloat(",1")) False print(isfloat("123.EE4")) False print(isfloat("6.523537535629999e-07")) True print(isfloat("6e777777")) True This is same as Inf print(isfloat("-iNF")) True print(isfloat("1.797693e+308")) True print(isfloat("infinity")) True print(isfloat("infinity and BEYOND")) False print(isfloat("12.34.56")) False Two dots not allowed. print(isfloat("#56")) False print(isfloat("56%")) False print(isfloat("0E0")) True print(isfloat("x86E0")) False print(isfloat("86-5")) False print(isfloat("True")) False Boolean is not a float. print(isfloat(True)) True Boolean is a float print(isfloat("+1e1^5")) False print(isfloat("+1e1")) True print(isfloat("+1e1.3")) False print(isfloat("+1.3P1")) False print(isfloat("-+1")) False print(isfloat("(1)")) False brackets not interpreted </code></pre>
51
2014-01-05T03:56:52Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.</p> <pre><code>partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): newelement=float(element) </code></pre> <p>This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in <a href="http://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python">this question</a>.</p> <p>Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?</p>
55
2009-04-09T21:52:33Z
25,299,441
<p>There is another method available via a third-party module called <a href="https://pypi.python.org/pypi/fastnumbers" rel="nofollow">fastnumbers</a> (disclosure, I am the author); it provides a function called <a href="http://pythonhosted.org//fastnumbers/checks.html#isfloat" rel="nofollow">isfloat</a>. I have taken the unittest example outlined by Jacob Gabrielson in <a href="http://stackoverflow.com/a/736179/1399279">this answer</a>, but added the <code>fastnumbers.isfloat</code> method. I should also note that Jacob's example did not do justice to the regex option because most of the time in that example was spent in global lookups because of the dot operator... I have modified that function to give a fairer comparison to <code>try: except:</code>. </p> <hr> <pre><code>def is_float_try(str): try: float(str) return True except ValueError: return False import re _float_regexp = re.compile(r"^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$").match def is_float_re(str): return True if _float_regexp(str) else False def is_float_partition(element): partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): return True else: return False from fastnumbers import isfloat if __name__ == '__main__': import unittest import timeit class ConvertTests(unittest.TestCase): def test_re_perf(self): print print 're sad:', timeit.Timer('ttest.is_float_re("12.2x")', "import ttest").timeit() print 're happy:', timeit.Timer('ttest.is_float_re("12.2")', "import ttest").timeit() def test_try_perf(self): print print 'try sad:', timeit.Timer('ttest.is_float_try("12.2x")', "import ttest").timeit() print 'try happy:', timeit.Timer('ttest.is_float_try("12.2")', "import ttest").timeit() def test_fn_perf(self): print print 'fn sad:', timeit.Timer('ttest.isfloat("12.2x")', "import ttest").timeit() print 'fn happy:', timeit.Timer('ttest.isfloat("12.2")', "import ttest").timeit() def test_part_perf(self): print print 'part sad:', timeit.Timer('ttest.is_float_partition("12.2x")', "import ttest").timeit() print 'part happy:', timeit.Timer('ttest.is_float_partition("12.2")', "import ttest").timeit() unittest.main() </code></pre> <hr> <p>On my machine, the output is:</p> <pre><code>fn sad: 0.220988988876 fn happy: 0.212214946747 . part sad: 1.2219619751 part happy: 0.754667043686 . re sad: 1.50515985489 re happy: 1.01107215881 . try sad: 2.40243887901 try happy: 0.425730228424 . ---------------------------------------------------------------------- Ran 4 tests in 7.761s OK </code></pre> <p>As you can see, regex is actually not as bad as it originally seemed, and if you have a real need for speed, the <code>fastnumbers</code> method is quite good.</p>
2
2014-08-14T03:13:05Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.</p> <pre><code>partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): newelement=float(element) </code></pre> <p>This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in <a href="http://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python">this question</a>.</p> <p>Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?</p>
55
2009-04-09T21:52:33Z
33,012,298
<p>If you don't need to worry about scientific or other expressions of numbers and are only working with strings that could be numbers with or without a period:</p> <p><strong>Function</strong></p> <pre><code>def is_float(s): result = False if s.count(".") == 1: if s.replace(".", "").isdigit(): result = True return result </code></pre> <p><strong>Lambda version</strong></p> <pre><code>is_float = lambda x: x.replace('.','',1).isdigit() and "." in x </code></pre> <p><strong>Example</strong></p> <pre><code>if is_float(some_string): some_string = float(some_string) elif some_string.isdigit(): some_string = int(some_string) else: print "Does not convert to int or float." </code></pre> <p>This way you aren't accidentally converting what should be an int, into a float.</p>
1
2015-10-08T09:50:32Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.</p> <pre><code>partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): newelement=float(element) </code></pre> <p>This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in <a href="http://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python">this question</a>.</p> <p>Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?</p>
55
2009-04-09T21:52:33Z
38,329,481
<pre><code>'1.43'.replace('.','',1).isdigit() </code></pre> <p>which will return <code>true</code> only if there is one or no '.' in the string of digits. <br><br></p> <pre><code>'1.4.3'.replace('.','',1).isdigit() </code></pre> <p>will return <code>false</code> <br><br></p> <pre><code>'1.ww'.replace('.','',1).isdigit() </code></pre> <p>will return <code>false</code></p>
2
2016-07-12T12:52:46Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.</p> <pre><code>partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): newelement=float(element) </code></pre> <p>This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in <a href="http://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python">this question</a>.</p> <p>Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?</p>
55
2009-04-09T21:52:33Z
39,671,880
<p>str(strval).isdigit() seems to be simple. Handles values stored in as a string or int or float</p>
0
2016-09-24T02:20:47Z
[ "python", "string", "type-conversion" ]
Checking if a string can be converted to float in Python
736,043
<p>I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy</p> <pre><code>if element.isdigit(): newelement=int(element) </code></pre> <p>Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.</p> <pre><code>partition=element.partition('.') if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''): newelement=float(element) </code></pre> <p>This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in <a href="http://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python">this question</a>.</p> <p>Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?</p>
55
2009-04-09T21:52:33Z
40,064,302
<p>I used the function already mentioned, but soon I notice that strings as "Nan", "Inf" and it's variation are considered as number. So I propose you improved version of the function, that will return false on those type of input and will not fail "1e3" variants:</p> <pre><code>def is_float(text): try: float(text) # check for nan/infinity etc. if text.isalpha(): return False return True except ValueError: return False </code></pre>
0
2016-10-15T21:15:58Z
[ "python", "string", "type-conversion" ]
Python Superglobal?
736,335
<p>Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file.</p>
3
2009-04-10T00:22:48Z
736,359
<p>In theory yes, you can start spewing crud into __builtin__:</p> <pre><code>&gt;&gt;&gt; import __builtin__ &gt;&gt;&gt; __builtin__.rubbish= 3 &gt;&gt;&gt; rubbish 3 </code></pre> <p>But, don't do this; it's horrible evilness that will give your applications programming-cancer.</p> <blockquote> <p>classes and functions and i don't want to have to keep declaring</p> </blockquote> <p>Put them in modules and ‘import’ them when you need to use them.</p> <blockquote> <p>I have certain variables i want to use throughout my whole project</p> </blockquote> <p>If you must have unqualified values, just put them in a file called something like “mypackage/constants.py” then:</p> <pre><code>from mypackage.constants import * </code></pre> <p>If they really are ‘variables’ in that you change them during app execution, you need to start encapsulating them in objects.</p>
15
2009-04-10T00:35:38Z
[ "python", "python-3.x" ]
Python Superglobal?
736,335
<p>Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file.</p>
3
2009-04-10T00:22:48Z
736,378
<p>Even if there are, you should not use such a construct EVER. Consider using a borg pattern to hold this kind of stuff.</p> <pre><code>class Config: """ Borg singlton config object """ __we_are_one = {} __myvalue = "" def __init__(self): #implement the borg patter (we are one) self.__dict__ = self.__we_are_one def myvalue(self, value=None): if value: self.__myvalue = value return self.__myvalue conf = Config() conf.myvalue("Hello") conf2 = Config() print conf2.myvalue() </code></pre> <p>Here we use the borg pattern to create a singlton object. No matter where you use this in the code, the 'myvalue' will be the same, no matter what module or class you instantiate Config in.</p>
4
2009-04-10T00:41:45Z
[ "python", "python-3.x" ]
Python Superglobal?
736,335
<p>Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file.</p>
3
2009-04-10T00:22:48Z
737,386
<p>Create empty superglobal.py module.<br/> In your files do:</p> <pre><code>import superglobal superglobal.whatever = loacalWhatever other = superglobal.other </code></pre>
2
2009-04-10T11:40:21Z
[ "python", "python-3.x" ]
Python Superglobal?
736,335
<p>Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file.</p>
3
2009-04-10T00:22:48Z
4,898,617
<p>The reason it wasn't obvious to you is that Python intentionally doesn't try to support such a thing. Namespaces are a <em>feature</em>, and using them is to your advantage. If you want something you defined in another file, import it. This means from reading your source code you can figure out where everything came from, and also makes your code easier to test and modify.</p>
1
2011-02-04T13:43:41Z
[ "python", "python-3.x" ]
Python Superglobal?
736,335
<p>Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file.</p>
3
2009-04-10T00:22:48Z
4,900,210
<p>in years of practice, i've grown quite disappointed with python's import system: it is complicated and difficult to handle correctly. also, i have to maintain scores of imports in each and every module i write, which is a pita. </p> <p>namespaces are a very good idea, and they're indispensable---php doesn't have proper namespaces, and it's a mess.</p> <p>conceptually, part of writing an application consists in defining a suitable vocabulary, the words that you'll use to do the things you want to. yet in the classical way, it's exactly these words that won't come easy, as you have to first import this, import that to obtain access. </p> <p>when namespaces came into focus in the javascript community, john resig of jquery fame decided that providing a single <code>$</code> variable in the global namespace was the way to go: it would only affect the global namespace minimally, and provide easy access to everything with jquery. </p> <p>likewise, i experimented with a global variable <code>g</code>, and it worked to an extent. basically, you have two options here: either have a startup module that must be run prior to any other module in your app, which defines what things should be available in <code>g</code>, so it is ready to go when needed. the other approach which i tried was to make <code>g</code> lazy and to react with custom imports when a new name was required; so whenever you need to <code>g.foo.frob(42)</code> for the first time, the mechanism will try something like <code>import foo; g.foo = foo</code> behind the scenes. that was considerable more difficult to do right.</p> <p>these days, i've ditched the import system almost completely except for standard library and site packages. most of the time i write wrappers for hose libraries, as 90% of those have inanely convoluted interfaces anyhow. those wrappers i then publish in the global namespace, using spelling conventions to keep the risk of collisions to a minimum.</p> <p>i only tell this to alleviate the impression that modifying the global namespace is something that is inherently evil, which the other answers seem to state. not so. what is evil is to do it thoughtlessly, or be compelled by language or package design to do so. </p> <p>let me add one remark, as i almost certainly will get some fire here: 99% of all imports done by people who religiously defend namespace purity are <em>wrong</em>. proof? you'll read in the beginning lines of any module <code>foo.py</code> that needs to do trigonometrics something like <code>from math import sin</code>. now when you correctly <code>import foo</code> and have a look at that namespace, what are you going to find? something named <code>foo.sin</code>. but that <code>sin</code> isn't part of the interface of <code>foo</code>, it is just a helper, it shouldn't clutter that namespace---hence, <code>from math import sin as _sin</code> or somesuch would've been correct. however, almost nobody does it that way.</p> <p>i'm sure to arouse some heated comments with these views, so go ahead.</p>
3
2011-02-04T16:14:51Z
[ "python", "python-3.x" ]
Ping FeedBurner in Django App
736,413
<p>I have a django site, and some of the feeds are published through FeedBurner. I would like to ping FeedBurner whenever I save an instance of a particular model. FeedBurner's website says to use the XML-RPC ping mechanism, but I can't find a lot of documentation on how to implement it.</p> <p>What's the easiest way to do the XML-RPC ping in django/Python?</p>
4
2009-04-10T01:00:55Z
736,576
<p>maybe sth like that:</p> <pre><code>import xmlrpclib j = xmlrpclib.Server('http://feedburnerrpc') reply = j.weblogUpdates.ping('website title','http://urltothenewpost') </code></pre>
1
2009-04-10T02:51:02Z
[ "python", "django", "xml-rpc" ]
Ping FeedBurner in Django App
736,413
<p>I have a django site, and some of the feeds are published through FeedBurner. I would like to ping FeedBurner whenever I save an instance of a particular model. FeedBurner's website says to use the XML-RPC ping mechanism, but I can't find a lot of documentation on how to implement it.</p> <p>What's the easiest way to do the XML-RPC ping in django/Python?</p>
4
2009-04-10T01:00:55Z
736,617
<p>You can use Django's <a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow"><code>signals</code></a> feature to get a callback after a model is saved:</p> <pre><code>import xmlrpclib from django.db.models.signals import post_save from app.models import MyModel def ping_handler(sender, instance=None, **kwargs): if instance is None: return rpc = xmlrpclib.Server('http://ping.feedburner.google.com/') rpc.weblogUpdates.ping(instance.title, instance.get_absolute_url()) post_save.connect(ping_handler, sender=MyModel) </code></pre> <p>Clearly, you should update this with what works for your app and read up on signals in case you want a different event.</p>
12
2009-04-10T03:14:49Z
[ "python", "django", "xml-rpc" ]
Ping FeedBurner in Django App
736,413
<p>I have a django site, and some of the feeds are published through FeedBurner. I would like to ping FeedBurner whenever I save an instance of a particular model. FeedBurner's website says to use the XML-RPC ping mechanism, but I can't find a lot of documentation on how to implement it.</p> <p>What's the easiest way to do the XML-RPC ping in django/Python?</p>
4
2009-04-10T01:00:55Z
736,821
<p>Use pluggable apps, Luke!</p> <p><a href="http://github.com/svetlyak40wt/django-pingback/" rel="nofollow">http://github.com/svetlyak40wt/django-pingback/</a></p>
2
2009-04-10T05:48:24Z
[ "python", "django", "xml-rpc" ]
PyQt connect method bug when used in a for loop which creates widgets from a list
736,651
<p>I have a GUI program, </p> <p>It auto create buttons from a name list, and connect to a function prints its name.</p> <p>but when I run this program, I press all the buttons, </p> <p>they all return the last button's name.</p> <p>I wonder why this thing happens. can any one help?</p> <pre><code>import sys from PyQt4.QtCore import * from PyQt4.QtGui import * import logging logging.basicConfig(level=logging.DEBUG,) class MainWindow(QWidget): def init(self): names = ('a','b','c') lo = QHBoxLayout(self) for name in names: button = QPushButton(name,self) lo.addWidget(button) self.connect(button,SIGNAL("clicked()"), lambda :logging.debug(name)) if __name__=="__main__": app = QApplication(sys.argv) m = MainWindow();m.init();m.show() app.exec_() </code></pre> <p>result like:</p> <pre><code>python t.py DEBUG:root:c DEBUG:root:c DEBUG:root:c </code></pre>
1
2009-04-10T03:48:22Z
736,738
<p>I see at least one bug in your code.</p> <p>Replace: </p> <pre><code> lambda :logging.debug(name) </code></pre> <p>By:</p> <pre><code> lambda name=name: logging.debug(name) </code></pre> <p>See <a href="http://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different">Why results of map() and list comprehension are different?</a> for details.</p>
3
2009-04-10T04:51:10Z
[ "python", "pyqt" ]
How to read ID3 Tag in an MP3 using Python?
736,813
<p>Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)</p>
12
2009-04-10T05:45:24Z
736,818
<p>A quick google showed up <a href="http://id3-py.sourceforge.net/" rel="nofollow">http://id3-py.sourceforge.net/</a></p> <p>Maybe this works for you ?</p>
2
2009-04-10T05:48:03Z
[ "python", "tags", "mp3", "music", "id3" ]
How to read ID3 Tag in an MP3 using Python?
736,813
<p>Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)</p>
12
2009-04-10T05:45:24Z
736,823
<p>Mutagen <a href="https://bitbucket.org/lazka/mutagen" rel="nofollow">https://bitbucket.org/lazka/mutagen</a> <em>Edited 14/09/23 with current code host location</em></p> <p>eyeD3 <a href="http://eyed3.nicfit.net/" rel="nofollow">http://eyed3.nicfit.net/</a></p>
12
2009-04-10T05:48:51Z
[ "python", "tags", "mp3", "music", "id3" ]
How to read ID3 Tag in an MP3 using Python?
736,813
<p>Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)</p>
12
2009-04-10T05:45:24Z
736,869
<p><a href="http://diveintopython.net/object_oriented_framework/index.html">Dive into Python</a> uses MP3 ID3 tags as an example.</p>
15
2009-04-10T06:20:26Z
[ "python", "tags", "mp3", "music", "id3" ]
How to read ID3 Tag in an MP3 using Python?
736,813
<p>Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)</p>
12
2009-04-10T05:45:24Z
737,144
<p>Try <a href="http://eyed3.nicfit.net/" rel="nofollow">eyeD3</a>, it's a program and a module.</p>
2
2009-04-10T09:24:35Z
[ "python", "tags", "mp3", "music", "id3" ]
Pygame: Sprite animation Theory - Need Feedback
737,303
<p>After some tweaking of some code I got from someone to cause a characters images to move in regards to its direction and up down left right input I've put this together: (hope the code isn't too messy)</p> <p><a href="http://animania1.ca/ShowFriends/dev/dirmove.rar" rel="nofollow">Character Move Code + IMG</a></p> <p>The Sprite sheet only runs lengthwise, so basically each sprite section is a different action. Now would there be a way I could make a code that functions with the current one to cycle down from a set 'action' in order to make an animation?</p> <p>For example: 'Run Left' is sprite 3. So then after we designate that column would it be possible to loop down how ever many frames of the run animation (lets say 4) in order to make an animation?</p> <p>Example Picture: <a href="http://animania1.ca/ShowFriends/dev/example.jpg" rel="nofollow">http://animania1.ca/ShowFriends/dev/example.jpg</a></p>
3
2009-04-10T10:53:05Z
737,379
<p>It should be easy.</p> <p>If you record the frame number in a variable, you can modulo this with the number of frames you have to get an animation frame number to display.</p> <pre><code>frame_count = 0 animation_frames = 4 while quit == False: # ... # snip # ... area = pygame.Rect( image_number * 100, (frame_count % animation_frames) * 150, 100, 150 ) display.blit(sprite, sprite_pos, area) pygame.display.flip() frame_count += 1 </code></pre> <p>If different actions have different numbers of frames, you'll have to update animation_frames when you update image_number.</p> <p>Also, this assumes that it's ok to play the animation starting at <em>any</em> frame. If this is not the case, you'll need to record what the frame count was when the action started, and take this away from frame count before the modulo:</p> <pre><code> area = pygame.Rect( image_number * 100, ((frame_count - action_start_frame) % animation_frames) * 150, 100, 150 ) </code></pre> <p>A note about your event handling. If you hold down, say, left, and tap right but keep holding down left, the sprite stops moving because the last event you processed was a keyup event, despite the fact that I'm still holding left.</p> <p>If this is not what you want, you can get around it by either keeping a record of the up/down states of the keys you are interested in, or by using the <a href="http://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed" rel="nofollow">pygame.key.get_pressed</a> interface.</p> <p>On another note, you appear to be aiming for a fixed frame rate, and at the same time determining how far to move your sprite based on the time taken in the last frame. In my opinion, this probably isn't ideal.</p> <p>2D action games generally need to work in a predictable manner. If some CPU heavy process starts in the background on your computer and causes your game to no longer be able to churn out 60 frames a second, it's probably preferable for it to slow down, rather then have your objects start skipping huge distances between frames. Imagine if this happened in a 2D action game like Metal Slug where you're having to jump around avoiding bullets?</p> <p>This also makes any physics calculations much simpler. You'll have to make a judgement call based on what type of game it is.</p>
4
2009-04-10T11:35:13Z
[ "python", "2d", "pygame", "sprite" ]
How can I make a Python extension module packaged as an egg loadable without installing it?
737,383
<p>I'm in the middle of reworking our build scripts to be based upon <a href="http://code.google.com/p/waf/" rel="nofollow">the wonderful Waf tool</a> (I did use SCons for ages but its just <em>way</em> too slow). </p> <p>Anyway, I've hit the following situation and I cannot find a resolution to it:</p> <ul> <li>I have a product that depends on a number of previously built egg files.</li> <li>I'm trying to package the product using <a href="http://www.pyinstaller.org/" rel="nofollow">PyInstaller</a> as part of the build process.</li> <li>I build the dependencies first.</li> <li>Next I want to run PyInstaller to package the product that depends on the eggs I built. I need PyInstaller to be able to load those egg files as part of it's packaging process.</li> </ul> <p>This sounds easy: you work out what <code>PYTHONPATH</code> should be, construct a copy of <code>sys.environ</code> setting the variable up correctly, and then invoke the PyInstaller script using <code>subprocess.Popen</code> passing the previously configured environment as the env argument.</p> <p>The problem is that setting <code>PYTHONPATH</code> alone does not seem to be enough if the eggs you are adding are extension modules that are packaged as zipsafe. In this case, it turns out that the embedded libraries are not able to be imported.</p> <p>If I unzip the eggs (renaming the directories to .egg), I can import them with no further settings but this is not what I want in this case.</p> <p>I can also get the eggs to import from a subshell by doing the following:</p> <ul> <li>Setting <code>PYTHONPATH</code> to the directory that contains the egg you want to import (not the path of the egg itself)</li> <li>Loading a python shell and using <code>pkg_resources.require</code> to locate the egg. </li> </ul> <p>Once this has been done, the egg loads as normal. Again, this is not practical because I need to be able to run my python shell in a manner where it is ready to import these eggs from the off. </p> <p>The dirty option would be to output a wrapper script that took the above actions before calling the real target script but this seems like the wrong thing to do: there must be a better way to do this.</p>
0
2009-04-10T11:37:52Z
737,493
<p>Heh, I think this was my bad. The issue appear to have been that the <code>zipsafe</code> flag in setup.py for the extension package was set to False, which appears to affect your ability to treat it as such at all.</p> <p>Now that I've set that to True I can import the egg files, simply by adding each one to the <code>PYTHONPATH</code>.</p> <p>I hope someone else finds this answer useful one day!</p>
3
2009-04-10T12:32:33Z
[ "python", "setuptools", "egg", "waf", "build-tools" ]
How can I make a Python extension module packaged as an egg loadable without installing it?
737,383
<p>I'm in the middle of reworking our build scripts to be based upon <a href="http://code.google.com/p/waf/" rel="nofollow">the wonderful Waf tool</a> (I did use SCons for ages but its just <em>way</em> too slow). </p> <p>Anyway, I've hit the following situation and I cannot find a resolution to it:</p> <ul> <li>I have a product that depends on a number of previously built egg files.</li> <li>I'm trying to package the product using <a href="http://www.pyinstaller.org/" rel="nofollow">PyInstaller</a> as part of the build process.</li> <li>I build the dependencies first.</li> <li>Next I want to run PyInstaller to package the product that depends on the eggs I built. I need PyInstaller to be able to load those egg files as part of it's packaging process.</li> </ul> <p>This sounds easy: you work out what <code>PYTHONPATH</code> should be, construct a copy of <code>sys.environ</code> setting the variable up correctly, and then invoke the PyInstaller script using <code>subprocess.Popen</code> passing the previously configured environment as the env argument.</p> <p>The problem is that setting <code>PYTHONPATH</code> alone does not seem to be enough if the eggs you are adding are extension modules that are packaged as zipsafe. In this case, it turns out that the embedded libraries are not able to be imported.</p> <p>If I unzip the eggs (renaming the directories to .egg), I can import them with no further settings but this is not what I want in this case.</p> <p>I can also get the eggs to import from a subshell by doing the following:</p> <ul> <li>Setting <code>PYTHONPATH</code> to the directory that contains the egg you want to import (not the path of the egg itself)</li> <li>Loading a python shell and using <code>pkg_resources.require</code> to locate the egg. </li> </ul> <p>Once this has been done, the egg loads as normal. Again, this is not practical because I need to be able to run my python shell in a manner where it is ready to import these eggs from the off. </p> <p>The dirty option would be to output a wrapper script that took the above actions before calling the real target script but this seems like the wrong thing to do: there must be a better way to do this.</p>
0
2009-04-10T11:37:52Z
738,470
<p>Although you have a solution, you could always try "virtualenv" that creates a virtual environment of python where you can install and test Python Packages without messing with the core system python:</p> <p><a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">http://pypi.python.org/pypi/virtualenv</a></p>
1
2009-04-10T18:32:32Z
[ "python", "setuptools", "egg", "waf", "build-tools" ]
SQLite in Python 2.2.3
737,511
<p>I've written a web-app in python using SQLite and it runs fine on my server at home (with apache and python 2.5.2). I'm now trying to upload it to my web host and there servers use python 2.2.3 without SQLite.<br/> Anyone know of a way to use SQLite in python 2.2.3 e.g. a module that I can upload and import? I've tried butchering the module from newer versions of python, but they don't seem to be compatible.<br/> Thanks,<br/> Mike</p>
1
2009-04-10T12:40:39Z
737,606
<p>Look here: <a href="http://oss.itsystementwicklung.de/download/pysqlite/" rel="nofollow">http://oss.itsystementwicklung.de/download/pysqlite/</a></p> <p>From the release notes (<a href="http://oss.itsystementwicklung.de/trac/pysqlite/browser/doc/install-source.txt" rel="nofollow">http://oss.itsystementwicklung.de/trac/pysqlite/browser/doc/install-source.txt</a>)</p> <blockquote> <ol> <li>Python: Python 2.3 or later</li> </ol> </blockquote> <p>You may not be able to do what you're trying to do.</p>
1
2009-04-10T13:21:35Z
[ "python", "sql", "linux", "sqlite", "hosting" ]
SQLite in Python 2.2.3
737,511
<p>I've written a web-app in python using SQLite and it runs fine on my server at home (with apache and python 2.5.2). I'm now trying to upload it to my web host and there servers use python 2.2.3 without SQLite.<br/> Anyone know of a way to use SQLite in python 2.2.3 e.g. a module that I can upload and import? I've tried butchering the module from newer versions of python, but they don't seem to be compatible.<br/> Thanks,<br/> Mike</p>
1
2009-04-10T12:40:39Z
737,617
<p>There is no out-of-the-box solution; you either have to backport the SQLlite module from Python 2.5 to Python 2.2 or ask your web hoster to upgrade to the latest Python version. </p> <p>Python 2.2 is really ancient! At least for security reasons, they should upgrade (no more security fixes for 2.2 since May 30, 2003!).</p> <p>Note that you can install several versions of Python in parallel. Just make sure you use "/usr/bin/python25" instead of "/usr/bin/python" in your scripts. To make sure all the old stuff is still working, after installing Python 2.5, you just have to fix the two symbolic links "/usr/bin/python" and "/usr/lib/python" which should now point to 2.5. Bend them back to 2.2 and you're good.</p>
2
2009-04-10T13:26:57Z
[ "python", "sql", "linux", "sqlite", "hosting" ]