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
overload print python
550,470
<p>Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.</p> <p>Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <a href="http://stackoverflow.com/questions/550470/overload-print-python/550477#550477">http://stackoverflow.com/questions/550470/overload-print-python/550477#550477</a> just told me i cant overload print in 2.x which is what i am using.</p>
26
2009-02-15T07:26:05Z
550,477
<p>In Python 2.x you can't, because print isn't a function, it's a statement. In Python 3 print is a function, so I suppose it could be overridden (haven't tried it, though).</p>
2
2009-02-15T07:29:39Z
[ "python", "printing", "overloading" ]
overload print python
550,470
<p>Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.</p> <p>Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <a href="http://stackoverflow.com/questions/550470/overload-print-python/550477#550477">http://stackoverflow.com/questions/550470/overload-print-python/550477#550477</a> just told me i cant overload print in 2.x which is what i am using.</p>
26
2009-02-15T07:26:05Z
550,483
<p>I don't think you can overload print, but Python has a robust logging package that is highly customizable.</p> <p><a href="http://docs.python.org/library/logging.html" rel="nofollow">http://docs.python.org/library/logging.html</a></p>
3
2009-02-15T07:32:41Z
[ "python", "printing", "overloading" ]
overload print python
550,470
<p>Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.</p> <p>Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <a href="http://stackoverflow.com/questions/550470/overload-print-python/550477#550477">http://stackoverflow.com/questions/550470/overload-print-python/550477#550477</a> just told me i cant overload print in 2.x which is what i am using.</p>
26
2009-02-15T07:26:05Z
550,488
<p>Overloading <code>print</code> is a design feature of python 3.0 to address your lack of ability to do so in python 2.x.</p> <p>However, you can override sys.stdout. (<a href="http://code.activestate.com/recipes/119404/">example</a>.) Just assign it to another file-like object that does what you want.</p> <p>Alternatively, you could just pipe your script through the the unix <code>tee</code> command. <code>python yourscript.py | tee output.txt</code> will print to both stdout and to output.txt, but this will capture all output.</p>
26
2009-02-15T07:37:01Z
[ "python", "printing", "overloading" ]
overload print python
550,470
<p>Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.</p> <p>Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <a href="http://stackoverflow.com/questions/550470/overload-print-python/550477#550477">http://stackoverflow.com/questions/550470/overload-print-python/550477#550477</a> just told me i cant overload print in 2.x which is what i am using.</p>
26
2009-02-15T07:26:05Z
550,546
<p>Though you can't replace the <code>print</code> keyword (in Python 2.x <code>print</code> is a keyword), it's common practice to replace <code>sys.stdout</code> to do something similar to <code>print</code> overriding; for example, with an instance of <code>StringIO.StringIO</code>. This will capture all of the printed data in the <code>StringIO</code> instance, after which you can manipulate it.</p>
3
2009-02-15T08:53:28Z
[ "python", "printing", "overloading" ]
overload print python
550,470
<p>Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.</p> <p>Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <a href="http://stackoverflow.com/questions/550470/overload-print-python/550477#550477">http://stackoverflow.com/questions/550470/overload-print-python/550477#550477</a> just told me i cant overload print in 2.x which is what i am using.</p>
26
2009-02-15T07:26:05Z
688,816
<p>I came across the same problem.</p> <p>How about this:</p> <pre><code>class writer : def __init__(self, *writers) : self.writers = writers def write(self, text) : for w in self.writers : w.write(text) import sys saved = sys.stdout fout = file('out.log', 'w') sys.stdout = writer(sys.stdout, fout) print "There you go." sys.stdout = saved fout.close() </code></pre> <p>It worked like a charm for me. It was taken from <a href="http://mail.python.org/pipermail/python-list/2003-February/188788.html">http://mail.python.org/pipermail/python-list/2003-February/188788.html</a> </p>
9
2009-03-27T07:22:31Z
[ "python", "printing", "overloading" ]
overload print python
550,470
<p>Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.</p> <p>Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <a href="http://stackoverflow.com/questions/550470/overload-print-python/550477#550477">http://stackoverflow.com/questions/550470/overload-print-python/550477#550477</a> just told me i cant overload print in 2.x which is what i am using.</p>
26
2009-02-15T07:26:05Z
1,818,580
<p>I answered the same question <a href="http://stackoverflow.com/questions/770657/python-overridding-print/1818572#1818572">on a different SO question</a></p> <p>Essentially, simplest solution is to just redirect the output to stderr as follows, in the wsgi config file.</p> <pre><code>sys.stdout = sys.stderr </code></pre>
1
2009-11-30T08:51:41Z
[ "python", "printing", "overloading" ]
overload print python
550,470
<p>Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.</p> <p>Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <a href="http://stackoverflow.com/questions/550470/overload-print-python/550477#550477">http://stackoverflow.com/questions/550470/overload-print-python/550477#550477</a> just told me i cant overload print in 2.x which is what i am using.</p>
26
2009-02-15T07:26:05Z
10,106,489
<p>For those reviewing the previously dated answers, as of version release "Python 2.6" there is a new answer to the original poster's question.</p> <p>In Python 2.6 and up, you can disable the print statement in favor of the print function, and then override the print function with your own print function:</p> <pre><code>from __future__ import print_function # This must be the first statement before other statements. # You may only put a quoted or triple quoted string, # Python comments, other future statements, or blank lines before the __future__ line. try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): """My custom print() function.""" # Adding new arguments to the print function signature # is probably a bad idea. # Instead consider testing if custom argument keywords # are present in kwargs __builtin__.print('My overridden print() function!') return __builtin__.print(*args, **kwargs) </code></pre> <p>Of course you'll need to consider that this print function is only module wide at this point. You could choose to override <code>__builtin__.print</code>, but you'll need to save the original <code>__builtin__.print</code>; likely mucking with the <code>__builtin__</code> namespace.</p>
32
2012-04-11T13:06:25Z
[ "python", "printing", "overloading" ]
overload print python
550,470
<p>Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.</p> <p>Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <a href="http://stackoverflow.com/questions/550470/overload-print-python/550477#550477">http://stackoverflow.com/questions/550470/overload-print-python/550477#550477</a> just told me i cant overload print in 2.x which is what i am using.</p>
26
2009-02-15T07:26:05Z
15,590,040
<pre><code>class MovieDesc: name = "Name" genders = "Genders" country = "Country" def __str__(self): #Do whatever you want here return "Name: {0}\tGenders: {1} Country: {2} ".format(self.name,self.genders,self.country) ) </code></pre>
4
2013-03-23T17:45:25Z
[ "python", "printing", "overloading" ]
overload print python
550,470
<p>Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.</p> <p>Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <a href="http://stackoverflow.com/questions/550470/overload-print-python/550477#550477">http://stackoverflow.com/questions/550470/overload-print-python/550477#550477</a> just told me i cant overload print in 2.x which is what i am using.</p>
26
2009-02-15T07:26:05Z
21,959,061
<p>just thought I'd add my idea... suited my purposes of being able to run sthg in Eclipse and then run from the (Windows) CLI without getting encoding exceptions with each print statement. Whatever you do don't make EncodingStdout a subclass of class file: the line "self.encoding = encoding" would then result in the encoding attribute being None!</p> <p>NB one thing I found out during a day grappling with this stuff is that the encoding exception gets raised BEFORE getting to "print" or "write": it is when the parameterised string (i.e. "mondodod %s blah blah %s" % ( "blip", "blap" )) is constructed by... what??? the "framework"?</p> <pre><code>class EncodingStdout( object ): def __init__( self, encoding='utf-8' ): self.encoding = encoding def write_ln( self, *args ): if len( args ) &lt; 2: sys.__stdout__.write( args[ 0 ] + '\n' ) else: if not isinstance( args[ 0 ], basestring ): raise Exception( "first arg was %s, type %s" % ( args[ 0 ], type( args[ 0 ]) )) # if the default encoding is UTF-8 don't bother with encoding if sys.getdefaultencoding() != 'utf-8': encoded_args = [ args[ 0 ] ] for i in range( 1, len( args )): # numbers (for example) do not have an attribute "encode" if hasattr( args[ i ], 'encode' ): encoded_args.append( args[ i ].encode( self.encoding, 'replace' ) ) else: encoded_args.append( args[ i ]) args = encoded_args sys.__stdout__.write( args[ 0 ] % tuple( args[ 1 : ] ) + '\n' ) # write seems to need a flush sys.__stdout__.flush() def __getattr__( self, name ): return sys.__stdout__.__getattribute__( name ) print "=== A mondodod %s %s" % ( "été", "pluviôse, irritée contre la ville entière" ) sys.stdout = EncodingStdout() sys.stdout.write_ln( "=== B mondodod %s %s", "été", "pluviôse, irritée contre la ville entière" ) # convenience method def pr( *args ): sys.stdout.write_ln( *args ) pr( "=== C mondodod %s %s", "été", "pluviôse, irritée contre la ville entière" ) </code></pre>
1
2014-02-22T19:05:39Z
[ "python", "printing", "overloading" ]
overload print python
550,470
<p>Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.</p> <p>Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <a href="http://stackoverflow.com/questions/550470/overload-print-python/550477#550477">http://stackoverflow.com/questions/550470/overload-print-python/550477#550477</a> just told me i cant overload print in 2.x which is what i am using.</p>
26
2009-02-15T07:26:05Z
36,407,330
<p>For a very simple example, as of Python3.4 (haven't tested with older versions) this works well for me (placed at top of module):</p> <pre><code>def dprint(string): __builtins__.print("%f -- %s" % (time.time(), string)) print = dprint </code></pre> <p>Note, this only works if the string parameter is a str... YMMV</p>
0
2016-04-04T15:53:01Z
[ "python", "printing", "overloading" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
550,644
<p>I'm just going to start with a tip from myself :)</p> <p><strong>Use os.path.dirname() in settings.py to avoid hardcoded dirnames.</strong></p> <p>Don't hardcode path's in your settings.py if you want to run your project in different locations. Use the following code in settings.py if your templates and static files are located within the Django project directory:</p> <pre><code># settings.py import os PROJECT_DIR = os.path.dirname(__file__) ... STATIC_DOC_ROOT = os.path.join(PROJECT_DIR, "static") ... TEMPLATE_DIRS = ( os.path.join(PROJECT_DIR, "templates"), ) </code></pre> <p>Credits: I got this tip from the screencast '<a href="http://thisweekindjango.com/screencasts/episode/10/django-ground-episodes-1-and-2/" rel="nofollow">Django From the Ground Up</a>'.</p>
222
2009-02-15T10:15:52Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
551,114
<p>Use <a href="http://bitbucket.org/offline/django-annoying/wiki/Home" rel="nofollow">django-annoying's</a> <code>render_to</code> decorator instead of <code>render_to_response</code>.</p> <pre><code>@render_to('template.html') def foo(request): bars = Bar.objects.all() if request.user.is_authenticated(): return HttpResponseRedirect("/some/url/") else: return {'bars': bars} # equals to def foo(request): bars = Bar.objects.all() if request.user.is_authenticated(): return HttpResponseRedirect("/some/url/") else: return render_to_response('template.html', {'bars': bars}, context_instance=RequestContext(request)) </code></pre> <p>Edited to point out that returning an HttpResponse (such as a redirect) will short circuit the decorator and work just as you expect.</p>
119
2009-02-15T16:06:32Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
551,139
<p>I like to use the Python debugger pdb to debug Django projects.</p> <p>This is a helpful link for learning how to use it: <a href="http://www.ferg.org/papers/debugging_in_python.html" rel="nofollow">http://www.ferg.org/papers/debugging_in_python.html</a></p>
37
2009-02-15T16:20:26Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
551,158
<p>Use <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja2</a> alongside Django.</p> <p>If you find the Django template language extremely restricting (like me!) then you don't have to be stuck with it. Django is flexible, and the template language is loosely coupled to the rest of the system, so just plug-in another template language and use it to render your http responses!</p> <p>I use <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja2</a>, it's almost like a powered-up version of the django template language, it uses the same syntax, and allows you to use expressions in if statements! no more making a custom if-tags such as <code>if_item_in_list</code>! you can simply say <code>%{ if item in list %}</code>, or <code>{% if object.field &lt; 10 %}</code>.</p> <p>But that's not all; it has many more features to ease template creation, that I can't go though all of them in here.</p>
35
2009-02-15T16:30:50Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
551,499
<p>Add <code>assert False</code> in your view code to dump debug information.</p>
35
2009-02-15T20:06:58Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
551,615
<p>Install <a href="http://code.google.com/p/django-command-extensions">Django Command Extensions</a> and <a href="http://networkx.lanl.gov/pygraphviz/">pygraphviz</a> and then issue the following command to get a really nice looking Django model visualization:</p> <pre><code>./manage.py graph_models -a -g -o my_project.png </code></pre>
130
2009-02-15T21:18:14Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
558,401
<p>Don't hard-code your URLs! </p> <p>Use <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#id2" rel="nofollow">url names</a> instead, and the <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse" rel="nofollow"><code>reverse</code></a> function to get the URL itself.</p> <p>When you define your URL mappings, give names to your URLs. </p> <pre><code>urlpatterns += ('project.application.views' url( r'^something/$', 'view_function', name="url-name" ), .... ) </code></pre> <p>Make sure the name is unique per URL.</p> <p>I usually have a consistent format "project-appplication-view", e.g. "cbx-forum-thread" for a thread view.</p> <p><strong>UPDATE</strong> (shamelessly stealing <a href="http://stackoverflow.com/questions/550632/favorite-django-tips-features/560111#560111">ayaz's addition</a>):</p> <p>This name can be used in templates with the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url" rel="nofollow"><code>url</code> tag</a>.</p>
88
2009-02-17T19:34:58Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
559,972
<p>Don't write your own login pages. If you're using django.contrib.auth.</p> <p>The real, dirty secret is that if you're also using django.contrib.admin, and django.template.loaders.app_directories.load_template_source is in your template loaders, <strong>you can get your templates free too!</strong></p> <pre><code># somewhere in urls.py urlpatterns += patterns('django.contrib.auth', (r'^accounts/login/$','views.login', {'template_name': 'admin/login.html'}), (r'^accounts/logout/$','views.logout'), ) </code></pre>
80
2009-02-18T05:37:30Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
560,064
<p><a href="http://docs.djangoproject.com/en/dev/ref/generic-views/?from=olddocs#django-views-generic-list-detail-object-list" rel="nofollow">django.views.generic.list_detail.object_list</a> -- It provides all the logic &amp; template variables for pagination (one of those I've-written-that-a-thousand-times-now drudgeries). <a href="http://www.djangobook.com/en/2.0/chapter11/" rel="nofollow">Wrapping it</a> allows for any logic you need. This gem has saved me many hours of debugging off-by-one errors in my "Search Results" pages and makes the view code cleaner in the process.</p>
16
2009-02-18T06:44:49Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
560,111
<p>This adds to the reply above about <a href="http://stackoverflow.com/questions/550632/favorite-django-tips-features/558401#558401">Django URL names and reverse URL dispatching</a>.</p> <p>The URL names can also be effectively used within templates. For example, for a given URL pattern:</p> <pre><code>url(r'(?P&lt;project_id&gt;\d+)/team/$', 'project_team', name='project_team') </code></pre> <p>you can have the following in templates:</p> <pre><code>&lt;a href="{% url project_team project.id %}"&gt;Team&lt;/a&gt; </code></pre>
33
2009-02-18T07:07:30Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
562,998
<p>When I was starting out, I didn't know that there was a <a href="http://docs.djangoproject.com/en/dev/topics/pagination/#topics-pagination" rel="nofollow">Paginator</a>, make sure you know of its existence!!</p>
57
2009-02-18T21:54:03Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
709,180
<p>When trying to exchange data between Django and another application, <code>request.raw_post_data</code> is a good friend. Use it to receive and custom-process, say, XML data.</p> <p>Documentation: <a href="http://docs.djangoproject.com/en/dev/ref/request-response/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/request-response/</a></p>
37
2009-04-02T10:30:16Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
864,898
<p><code>django.db.models.get_model</code> does allow you to retrieve a model without importing it.</p> <p>James shows how handy it can be: <a href="http://www.b-list.org/weblog/2006/jun/07/django-tips-write-better-template-tags/" rel="nofollow">"Django tips: Write better template tags — Iteration 4 "</a>.</p>
19
2009-05-14T18:19:48Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
942,214
<p><a href="http://code.djangoproject.com/wiki/TemplatedForm" rel="nofollow">Render form via django template instead of as_(ul|table|p)()</a>.</p> <p>This article shows, how to use template to render CusstomForms instead of <code>as_p()</code>, <code>as_table()</code>...</p> <p>To make it work change </p> <ul> <li><code>from django import newforms as forms</code> <strong>to</strong> <code>from django import forms</code> </li> <li><code>from django.newforms.forms import BoundField</code> <strong>to</strong> <code>from django.forms.forms import BoundField</code></li> </ul>
5
2009-06-02T22:22:35Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
942,237
<p>Use <a href="http://code.google.com/p/isapi-wsgi/" rel="nofollow">isapi-wsgi</a> and <a href="http://code.google.com/p/django-pyodbc/" rel="nofollow">django-pyodbc</a> to run Django on Windows using IIS and SQL Server!</p>
1
2009-06-02T22:27:43Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
942,426
<p>The <a href="http://docs.djangoproject.com/en/dev/ref/contrib/webdesign/#ref-contrib-webdesign" rel="nofollow">webdesign app</a> is very useful when starting to design your website. Once imported, you can add this to generate sample text:</p> <pre><code>{% load webdesign %} {% lorem 5 p %} </code></pre>
19
2009-06-02T23:32:21Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
946,397
<p>There's a set of custom tags I use all over my site's templates. Looking for a way to autoload it (DRY, remember?), I found the following:</p> <pre><code>from django import template template.add_to_builtins('project.app.templatetags.custom_tag_module') </code></pre> <p>If you put this in a module that's loaded by default (your main urlconf for instance), you'll have the tags and filters from your custom tag module available in any template, without using <code>{% load custom_tag_module %}</code>.</p> <p>The argument passed to <code>template.add_to_builtins()</code> can be any module path; your custom tag module doesn't have to live in a specific application. For example, it can also be a module in your project's root directory (eg. <code>'project.custom_tag_module'</code>).</p>
103
2009-06-03T18:34:02Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
946,443
<p><a href="http://pypi.python.org/pypi/virtualenv#what-it-does" rel="nofollow">Virtualenv</a> + Python = life saver if you are working on multiple Django projects and there is a possibility that they all don't depend on the same version of Django/an application.</p>
97
2009-06-03T18:44:29Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
946,497
<p>Use <a href="http://github.com/robhudson/django-debug-toolbar/">django debug toolbar</a>. For example, it allows to view all SQL queries performed while rendering view and you can also view stacktrace for any of them.</p>
82
2009-06-03T18:53:46Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,018,895
<p>I don't have enough reputation to reply to the comment in question, but it's important to note that if you're going to use <a href="http://en.wikipedia.org/wiki/Jinja%5F%28template%5Fengine%29" rel="nofollow">Jinja</a>, it does NOT support the '-' character in template block names, while Django does. This caused me a lot of problems and wasted time trying to track down the very obscure error message it generated.</p>
20
2009-06-19T16:35:18Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,057,512
<p>Just found this link: <a href="http://lincolnloop.com/django-best-practices/#table-of-contents" rel="nofollow">http://lincolnloop.com/django-best-practices/#table-of-contents</a> - "Django Best Practices".</p>
13
2009-06-29T10:01:07Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,067,267
<p>From the <a href="http://docs.djangoproject.com/en/dev/ref/django-admin/" rel="nofollow">django-admin documentation</a>:</p> <p>If you use the Bash shell, consider installing the Django bash completion script, which lives in <code>extras/django_bash_completion</code> in the Django distribution. It enables tab-completion of <code>django-admin.py</code> and <code>manage.py</code> commands, so you can, for instance...</p> <ul> <li>Type <code>django-admin.py</code>.</li> <li>Press [TAB] to see all available options.</li> <li>Type <code>sql</code>, then [TAB], to see all available options whose names start with <code>sql</code>.</li> </ul>
41
2009-07-01T04:27:35Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,300,107
<h2>Context processors are awesome.</h2> <p>Say you have a different user model and you want to include that in every response. Instead of doing this:</p> <pre><code>def myview(request, arg, arg2=None, template='my/template.html'): ''' My view... ''' response = dict() myuser = MyUser.objects.get(user=request.user) response['my_user'] = myuser ... return render_to_response(template, response, context_instance=RequestContext(request)) </code></pre> <p>Context processes give you the ability to pass any variable to your templates. I typically put mine in <code>'my_project/apps/core/context.py</code>:</p> <pre><code>def my_context(request): try: return dict(my_user=MyUser.objects.get(user=request.user)) except ObjectNotFound: return dict(my_user='') </code></pre> <p>In your <code>settings.py</code> add the following line to your <code>TEMPLATE_CONTEXT_PROCESSORS</code></p> <pre><code>TEMPLATE_CONTEXT_PROCESSORS = ( 'my_project.apps.core.context.my_context', ... ) </code></pre> <p>Now every time a request is made it includes the <code>my_user</code> key automatically.</p> <h2>Also <a href="http://docs.djangoproject.com/en/dev/topics/signals/" title="Django Signals">signals</a> win.</h2> <p>I wrote a blog post about this a few months ago so I'm just going to cut and paste:</p> <p>Out of the box Django gives you several signals that are incredibly useful. You have the ability to do things pre and post save, init, delete, or even when a request is being processed. So lets get away from the concepts and demonstrate how these are used. Say we’ve got a blog</p> <pre><code>from django.utils.translation import ugettext_lazy as _ class Post(models.Model): title = models.CharField(_('title'), max_length=255) body = models.TextField(_('body')) created = models.DateTimeField(auto_now_add=True) </code></pre> <p>So somehow you want to notify one of the many blog-pinging services we’ve made a new post, rebuild the most recent posts cache, and tweet about it. Well with signals you have the ability to do all of this without having to add any methods to the Post class.</p> <pre><code>import twitter from django.core.cache import cache from django.db.models.signals import post_save from django.conf import settings def posted_blog(sender, created=None, instance=None, **kwargs): ''' Listens for a blog post to save and alerts some services. ''' if (created and instance is not None): tweet = 'New blog post! %s' instance.title t = twitter.PostUpdate(settings.TWITTER_USER, settings.TWITTER_PASSWD, tweet) cache.set(instance.cache_key, instance, 60*5) # send pingbacks # ... # whatever else else: cache.delete(instance.cache_key) post_save.connect(posted_blog, sender=Post) </code></pre> <p>There we go, by defining that function and using the post_init signal to connect the function to the Post model and execute it after it has been saved.</p>
67
2009-08-19T13:53:50Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,346,574
<p>I learned this one from the documentation for the <a href="http://code.google.com/p/sorl-thumbnail/" rel="nofollow">sorl-thumbnails</a> app. You can use the "as" keyword in template tags to use the results of the call elsewhere in your template.</p> <p>For example:</p> <pre><code>{% url image-processor uid as img_src %} &lt;img src="{% thumbnail img_src 100x100 %}"/&gt; </code></pre> <p>This is mentioned in passing in the Django templatetag documentation, but in reference to loops only. They don't call out that you can use this elsewhere (anywhere?) as well.</p>
18
2009-08-28T11:59:46Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,359,196
<p>Since Django "views" only need to be callables that return an HttpResponse, you can easily create class-based views like those in Ruby on Rails and other frameworks.</p> <p>There are several ways to create class-based views, here's my favorite:</p> <pre><code>from django import http class RestView(object): methods = ('GET', 'HEAD') @classmethod def dispatch(cls, request, *args, **kwargs): resource = cls() if request.method.lower() not in (method.lower() for method in resource.methods): return http.HttpResponseNotAllowed(resource.methods) try: method = getattr(resource, request.method.lower()) except AttributeError: raise Exception("View method `%s` does not exist." % request.method.lower()) if not callable(method): raise Exception("View method `%s` is not callable." % request.method.lower()) return method(request, *args, **kwargs) def get(self, request, *args, **kwargs): return http.HttpResponse() def head(self, request, *args, **kwargs): response = self.get(request, *args, **kwargs) response.content = '' return response </code></pre> <p>You can add all sorts of other stuff like conditional request handling and authorization in your base view.</p> <p>Once you've got your views setup your urls.py will look something like this:</p> <pre><code>from django.conf.urls.defaults import * from views import MyRestView urlpatterns = patterns('', (r'^restview/', MyRestView.dispatch), ) </code></pre>
27
2009-08-31T20:12:58Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,407,331
<p>Use <a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow">signals</a> to add accessor-methods on-the-fly.</p> <p>I saw this technique in <a href="http://code.google.com/p/django-photologue" rel="nofollow">django-photologue</a>: For any Size object added, the post_init signal will add the corresponding methods to the Image model. If you add a site <em>giant</em>, the methods to retrieve the picture in giant resolution will be <code>image.get_giant_url()</code>.</p> <p>The methods are generated by calling <code>add_accessor_methods</code> from the <code>post_init</code> signal:</p> <pre><code>def add_accessor_methods(self, *args, **kwargs): for size in PhotoSizeCache().sizes.keys(): setattr(self, 'get_%s_size' % size, curry(self._get_SIZE_size, size=size)) setattr(self, 'get_%s_photosize' % size, curry(self._get_SIZE_photosize, size=size)) setattr(self, 'get_%s_url' % size, curry(self._get_SIZE_url, size=size)) setattr(self, 'get_%s_filename' % size, curry(self._get_SIZE_filename, size=size)) </code></pre> <p>See the <a href="http://code.google.com/p/django-photologue/source/browse/trunk/photologue/models.py" rel="nofollow">source code of photologue.models</a> for real-world usage.</p>
11
2009-09-10T19:46:16Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,656,759
<p>Use <strong><a href="http://pypi.python.org/pypi/djangorecipe" rel="nofollow">djangorecipe</a></strong> to manage your project</p> <ul> <li>If you're writing a new app, this recipe makes testing it outside of a project really easy</li> <li>It allows you to manage dependencies for a project (e.g. what version of some app it should depend on)</li> </ul> <p>All you have to do to get started is this:</p> <ol> <li>Create a folder for your new website (or library)</li> <li>Create a buildout.cfg with following content in it:</li> </ol> <pre><code> [buildout] parts=django [django] recipe=djangorecipe version=1.1.1 project=my_new_site settings=development </code></pre> <ol> <li>Grab a bootstrap.py to get a local installation of buildout and place it within your directory. You can either go with the <a href="http://www.google.at/search?q=buidlout+bootstrap.py&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla%3aen-US%3aofficial&amp;client=firefox-a" rel="nofollow">official one</a> (sorry, Markdown didn't like part of the full link :-/ ) or with one that uses distribute instead of setuptools as described by <a href="http://reinout.vanrees.org/weblog/2009/10/15/distribute-works-with-buildout.html" rel="nofollow">Reinout van Rees</a>.</li> <li><code>python bootstrap.py</code> (or <code>python bootstrap_dev.py</code> if you want to use distribute).</li> <li><code>./bin/buildout</code></li> </ol> <p>That's it. You should now have a new folder "my_new_site", which is your new django 1.1.1 project, and in ./bin you will find the <code>django</code>-script which replaces the manage.py on a normal installation. </p> <p>What's the benefit? Let's say you want to use something like django-comment-spamfighter in your project. All you'd have to do is change your buildout.cfg to something like this:</p> <pre><code> [buildout] parts=django [django] recipe=djangorecipe version=1.1.1 project=my_new_site settings=development eggs= django-comments-spamfighter==0.4 </code></pre> <p>Note that all I did was to add the last 2 lines which say, that the django-part should also have the django-comments-spamfighter package in version 0.4. The next time you run <code>./bin/buildout</code>, buildout will download that package and modify ./bin/django to add it to its PYTHONPATH.</p> <p>djangorecipe is also suited for deploying your project with mod_wsgi. Just add the <code>wsgi=true</code> setting to the django-part of your buildout.cfg and a "django.wsgi" will appear in your ./bin folder :-)</p> <p>And if you set the <code>test</code> option to a list of applications, the djangorecipe will create a nice wrapper for you that runs all the tests for the listed application in your project.</p> <p>If you want to develop a single app in a standalone environment for debugging etc., Jakob Kaplan-Moss has a quite complete tutorial on <a href="http://jacobian.org/writing/django-apps-with-buildout/" rel="nofollow">his blog</a></p>
5
2009-11-01T09:47:20Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,735,782
<p>Instead of using <code>render_to_response</code> to bind your context to a template and render it (which is what the Django docs usually show) use the generic view <a href="http://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-simple-direct-to-template" rel="nofollow"><code>direct_to_template</code></a>. It does the same thing that <code>render_to_response</code> does but it also automatically adds RequestContext to the template context, implicitly allowing context processors to be used. You can do this manually using <code>render_to_response</code>, but why bother? It's just another step to remember and another LOC. Besides making use of context processors, having RequestContext in your template allows you to do things like:</p> <pre><code>&lt;a href="{{MEDIA_URL}}images/frog.jpg"&gt;A frog&lt;/a&gt; </code></pre> <p>which is very useful. In fact, +1 on generic views in general. The Django docs mostly show them as shortcuts for not even having a views.py file for simple apps, but you can also use them inside your own view functions:</p> <pre><code>from django.views.generic import simple def article_detail(request, slug=None): article = get_object_or_404(Article, slug=slug) return simple.direct_to_template(request, template="articles/article_detail.html", extra_context={'article': article} ) </code></pre>
22
2009-11-14T22:15:03Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,774,722
<p>Instead of running the Django dev server on localhost, run it on a proper network interface. For example:</p> <pre><code>python manage.py runserver 192.168.1.110:8000 </code></pre> <p>or </p> <pre><code>python manage.py runserver 0.0.0.0:8000 </code></pre> <p>Then you can not only easily use Fiddler (<a href="http://www.fiddler2.com/fiddler2/" rel="nofollow">http://www.fiddler2.com/fiddler2/</a>) or another tool like HTTP Debugger (<a href="http://www.httpdebugger.com/" rel="nofollow">http://www.httpdebugger.com/</a>) to inspect your HTTP headers, but you can also access your dev site from other machines on your LAN to test.</p> <p>Make sure you are protected by a firewall though, although the dev server is minimal and relatively safe.</p>
9
2009-11-21T06:29:49Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,837,525
<p>Use <a href="http://ipython.scipy.org/moin/" rel="nofollow">IPython</a> to jump into your code at any level and debug using the power of IPython. Once you have installed IPython just put this code in wherever you want to debug: </p> <pre><code>from IPython.Shell import IPShellEmbed; IPShellEmbed()() </code></pre> <p>Then, refresh the page, go to your runserver window and you will be in an interactive IPython window.</p> <p>I have a snippet set up in TextMate so I just type ipshell and hit tab. I couldn't live without it.</p>
47
2009-12-03T03:55:57Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
1,837,571
<p>This is a really easy way to never have to import another one of your models again in your python shell.</p> <p>First, install <a href="http://ipython.scipy.org/moin/" rel="nofollow">IPython</a> (If you don't use IPython, what's wrong with you?). Next, create a python script, ipythonrc.py, in your django project directory with the following code in it:</p> <pre><code>from django.db.models.loading import get_models for m in get_models(): globals()[m.__name__] = m #NOTE: if you have two models with the same name you'll only end up with one of them </code></pre> <p>Then, in your ~/.ipython/ipythonrc file, put the following code in the "Python files to load and execute" section:</p> <pre><code>execfile /path/to/project/ipythonrc.py </code></pre> <p>Now every time you start up IPython or run <code>./manage.py shell</code> you will have all your models already imported and ready to use. No need to ever import another model again. </p> <p>You can also put any other code you execute a lot in your ipythonrc.py file to save yourself time.</p>
4
2009-12-03T04:08:47Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
2,093,549
<p>Everybody knows there is a development server you can run with "manage.py runserver", but did you know that there is a development view for serving static files (CSS / JS / IMG) as well ?</p> <p>Newcomers are always puzzled because Django doesn't come with any way to serve static files. This is because the dev team think it is the job for a real life Web server.</p> <p>But when developing, you may not want to set up Apache + mod_wisgi, it's heavy. Then you can just add the following to urls.py:</p> <pre><code>(r'^site_media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': '/path/to/media'}), </code></pre> <p>Your CSS / JS / IMG will be available at www.yoursite.com/site_media/.</p> <p>Of course, don't use it in a production environment.</p>
19
2010-01-19T12:57:39Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
2,260,327
<p>Run a development SMTP server that will just output whatever is sent to it (if you don't want to actually install SMTP on your dev server.)</p> <p>command line:</p> <pre><code>python -m smtpd -n -c DebuggingServer localhost:1025 </code></pre>
43
2010-02-14T06:26:28Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
2,740,163
<p>Use <code>wraps</code> decorator in custom views decorators to preserve view's name, module and docstring. E.g.</p> <pre><code>try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.3, 2.4 fallback. def view_decorator(fun): @wraps(fun) def wrapper(): # here goes your decorator's code return wrapper </code></pre> <p><strong>Beware</strong>: will not work on a class-based views (those with <code>__call__</code> method definition), if the author hasn't defined a <code>__name__</code> property. As a workaround use:</p> <pre><code>from django.utils.decorators import available_attrs ... @wraps(fun, assigned=available_attrs(fun)) </code></pre>
7
2010-04-29T19:22:46Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
2,751,177
<p><strong>Changing Django form field properties on init</strong></p> <p>Sometimes it's useful to pass extra arguments to a Form class.</p> <pre><code>from django import forms from mymodels import Group class MyForm(forms.Form): group=forms.ModelChoiceField(queryset=None) email=forms.EmailField() some_choices=forms.ChoiceField() def __init__(self,my_var,*args,**kwrds): super(MyForm,self).__init__(*args,**kwrds) self.fields['group'].queryset=Group.objects.filter(...) self.fields['email'].widget.attrs['size']='50' self.fields['some_choices']=[[x,x] for x in list_of_stuff] </code></pre> <p>source: <a href="http://snippets.dzone.com/posts/show/7936" rel="nofollow">Dzone snippets</a></p>
4
2010-05-01T18:51:42Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
2,830,887
<p><a href="http://www.jetbrains.com/pycharm/" rel="nofollow">PyCharm IDE</a> is a nice environment to code and especially debug, with built-in support for Django.</p>
16
2010-05-13T23:04:24Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
2,832,479
<p>The <a href="http://github.com/robhudson/django-debug-toolbar" rel="nofollow">Django Debug Toolbar</a> is really fantastic. Not really a toolbar, it actually brings up a sidepane that tells you all sorts of information about what brought you the page you're looking at - DB queries, the context variables sent to the template, signals, and more. </p>
7
2010-05-14T07:23:52Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
3,247,524
<p>Use <a href="http://djangorestmodel.sourceforge.net/" rel="nofollow">xml_models</a> to create Django models that use an XML REST API backend (instead of a SQL one). This is very useful especially when modelling third party APIs - you get all the same QuerySet syntax that you're used to. You can install it from PyPI.</p> <p>XML from an API:</p> <pre><code>&lt;profile id=4&gt; &lt;email&gt;joe@example.com&lt;/email&gt; &lt;first_name&gt;Joe&lt;/first_name&gt; &lt;last_name&gt;Example&lt;/last_name&gt; &lt;date_of_birth&gt;1975-05-15&lt;/date_of_birth&gt; &lt;/profile&gt; </code></pre> <p>And now in python:</p> <pre><code>class Profile(xml_models.Model): user_id = xml_models.IntField(xpath='/profile/@id') email = xml_models.CharField(xpath='/profile/email') first = xml_models.CharField(xpath='/profile/first_name') last = xml_models.CharField(xpath='/profile/last_name') birthday = xml_models.DateField(xpath='/profile/date_of_birth') finders = { (user_id,): settings.API_URL +'/api/v1/profile/userid/%s', (email,): settings.API_URL +'/api/v1/profile/email/%s', } profile = Profile.objects.get(user_id=4) print profile.email # would print 'joe@example.com' </code></pre> <p>It can also handle relationships and collections. We use it every day in heavily used production code, so even though it's beta it's very usable. It also has a good set of stubs that you can use in your tests.</p> <p>(Disclaimer: while I'm not the author of this library, I am now a committer, having made a few minor commits)</p>
14
2010-07-14T15:06:49Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
3,262,408
<p>Use reverse in your urlconf.</p> <p>This is one of those tricks where I don't understand why it isn't the default.</p> <p>Here's a link to where I picked it up: <a href="http://andr.in/2009/11/21/calling-reverse-in-django/">http://andr.in/2009/11/21/calling-reverse-in-django/</a></p> <p>Here's the code snippet:</p> <blockquote><pre><code>from django.conf.urls.defaults import * from django.core.urlresolvers import reverse from django.utils.functional import lazy from django.http import HttpResponse reverse_lazy = lazy(reverse, str) urlpatterns = patterns('', url(r'^comehere/', lambda request: HttpResponse('Welcome!'), name='comehere'), url(r'^$', 'django.views.generic.simple.redirect_to', {'url': reverse_lazy('comehere')}, name='root') )</code></pre></blockquote>
5
2010-07-16T06:27:08Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
4,007,017
<p>Create dynamic models for sets of legacy tables with the same structure:</p> <pre><code>class BaseStructure(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) class Meta: abstract=True class DynamicTable(models.Model): table_name = models.CharField(max_length=20) def get_model(self): class Meta: managed=False table_name=self.table_name attrs = {} attrs['Meta'] = Meta # type(new_class_name, (base,classes), {extra: attributes}) dynamic_class = type(self.table_name, (BaseStructure,), attrs) return dynamic_class customers = DynamicTable.objects.get(table_name='Customers').get_model() me = customers.objects.get(name='Josh Smeaton') me.address = 'Over the rainbow' me.save() </code></pre> <p>This assumes that you have legacy tables with the same structure. Instead of creating a model to wrap each of the tables, you define one base model, and dynamically construct the class needed to interact with a specific table.</p>
1
2010-10-24T03:17:55Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
4,007,078
<h1>Remove Database Access Information from settings.py</h1> <p>One thing I've done in my Django site's <code>settings.py</code> is load database access info from a file in <code>/etc</code>. This way the access setup (database host, port, username, password) can be different for each machine, and sensitive info like the password isn't in my project's repository. You might want to restrict access to the workers in a similar manner, by making them connect with a different username.</p> <p>You could also pass in the database connection information, or even just a key or path to a configuration file, via environment variables, and handle it in <code>settings.py</code>.</p> <p>For example, here's how I pull in my database configuration file:</p> <pre><code>g = {} dbSetup = {} execfile(os.environ['DB_CONFIG'], g, dbSetup) if 'databases' in dbSetup: DATABASES = dbSetup['databases'] else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # ... } } </code></pre> <p>Needless to say, you need to make sure that the file in <code>DB_CONFIG</code> is not accessible to any user besides the db admins and Django itself. The default case should refer Django to a developer's own test database. There may also be a better solution using the <code>ast</code> module instead of <code>execfile</code>, but I haven't researched it yet.</p> <p>Another thing I do is use separate users for DB admin tasks vs. everything else. In my <code>manage.py</code>, I added the following preamble:</p> <pre><code># Find a database configuration, if there is one, and set it in the environment. adminDBConfFile = '/etc/django/db_admin.py' dbConfFile = '/etc/django/db_regular.py' import sys import os def goodFile(path): return os.path.isfile(path) and os.access(path, os.R_OK) if len(sys.argv) &gt;= 2 and sys.argv[1] in ["syncdb", "dbshell", "migrate"] \ and goodFile(adminDBConfFile): os.environ['DB_CONFIG'] = adminDBConfFile elif goodFile(dbConfFile): os.environ['DB_CONFIG'] = dbConfFile </code></pre> <p>Where the config in <code>/etc/django/db_regular.py</code> is for a user with access to only the Django database with SELECT, INSERT, UPDATE, and DELETE, and <code>/etc/django/db_admin.py</code> is for a user with these permissions plus CREATE, DROP, INDEX, ALTER, and LOCK TABLES. (The <code>migrate</code> command is from <a href="http://south.aeracode.org/" rel="nofollow">South</a>.) This gives me some protection from Django code messing with my schema at runtime, and it limits the damage an SQL injection attack can cause (though you should still check and filter all user input).</p> <p>(Copied from my answer to <a href="http://stackoverflow.com/questions/3884249/django-celery-database-for-models-on-producer-and-worker/3884535#3884535">another question</a>)</p>
11
2010-10-24T03:41:54Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
4,861,267
<p>The <code>./manage.py runserver_plus</code> facilty which comes with <a href="http://code.google.com/p/django-command-extensions/" rel="nofollow">django_extensions</a> is truly awesome. </p> <p>It creates an enhanced debug page that, amongst other things, uses the Werkzeug debugger to create interactive debugging consoles for each point in the stack (see screenshot). It also provides a very useful convenience debugging method <code>dump()</code> for displaying information about an object/frame.</p> <p><img src="http://i.stack.imgur.com/M6dJb.jpg" alt="enter image description here"></p> <p>To install, you can use pip:</p> <pre><code>pip install django_extensions pip install Werkzeug </code></pre> <p>Then add <code>'django_extensions'</code> to your <code>INSTALLED_APPS</code> tuple in <code>settings.py</code> and start the development server with the new extension:</p> <pre><code>./manage.py runserver_plus </code></pre> <p>This will change the way you debug.</p>
40
2011-02-01T10:11:58Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
4,888,160
<p>Using an 'apps' folder to organize your applications without editing PYTHONPATH</p> <p>This has come handy when I want to organize my folders like this:</p> <pre><code>apps/ foo/ bar/ site/ settings.py urls.py </code></pre> <p>without overwritting PYTHONPATH or having to add <strong>apps</strong> to every import like:</p> <pre><code>from apps.foo.model import * from apps.bar.forms import * </code></pre> <p>In your settings.py add</p> <pre><code>import os import sys PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(PROJECT_ROOT, "apps")) </code></pre> <p>and you are ready to go :-)</p> <p>I saw this at <a href="http://codespatter.com/2009/04/10/how-to-add-locations-to-python-path-for-reusable-django-apps/" rel="nofollow">http://codespatter.com/2009/04/10/how-to-add-locations-to-python-path-for-reusable-django-apps/</a></p>
6
2011-02-03T15:37:33Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
5,546,778
<p>Instead of evaluating whole queryset to check whether you got back any results, use .exists() in Django 1.2+ and .count() for previous versions.</p> <p>Both exists() and count() clears order by clauses and retrieves a single integer from DB. However exists() will always return 1 where as count may return higher values on which limits will be applied manually. Source for <a href="http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py#L412" rel="nofollow">has_result</a> used in exists() and <a href="http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py#L377" rel="nofollow">get_count</a> used in count() for the curious.</p> <p>Since they both return a single integer, there's no model instantiation, loading model attributes in memory and no large TextFields being passed between your DB and app.</p> <p>If you have already evaluated the query, .count() computes len(cached_result) and .exists() computes bool(cached_result)</p> <p><strong>Not efficient - Example 1</strong></p> <pre><code>books = Books.objects.filter(author__last_name='Brown') if books: # Do something </code></pre> <p><strong>Not efficient - Example 2</strong></p> <pre><code>books = Books.objects.filter(author__last_name='Brown') if len(books): # Do something </code></pre> <p><strong>Efficient - Example 1</strong></p> <pre><code>books = Books.objects.filter(author__last_name='Brown') if books.count(): # Do something </code></pre> <p><strong>Efficient - Example 2</strong></p> <pre><code>books = Books.objects.filter(author__last_name='Brown') if books.exists(): # Do something </code></pre>
12
2011-04-05T03:12:34Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
5,557,751
<p><code>django_extensions</code> from <a href="https://github.com/django-extensions/django-extensions" rel="nofollow">https://github.com/django-extensions/django-extensions</a> is just great.</p> <p>Few nice <code>./manage.py</code> commands:</p> <ul> <li><code>shell_plus</code> - autoimports models from all INSTALLED_APPS</li> <li><code>show_urls</code> - prints all urls defined in all apps in project</li> <li><code>runscript</code> - runs any script in project context (you can use models and other Django-related modules)</li> </ul>
2
2011-04-05T19:59:33Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
5,753,606
<p>PyCharm and Wingware IDE is great tool if you have money to pay for the license. </p> <p>Since I am a poor developer, I use <a href="http://pydev.org/" rel="nofollow">PyDev</a> with <a href="http://www.eclipse.org/" rel="nofollow">Eclipse</a>. </p>
2
2011-04-22T08:22:38Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
5,757,092
<p>When passing variables from a view to a template the response dictionary can become tedious to type out. I find it nice to just pass all the local variables at once using <code>locals()</code> .</p> <pre><code>def show_thing(request, thing_id): thing = Thing.objects.get(pk=thing_id) return render_to_response('templates/things/show.html', locals()) </code></pre> <p>(Not a hidden feature per se but nevertheless helpful when new to Python and or Django.)</p> <p>Edit: Obviously it's better to be explicit than implicit but this approach can be helpful during development.</p>
0
2011-04-22T15:40:32Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
5,809,809
<p>Use database migrations. Use <a href="http://south.aeracode.org" rel="nofollow">South</a>.</p>
14
2011-04-27T19:59:16Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
6,008,305
<p>A bit late to the party. But Django Canvas has recently come out and it deserves a place here.</p> <p>Don't start your project with <code>django-admin.py startproject</code>. Instead you can use something like <a href="http://djangocanvas.com" rel="nofollow">Django Canvas</a> to help piece together a blank project with the modules you need.</p> <p>You go to that site, tick some options and then download a blank project, so simple.</p> <p>It has all the common things like South schema migrations and Command Extensions as well as a lot of other best practices mentioned here. Plus it has a great <code>start.sh/shart.bat</code> script that will install python, virtualenv, pip, django and whatever you need to start from a fresh copy of windows, osx or linux.</p>
1
2011-05-15T12:13:44Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
6,169,597
<p>If you make changes into model</p> <pre><code>./manage.py dumpdata appname &gt; appname_data.json ./manage.py reset appname django-admin.py loaddata appname_data.json </code></pre>
12
2011-05-29T18:31:22Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
6,326,248
<p><strong>dir() &amp; raise ValueError()</strong></p> <p>For debugging / exploring the state of things during development, I use the following trick:</p> <pre><code>... to_see = dir(inspect_this_thing) to_see2 = inspect_this_thing.some_attribute raise ValueError("Debugging") ... </code></pre> <p>This is especially helpful when you're working on parts of django that aren't particularly well documented (form.changed_fields is one I used this on recently).</p> <p><strong>locals().</strong> </p> <p>Instead of writing out every variable for the template context, use the python builtin locals() command which creates a dictionary for you:</p> <pre><code>#This is tedious and not very DRY return render_to_response('template.html', {"var1": var1, "var2":var2}, context_instance=RequestContext(request)) #95% of the time this works perfectly return render_to_response('template.html', locals(), context_instance=RequestContext(request)) #The other 4.99% render_dict = locals() render_dict['also_needs'] = "this value" return render_to_response('template.html', render_dict, context_instance=RequestContext(request)) </code></pre>
0
2011-06-13T02:54:49Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
7,140,786
<p>Automatically set 'DEBUG' attribute on production environment (settings.py)</p> <pre><code>import socket if socket.gethostname() == 'productionserver.com': DEBUG = False else: DEBUG = True </code></pre> <p>By: <a href="http://nicksergeant.com/2008/automatically-setting-debug-in-your-django-app-based-on-server-hostname/" rel="nofollow">http://nicksergeant.com/2008/automatically-setting-debug-in-your-django-app-based-on-server-hostname/</a></p>
5
2011-08-21T20:05:03Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
8,065,577
<p>Django hasn't got app settings, so i made my own app_settings.py detection. At the bottom of the settings.py i added this code:</p> <pre><code>import sys, os # Append application settings without triggering the __init__. for installed_app in INSTALLED_APPS: # Ignore django applications if not installed_app.startswith('django.'): # Find the app (and the settings file) for path in sys.path: path = os.path.join(path, installed_app, 'app_settings.py') if os.path.isfile(path): # Application settings found exec open(path).read() </code></pre> <p>It detects app_settings.py in all the INSTALLED_APPS. Instead of importing it, it will read the contents of the app_settings file and will execute it inline. If app_settings is imported directly all sort of Django import errors will be raised (because Django isn't initialized yet).</p> <p>So my app/app_settings.py will look like this:</p> <pre><code>MIDDLEWARE_CLASSES += ( 'app.middleware.FancyMiddleware', ) </code></pre> <p>Now the application only has to be added to the INSTALLED_APPS, instead of finding all application settings and add them to the settings.py (middleware, urls...)</p> <p>Note: It would be better if Django had a hook to append extra settings, so application settings could be added on startup (or in runtime).</p>
0
2011-11-09T13:17:37Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
8,147,991
<p>Use asynchronous tasks. Use <a href="http://celeryproject.org/" rel="nofollow">Celery</a></p>
1
2011-11-16T07:14:08Z
[ "python", "django", "hidden-features" ]
Favorite Django Tips & Features?
550,632
<p>Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.</p> <ul> <li>Please, include only one tip per answer.</li> <li>Add Django version requirements if there are any.</li> </ul>
309
2009-02-15T10:06:22Z
8,512,853
<p>Read <a href="http://thebuild.com/presentations/unbreaking-django.pdf" rel="nofollow">Unbreaking Django</a> if you haven't already. It contains <em>lots</em> of useful information regarding django pitfalls.</p>
1
2011-12-14T22:48:04Z
[ "python", "django", "hidden-features" ]
Cross-platform way to get PIDs by process name in python
550,653
<p>Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using <strong>python</strong> or <strong>jython</strong>?</p> <ol> <li>I want something like <code>pidof</code> but in python. (I don't have <code>pidof</code> anyway.)</li> <li>I can't parse <code>/proc</code> because it might be unavailable (on HP-UX).</li> <li>I do not want to run <code>os.popen('ps')</code> and parse the output because I think it is ugly (field sequence may be different in different OS).</li> <li>Target platforms are Solaris, HP-UX, and maybe others.</li> </ol>
36
2009-02-15T10:23:56Z
550,672
<p>I don't think you will be able to find a purely python-based, portable solution without using /proc or command line utilities, at least not in python itself. Parsing os.system is not ugly - someone has to deal with the multiple platforms, be it you or someone else. Implementing it for the OS you are interested in should be fairly easy, honestly.</p>
3
2009-02-15T10:35:56Z
[ "python", "cross-platform", "jython", "hp-ux" ]
Cross-platform way to get PIDs by process name in python
550,653
<p>Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using <strong>python</strong> or <strong>jython</strong>?</p> <ol> <li>I want something like <code>pidof</code> but in python. (I don't have <code>pidof</code> anyway.)</li> <li>I can't parse <code>/proc</code> because it might be unavailable (on HP-UX).</li> <li>I do not want to run <code>os.popen('ps')</code> and parse the output because I think it is ugly (field sequence may be different in different OS).</li> <li>Target platforms are Solaris, HP-UX, and maybe others.</li> </ol>
36
2009-02-15T10:23:56Z
550,819
<p>First, Windows (in all it's incarnations) is a non-standard OS.</p> <p>Linux (and most proprietary unixen) are POSIX-compliant standard operating systems.</p> <p>The C libraries reflect this dichotomy. Python reflects the C libraries.</p> <p>There is no "cross-platform" way to do this. You have to hack up something with <a href="http://www.python.org/doc/2.5.2/lib/module-ctypes.html" rel="nofollow">ctypes</a> for a particular release of Windows (XP or Vista)</p>
3
2009-02-15T12:43:05Z
[ "python", "cross-platform", "jython", "hp-ux" ]
Cross-platform way to get PIDs by process name in python
550,653
<p>Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using <strong>python</strong> or <strong>jython</strong>?</p> <ol> <li>I want something like <code>pidof</code> but in python. (I don't have <code>pidof</code> anyway.)</li> <li>I can't parse <code>/proc</code> because it might be unavailable (on HP-UX).</li> <li>I do not want to run <code>os.popen('ps')</code> and parse the output because I think it is ugly (field sequence may be different in different OS).</li> <li>Target platforms are Solaris, HP-UX, and maybe others.</li> </ol>
36
2009-02-15T10:23:56Z
557,021
<p>There isn't, I'm afraid. Processes are uniquely identified by pid not by name. If you really must find a pid by name, then you will have use something like you have suggested, but it won't be portable and probably will not work in all cases.</p> <p>If you only have to find the pids for a certain application and you have control over this application, then I'd suggest changing this app to store its pid in files in some location where your script can find it.</p>
1
2009-02-17T14:21:30Z
[ "python", "cross-platform", "jython", "hp-ux" ]
Cross-platform way to get PIDs by process name in python
550,653
<p>Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using <strong>python</strong> or <strong>jython</strong>?</p> <ol> <li>I want something like <code>pidof</code> but in python. (I don't have <code>pidof</code> anyway.)</li> <li>I can't parse <code>/proc</code> because it might be unavailable (on HP-UX).</li> <li>I do not want to run <code>os.popen('ps')</code> and parse the output because I think it is ugly (field sequence may be different in different OS).</li> <li>Target platforms are Solaris, HP-UX, and maybe others.</li> </ol>
36
2009-02-15T10:23:56Z
727,024
<p>For jython, if Java 5 is used, then you can get the Java process id as following:</p> <p>from java.lang.management import *<br/> pid = ManagementFactory.getRuntimeMXBean().getName()</p>
1
2009-04-07T18:30:37Z
[ "python", "cross-platform", "jython", "hp-ux" ]
Cross-platform way to get PIDs by process name in python
550,653
<p>Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using <strong>python</strong> or <strong>jython</strong>?</p> <ol> <li>I want something like <code>pidof</code> but in python. (I don't have <code>pidof</code> anyway.)</li> <li>I can't parse <code>/proc</code> because it might be unavailable (on HP-UX).</li> <li>I do not want to run <code>os.popen('ps')</code> and parse the output because I think it is ugly (field sequence may be different in different OS).</li> <li>Target platforms are Solaris, HP-UX, and maybe others.</li> </ol>
36
2009-02-15T10:23:56Z
1,226,643
<p>There's no single cross-platform API, you'll have to check for OS. For posix based use /proc. For Windows use following code to get list of all pids with coresponding process names</p> <pre><code>from win32com.client import GetObject WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') process_list = [(p.Properties_("ProcessID").Value, p.Properties_("Name").Value) for p in processes] </code></pre> <p>You can then easily filter out processes you need. For more info on available properties of Win32_Process check out <a href="http://msdn.microsoft.com/en-us/library/aa394372%28VS.85%29.aspx">Win32_Process Class</a></p>
10
2009-08-04T10:00:18Z
[ "python", "cross-platform", "jython", "hp-ux" ]
Cross-platform way to get PIDs by process name in python
550,653
<p>Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using <strong>python</strong> or <strong>jython</strong>?</p> <ol> <li>I want something like <code>pidof</code> but in python. (I don't have <code>pidof</code> anyway.)</li> <li>I can't parse <code>/proc</code> because it might be unavailable (on HP-UX).</li> <li>I do not want to run <code>os.popen('ps')</code> and parse the output because I think it is ugly (field sequence may be different in different OS).</li> <li>Target platforms are Solaris, HP-UX, and maybe others.</li> </ol>
36
2009-02-15T10:23:56Z
2,241,047
<p>You can use psutil ( <a href="https://github.com/giampaolo/psutil" rel="nofollow">https://github.com/giampaolo/psutil</a> ), which works on Windows and UNIX:</p> <pre> import psutil PROCNAME = "python.exe" for proc in psutil.process_iter(): if proc.name() == PROCNAME: print(proc) </pre> <p>The code above prints the following on my machine:</p> <pre> psutil.Process (PID:2908; PPID:3944; NAME:'python.exe'; PATH:'C:\Python26'; CMDL INE:['C:\\Python26\\python.exe', 'D:\\pyftpdlib\\svn\\psutil\\foo.py']; UID:-1; GID:-1;) </pre>
45
2010-02-10T23:12:17Z
[ "python", "cross-platform", "jython", "hp-ux" ]
Cross-platform way to get PIDs by process name in python
550,653
<p>Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using <strong>python</strong> or <strong>jython</strong>?</p> <ol> <li>I want something like <code>pidof</code> but in python. (I don't have <code>pidof</code> anyway.)</li> <li>I can't parse <code>/proc</code> because it might be unavailable (on HP-UX).</li> <li>I do not want to run <code>os.popen('ps')</code> and parse the output because I think it is ugly (field sequence may be different in different OS).</li> <li>Target platforms are Solaris, HP-UX, and maybe others.</li> </ol>
36
2009-02-15T10:23:56Z
14,792,920
<pre><code>import psutil process = filter(lambda p: p.name == "YourProcess.exe", psutil.process_iter()) for i in process: print i.name,i.pid </code></pre> <p>Give all pids of "YourProcess.exe"</p>
4
2013-02-09T23:42:35Z
[ "python", "cross-platform", "jython", "hp-ux" ]
python, dictionary and int error
550,673
<p>I have a very frustrating python problem. In this code</p> <pre><code>fixedKeyStringInAVar = "SomeKey" def myFunc(a, b): global sleepTime global fixedKeyStringInAVar varMe=int("15") sleepTime[fixedKeyStringInAVar] = varMe*60*1000 #more code </code></pre> <p>Now this works. BUT sometimes when I run this function I get</p> <pre><code>TypeError: 'int' object does not support item assignment </code></pre> <p>It is extremely annoying since I tried several test cases and could not reproduce the error, yet it happens very often when I run the full code. The code reads data from a db, access sites, etc. so its hard for me to go through the data since it reads from several sources and depends on 3rd party input that changes (websites).</p> <p>What could this error be?</p>
0
2009-02-15T10:37:57Z
550,679
<p>Your sleepTime is a global variable. It could be changed to be an int at some point in your program.</p> <p>The item assignment is the "foo[bar] = baz" construction in your function.</p>
1
2009-02-15T10:40:58Z
[ "python", "dictionary", "global" ]
python, dictionary and int error
550,673
<p>I have a very frustrating python problem. In this code</p> <pre><code>fixedKeyStringInAVar = "SomeKey" def myFunc(a, b): global sleepTime global fixedKeyStringInAVar varMe=int("15") sleepTime[fixedKeyStringInAVar] = varMe*60*1000 #more code </code></pre> <p>Now this works. BUT sometimes when I run this function I get</p> <pre><code>TypeError: 'int' object does not support item assignment </code></pre> <p>It is extremely annoying since I tried several test cases and could not reproduce the error, yet it happens very often when I run the full code. The code reads data from a db, access sites, etc. so its hard for me to go through the data since it reads from several sources and depends on 3rd party input that changes (websites).</p> <p>What could this error be?</p>
0
2009-02-15T10:37:57Z
550,722
<ol> <li><p>Don't use <code>global</code> keyword in a function unless you'd like to change binding of a global name.</p></li> <li><p>Search for '<code>sleepTime =</code>' in your code. You are binding an int object to the <code>sleepTime</code> name at some point in your program.</p></li> </ol>
5
2009-02-15T11:12:08Z
[ "python", "dictionary", "global" ]
python runtime error, can dump a file?
550,804
<p>I am using libcurl to DL a webpage, then i am scanning it for data and doing something with one of the links. However, once in a while the page is different then i except thus i extract bad data and pycurl throws an exception. I tried finding the exception name for pycurl but had no luck.</p> <p>Is there a way i can get the traceback to execute a function so i can dump the file so i can look at the file input and see were my code went wrong?</p>
2
2009-02-15T12:29:46Z
550,815
<p>Can you catch all exceptions somewhere in the main block and use sys.exc_info() for callback information and log that to your file. exc_info() returns not just exception type, but also call traceback so there should information what went wrong.</p>
2
2009-02-15T12:40:18Z
[ "python", "error-handling", "pycurl" ]
python runtime error, can dump a file?
550,804
<p>I am using libcurl to DL a webpage, then i am scanning it for data and doing something with one of the links. However, once in a while the page is different then i except thus i extract bad data and pycurl throws an exception. I tried finding the exception name for pycurl but had no luck.</p> <p>Is there a way i can get the traceback to execute a function so i can dump the file so i can look at the file input and see were my code went wrong?</p>
2
2009-02-15T12:29:46Z
550,822
<p><a href="http://docs.python.org/library/sys.html#sys.excepthook" rel="nofollow">sys.excepthook</a> may help you here, where you can set a global exception handler. I am not sure how pycurl exceptions are handled, it being a binding library, but it will probably work to reassign it to a generic function. Something like:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; &gt;&gt;&gt; def my_global_exception_handler(type, value, traceback): ... print traceback ... sys.exit() ... &gt;&gt;&gt; sys.excepthook = my_global_exception_handler &gt;&gt;&gt; raise &lt;traceback object at 0xb7cfcaa4&gt; </code></pre> <p>This exception hook function could easily be an instance method that has access to the file that needs dumping.</p>
3
2009-02-15T12:45:56Z
[ "python", "error-handling", "pycurl" ]
python runtime error, can dump a file?
550,804
<p>I am using libcurl to DL a webpage, then i am scanning it for data and doing something with one of the links. However, once in a while the page is different then i except thus i extract bad data and pycurl throws an exception. I tried finding the exception name for pycurl but had no luck.</p> <p>Is there a way i can get the traceback to execute a function so i can dump the file so i can look at the file input and see were my code went wrong?</p>
2
2009-02-15T12:29:46Z
551,449
<p>You can use a generic exception handler.</p> <pre><code>logging.basicConfig( file="someFile.log", level=logging.DEBUG ) logger= logging.getLogger( __name__ ) try: curl = pycurl.Curl() curl.setopt(pycurl.URL, url) # etc. curl.perform() curl.close logger.info( "Read %s", url ) except Exception, e: logger.exception( e ) print e, repr(e), e.message, e.args raise logging.shutdown() </code></pre> <p>This will write a nice log that has the exception information you're looking for.</p>
3
2009-02-15T19:37:05Z
[ "python", "error-handling", "pycurl" ]
"Private" (implementation) class in Python
551,038
<p>I am coding a small Python module composed of two parts:</p> <ul> <li>some functions defining a public interface,</li> <li>an implementation class used by the above functions, but which is not meaningful outside the module.</li> </ul> <p>At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class.</p> <p>So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.</p>
50
2009-02-15T15:29:40Z
551,047
<p>The convention is prepend "_" to internal classes, functions, and variables.</p>
6
2009-02-15T15:33:48Z
[ "python", "design", "access-modifiers" ]
"Private" (implementation) class in Python
551,038
<p>I am coding a small Python module composed of two parts:</p> <ul> <li>some functions defining a public interface,</li> <li>an implementation class used by the above functions, but which is not meaningful outside the module.</li> </ul> <p>At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class.</p> <p>So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.</p>
50
2009-02-15T15:29:40Z
551,048
<p>Use a single underscore prefix:</p> <pre><code>class _Internal: ... </code></pre> <p>This is the official Python convention for 'internal' symbols; "from module import *" does not import underscore-prefixed objects.</p>
89
2009-02-15T15:34:03Z
[ "python", "design", "access-modifiers" ]
"Private" (implementation) class in Python
551,038
<p>I am coding a small Python module composed of two parts:</p> <ul> <li>some functions defining a public interface,</li> <li>an implementation class used by the above functions, but which is not meaningful outside the module.</li> </ul> <p>At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class.</p> <p>So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.</p>
50
2009-02-15T15:29:40Z
551,054
<p>Define <code>__all__</code>, a list of names that you want to be exported (<a href="http://docs.python.org/tutorial/modules.html#importing-from-a-package">see documentation</a>).</p> <pre><code>__all__ = ['public_class'] # don't add here the 'implementation_class' </code></pre>
22
2009-02-15T15:36:03Z
[ "python", "design", "access-modifiers" ]
"Private" (implementation) class in Python
551,038
<p>I am coding a small Python module composed of two parts:</p> <ul> <li>some functions defining a public interface,</li> <li>an implementation class used by the above functions, but which is not meaningful outside the module.</li> </ul> <p>At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class.</p> <p>So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.</p>
50
2009-02-15T15:29:40Z
551,097
<p>A pattern that I sometimes use is this:</p> <p>Define a class:</p> <pre><code>class x(object): def doThis(self): ... def doThat(self): ... </code></pre> <p>Create an instance of the class, overwriting the class name:</p> <pre><code>x = x() </code></pre> <p>Define symbols that expose the functionality:</p> <pre><code>doThis = x.doThis doThat = x.doThat </code></pre> <p>Delete the instance itself:</p> <pre><code>del x </code></pre> <p>Now you have a module that only exposes your public functions.</p>
8
2009-02-15T15:58:49Z
[ "python", "design", "access-modifiers" ]
"Private" (implementation) class in Python
551,038
<p>I am coding a small Python module composed of two parts:</p> <ul> <li>some functions defining a public interface,</li> <li>an implementation class used by the above functions, but which is not meaningful outside the module.</li> </ul> <p>At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class.</p> <p>So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.</p>
50
2009-02-15T15:29:40Z
551,169
<p>Use two underscores to prefix names of "private" identifiers. For classes in a module, use a single leading underscore and they will not be imported using "from module import *".</p> <pre><code>class _MyInternalClass: def __my_private_method: pass </code></pre> <p>(There is no such thing as true "private" in Python. For example, Python just automatically mangles the names of class members with double underscores to be <code>__clssname_mymember</code>. So really, if you know the mangled name you can use the "private" entity anyway. <a href="http://docs.python.org/tutorial/classes.html#private-variables" rel="nofollow">See here.</a> And of course you can choose to manually import "internal" classes if you wanted to).</p>
2
2009-02-15T16:37:01Z
[ "python", "design", "access-modifiers" ]
"Private" (implementation) class in Python
551,038
<p>I am coding a small Python module composed of two parts:</p> <ul> <li>some functions defining a public interface,</li> <li>an implementation class used by the above functions, but which is not meaningful outside the module.</li> </ul> <p>At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class.</p> <p>So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.</p>
50
2009-02-15T15:29:40Z
551,311
<p>To address the issue of design conventions, and as Christopher said, there's really no such thing as "private" in Python. This may sound twisted for someone coming from C/C++ background (like me a while back), but eventually, you'll probably realize following conventions is plenty enough. </p> <p>Seeing something having an underscore in front should be a good enough hint not to use it directly. If you're concerned with cluttering <code>help(MyClass)</code> output (which is what everyone looks at when searching on how to use a class), the underscored attributes/classes are not included there, so you'll end up just having your "public" interface described.</p> <p>Plus, having everything public has its own awesome perks, like for instance, you can unit test pretty much anything from outside (which you can't really do with C/C++ private constructs).</p>
3
2009-02-15T18:09:59Z
[ "python", "design", "access-modifiers" ]
"Private" (implementation) class in Python
551,038
<p>I am coding a small Python module composed of two parts:</p> <ul> <li>some functions defining a public interface,</li> <li>an implementation class used by the above functions, but which is not meaningful outside the module.</li> </ul> <p>At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class.</p> <p>So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.</p>
50
2009-02-15T15:29:40Z
551,361
<p>In short:</p> <ol> <li><p><strong>You cannot enforce privacy</strong>. There are no private classes/methods/functions in Python. At least, not strict privacy as in other languages, such as Java. </p></li> <li><p><strong>You can only indicate/suggest privacy</strong>. This follows a convention. The python convention for marking a class/function/method as private is to preface it with an _ (underscore). For example, <code>def _myfunc()</code> or <code>class _MyClass:</code>. You can also create pseudo-privacy by prefacing the method with two underscores (eg: <code>__foo</code>). You cannot access the method directly, but you can still call it through a special prefix using the classname (eg: <code>_classname__foo</code>). So the best you can do is indicate/suggest privacy, not enforce it.</p></li> </ol> <p>Python is like perl in this respect. To paraphrase a famous line about privacy from the Perl book, the philosophy is that you should stay of the living room because you weren't invited, not because it is defended with a shotgun.</p> <p>For more information:</p> <ul> <li><a href="http://docs.python.org/tutorial/classes.html#private-variables">Private variables</a> <em>Python Documentation</em></li> <li><a href="http://www.diveintopython.net/object_oriented_framework/private_functions.html">Private functions</a> <em>Dive into Python</em>, by Mark Pilgrim</li> <li><a href="http://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private">Why are Python’s ‘private’ methods not actually private?</a> <em>StackOverflow question 70528</em></li> </ul>
45
2009-02-15T18:31:49Z
[ "python", "design", "access-modifiers" ]
Deploying application with Python or another embedded scripting language
551,227
<p>I'm thinking about using Python as an <strong>embedded scripting language</strong> in a hobby project written in <strong>C++</strong>. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but I couldn't find a clear answer to this.</p> <p>Is it feasible to deploy a Python interpreter + standard library with my application? Would some other language like Lua, Javascript (Spidermonkey), Ruby, etc. be better for this use?</p> <p>Here's the criteria I'm weighing the different languages against:</p> <ul> <li>No/Few dependencies on externally installed packages</li> <li>Standard library with good feature set</li> <li>Nice language :)</li> <li>Doesn't result in a huge install package</li> </ul> <p>edit: </p> <p>I guess the question should be: How do I deploy my own python library + standard library with the installer of my program, so that it doesn't matter whether the platform already has python installed or not?</p> <p>edit2: </p> <p>One more clarification. I don't need info about specifics of linking C and Python code.</p>
14
2009-02-15T17:12:33Z
551,252
<p>The embedding process is fully documented : <a href="http://docs.python.org/extending/embedding.html" rel="nofollow">Embedding Python in Another Application</a>. The documents suggests a few levels at which embedding is done, choose whatever best fits your requirements. </p> <blockquote> <p>A simple demo of embedding Python can be found in the directory Demo/embed/ of the source distribution.</p> </blockquote> <p><a href="http://svn.python.org/view/python/trunk/Demo/embed/" rel="nofollow">The demo is here</a>, should be able to build from the distro.</p> <blockquote> <ul> <li>Very High Level Embedding</li> <li>Beyond Very High Level Embedding: An overview</li> <li>Pure Embedding</li> <li>Extending Embedded Python</li> <li>Embedding Python in C++</li> </ul> </blockquote> <p>From the standard library you can select the components that do not carry too much dependencies.</p>
8
2009-02-15T17:28:19Z
[ "c++", "python", "deployment", "scripting-language", "embedded-language" ]
Deploying application with Python or another embedded scripting language
551,227
<p>I'm thinking about using Python as an <strong>embedded scripting language</strong> in a hobby project written in <strong>C++</strong>. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but I couldn't find a clear answer to this.</p> <p>Is it feasible to deploy a Python interpreter + standard library with my application? Would some other language like Lua, Javascript (Spidermonkey), Ruby, etc. be better for this use?</p> <p>Here's the criteria I'm weighing the different languages against:</p> <ul> <li>No/Few dependencies on externally installed packages</li> <li>Standard library with good feature set</li> <li>Nice language :)</li> <li>Doesn't result in a huge install package</li> </ul> <p>edit: </p> <p>I guess the question should be: How do I deploy my own python library + standard library with the installer of my program, so that it doesn't matter whether the platform already has python installed or not?</p> <p>edit2: </p> <p>One more clarification. I don't need info about specifics of linking C and Python code.</p>
14
2009-02-15T17:12:33Z
551,264
<p>If you're looking for a way to simply deploy a Python app, you could use <a href="http://www.py2exe.org/" rel="nofollow">Py2Exe</a>. That would allow your app all the dependencies it needs without worrying what is or isn't already installed on the users machine.</p> <p>[Edit] If Py2Exe is a no-go for embedded applications, could you simply get your installer to check for the relevent files and download / install anything that's missing?[/Edit]</p> <p>[Edit2] Could <a href="http://elmer.sourceforge.net/" rel="nofollow">Elmer</a> be what you're looking for? [/Edit2]</p>
0
2009-02-15T17:42:00Z
[ "c++", "python", "deployment", "scripting-language", "embedded-language" ]
Deploying application with Python or another embedded scripting language
551,227
<p>I'm thinking about using Python as an <strong>embedded scripting language</strong> in a hobby project written in <strong>C++</strong>. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but I couldn't find a clear answer to this.</p> <p>Is it feasible to deploy a Python interpreter + standard library with my application? Would some other language like Lua, Javascript (Spidermonkey), Ruby, etc. be better for this use?</p> <p>Here's the criteria I'm weighing the different languages against:</p> <ul> <li>No/Few dependencies on externally installed packages</li> <li>Standard library with good feature set</li> <li>Nice language :)</li> <li>Doesn't result in a huge install package</li> </ul> <p>edit: </p> <p>I guess the question should be: How do I deploy my own python library + standard library with the installer of my program, so that it doesn't matter whether the platform already has python installed or not?</p> <p>edit2: </p> <p>One more clarification. I don't need info about specifics of linking C and Python code.</p>
14
2009-02-15T17:12:33Z
551,332
<p>To extend the answer by gimel, there is nothing to stop you from shipping python.dll, using it, and setting a correct PYTHONPATH in order to use your own installation of the python standard library. They are just libraries and files, and your install process can just deal with them as such.</p>
5
2009-02-15T18:16:30Z
[ "c++", "python", "deployment", "scripting-language", "embedded-language" ]
Deploying application with Python or another embedded scripting language
551,227
<p>I'm thinking about using Python as an <strong>embedded scripting language</strong> in a hobby project written in <strong>C++</strong>. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but I couldn't find a clear answer to this.</p> <p>Is it feasible to deploy a Python interpreter + standard library with my application? Would some other language like Lua, Javascript (Spidermonkey), Ruby, etc. be better for this use?</p> <p>Here's the criteria I'm weighing the different languages against:</p> <ul> <li>No/Few dependencies on externally installed packages</li> <li>Standard library with good feature set</li> <li>Nice language :)</li> <li>Doesn't result in a huge install package</li> </ul> <p>edit: </p> <p>I guess the question should be: How do I deploy my own python library + standard library with the installer of my program, so that it doesn't matter whether the platform already has python installed or not?</p> <p>edit2: </p> <p>One more clarification. I don't need info about specifics of linking C and Python code.</p>
14
2009-02-15T17:12:33Z
551,533
<p>Link your application to the python library (pythonXX.lib on Windows) and add the following to your main() function.</p> <pre><code>Py_NoSiteFlag = 1; // Disable importing site.py Py_Initialize(); // Create a python interpreter </code></pre> <p>Put the python standard library bits you need into a zip file (called pythonXX.zip) and place this and pythonXX.dll beside the executable you distribute. Have a look at PyZipFile in the the zipfile module.</p>
14
2009-02-15T20:28:31Z
[ "c++", "python", "deployment", "scripting-language", "embedded-language" ]
Getting "global name 'foo' is not defined" with Python's timeit
551,797
<p>I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called <a href="http://docs.python.org/library/timeit.html">timeit</a> that purports to do exactly that:</p> <pre><code>import timeit def foo(): # ... contains code I want to time ... def dotime(): t = timeit.Timer("foo()") time = t.timeit(1) print "took %fs\n" % (time,) dotime() </code></pre> <p>However, this produces an error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in dotime File "/usr/local/lib/python2.6/timeit.py", line 193, in timeit timing = self.inner(it, self.timer) File "&lt;timeit-src&gt;", line 6, in inner NameError: global name 'foo' is not defined </code></pre> <p>I'm still new to Python and I don't fully understand all the scoping issues it has, but I don't know why this snippet doesn't work. Any thoughts?</p>
58
2009-02-15T23:15:40Z
551,804
<p>have you tried making this line:</p> <pre><code>t = timeit.Timer("foo()") </code></pre> <p>This:</p> <pre><code>t = timeit.Timer("foo()", "from __main__ import foo") </code></pre> <p>Check out the link you provided at the very bottom.</p> <blockquote> <p>To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement:</p> </blockquote> <p>I just tested it on my machine and it worked with the changes.</p>
67
2009-02-15T23:18:42Z
[ "python", "scope", "timeit" ]
Getting "global name 'foo' is not defined" with Python's timeit
551,797
<p>I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called <a href="http://docs.python.org/library/timeit.html">timeit</a> that purports to do exactly that:</p> <pre><code>import timeit def foo(): # ... contains code I want to time ... def dotime(): t = timeit.Timer("foo()") time = t.timeit(1) print "took %fs\n" % (time,) dotime() </code></pre> <p>However, this produces an error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in dotime File "/usr/local/lib/python2.6/timeit.py", line 193, in timeit timing = self.inner(it, self.timer) File "&lt;timeit-src&gt;", line 6, in inner NameError: global name 'foo' is not defined </code></pre> <p>I'm still new to Python and I don't fully understand all the scoping issues it has, but I don't know why this snippet doesn't work. Any thoughts?</p>
58
2009-02-15T23:15:40Z
551,809
<pre><code>t = timeit.Timer("foo()", "from __main__ import foo") </code></pre> <p>Since timeit doesn't have your stuff in scope.</p>
6
2009-02-15T23:22:16Z
[ "python", "scope", "timeit" ]
Getting "global name 'foo' is not defined" with Python's timeit
551,797
<p>I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called <a href="http://docs.python.org/library/timeit.html">timeit</a> that purports to do exactly that:</p> <pre><code>import timeit def foo(): # ... contains code I want to time ... def dotime(): t = timeit.Timer("foo()") time = t.timeit(1) print "took %fs\n" % (time,) dotime() </code></pre> <p>However, this produces an error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in dotime File "/usr/local/lib/python2.6/timeit.py", line 193, in timeit timing = self.inner(it, self.timer) File "&lt;timeit-src&gt;", line 6, in inner NameError: global name 'foo' is not defined </code></pre> <p>I'm still new to Python and I don't fully understand all the scoping issues it has, but I don't know why this snippet doesn't work. Any thoughts?</p>
58
2009-02-15T23:15:40Z
5,390,326
<p>You can try this hack:</p> <pre><code>import timeit def foo(): print 'bar' def dotime(): t = timeit.Timer("foo()") time = t.timeit(1) print "took %fs\n" % (time,) import __builtin__ __builtin__.__dict__.update(locals()) dotime() </code></pre>
13
2011-03-22T11:16:51Z
[ "python", "scope", "timeit" ]
Help me implement Blackjack in Python (updated)
551,840
<p>I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it:</p> <ol> <li>Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly.</li> <li>Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins.</li> </ol> <p>Ok, this is what i have gotten so far.</p> <pre><code>"This imports the random object into Python, it allows it to generate random numbers." import random print("Hello and welcome to Sam's Black Jack!") input("Press &lt;ENTER&gt; to begin.") card1name = 1 card2name = 1 card3name = 1 card4name = 1 card5name = 1 "This defines the values of the character cards." Ace = 1 Jack = 10 Queen = 10 King = 10 decision = 0 "This generates the cards that are in your hand and the dealer's hand to begin with. card1 = int(random.randrange(12) + 1) card2 = int(random.randrange(12) + 1) card3 = int(random.randrange(12) + 1) card4 = int(random.randrange(12) + 1) card5 = int(random.randrange(12) + 1) total1 = card1 + card2 "This makes the value of the Ace equal 11 if the total of your cards is under 21" if total1 &lt;= 21: Ace = 11 "This defines what the cards are" if card1 == 11: card1 = 10 card1name = "Jack" if card1 == 12: card1 = 10 card1name = "Queen" if card1 == 13: card1 = 10 card1name = "King" if card1 == 1: card1 = Ace card1name = "Ace" elif card1: card1name = card1 if card2 == 11: card2 = 10 card2name = "Jack" if card2 == 12: card2 = 10 card2name = "Queen" if card2 == 13: card2 = 10 card2name = "King" if card2 == 1: card2 = Ace card2name = "Ace" elif card2: card2name = card2 if card3 == 11: card3 = 10 card3name = "Jack" if card3 == 12: card3 = 10 card3name = "Queen" if card3 == 13: card3 = 10 card3name= "King" if card3 == 1: card3 = Ace card3name = "Ace" elif card3: card3name = card3 if card4 == 11: card4 = 10 card4name = "Jack" if card4 == 12: card4 = 10 card4name = "Queen" if card4 == 13: card4 = 10 card4name = "King" if card4 == 1: card4 = Ace card4name = "Ace" elif card4: card4name = card4 if card5 == 11: card5 = 10 card5name = "Jack" if card5 == 12: card5 = 10 card5name = "Queen" if card5 == 13: card5 = 10 card5name = "King" if card5 == 1: card5 = Ace card5name = "Ace" elif card5: card5name = card5 "This creates the totals of your hand" total2 = card1 + card2 total3 = card1 + card2 + card3 print("You hand is ", card1name," and", card2name) print("The total of your hand is", total2) decision = input("Do you want to HIT or STAND?").lower() "This is the decision for Hit or Stand" if 'hit' or 'HIT' or 'Hit' in decision: decision = 1 print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if 'STAND' or 'stand' or 'Stand' in decision: print("You have selected STAND") "Dealer's Hand" dealer = card4 + card5 print() print("The dealer's hand is", card4name," and", card5name) if decision == 1 and dealer &lt; total3: print("Congratulations, you beat the dealer!") if decision == 1 and dealer &gt; total3: print("Too bad, the dealer beat you!") </code></pre> <p>Ok, nevermind, i fixed it :D</p> <p>I just changed the Hit and Stand to Yes or No</p> <pre><code>if total2 &lt; 21: decision = input("Do you want to hit? (Yes or No)") "This is the decision for Hit or Stand" if decision == 'Yes': print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if decision == 'No': print("You have selected STAND") </code></pre>
3
2009-02-15T23:34:26Z
551,852
<p>This can get you started:</p> <p><a href="http://docs.python.org/library/random.html">http://docs.python.org/library/random.html</a></p> <p><a href="http://docs.python.org/library/strings.html">http://docs.python.org/library/strings.html</a></p> <p><a href="http://docs.python.org/library/stdtypes.html">http://docs.python.org/library/stdtypes.html</a></p> <p><a href="http://docs.python.org/reference/index.html">http://docs.python.org/reference/index.html</a></p> <p>I see you have added some code; that's good.</p> <p>Think about the parts of your program that will need to exist. You will need some representation of "cards" -- cards have important features such as their value, their suit, etc. Given a card, you should be able to tell what its value is, whether it's a Jack or an Ace or a 2 of hearts. Read up on "classes" in Python to get started with this.</p> <p>You will also have a hand of cards -- the cards your dealer is currently holding, and the cards your player is currently holding. A "hand" is a collection of cards, which you (the programmer) can add new cards to (when a card is dealt). You might want to do that using "lists" or "arrays" or "classes" that contain those arrays. A hand also has a value, which is usually the sum of card values, but as you know, Aces are special (they can be 1 or 11), so you'll need to treat that case correctly with some "if statements".</p> <p>You will also have a deck; a deck is a special collection -- it has exactly 52 cards when it starts, and none of the cards are repeated (you could, of course, be using several decks to play, but that's a complication you can solve later). How do you populate a deck like that? Your program will want to "deal" from the deck -- so you'll need a way to keep track of which cards have been dealt to players.</p> <p>That's a lot of stuff. Try writing down all the logic of what your program needs to do in simple sentences, without worrying about Python. This is called "pseudo-code". It's not a real program, it's just a plan for what exactly you are going to do -- it's useful the way a map is useful. If you are going to a place you've been to a 100 times, you don't need a map, but if you are driving to some town you've never been to, you want to plan out your route first, before getting behind the wheel..</p> <p>Update your question with your pseudocode, and any attempts you have made (or will have made) to translate the pseudocode to Python.</p>
14
2009-02-15T23:42:10Z
[ "python" ]
Help me implement Blackjack in Python (updated)
551,840
<p>I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it:</p> <ol> <li>Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly.</li> <li>Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins.</li> </ol> <p>Ok, this is what i have gotten so far.</p> <pre><code>"This imports the random object into Python, it allows it to generate random numbers." import random print("Hello and welcome to Sam's Black Jack!") input("Press &lt;ENTER&gt; to begin.") card1name = 1 card2name = 1 card3name = 1 card4name = 1 card5name = 1 "This defines the values of the character cards." Ace = 1 Jack = 10 Queen = 10 King = 10 decision = 0 "This generates the cards that are in your hand and the dealer's hand to begin with. card1 = int(random.randrange(12) + 1) card2 = int(random.randrange(12) + 1) card3 = int(random.randrange(12) + 1) card4 = int(random.randrange(12) + 1) card5 = int(random.randrange(12) + 1) total1 = card1 + card2 "This makes the value of the Ace equal 11 if the total of your cards is under 21" if total1 &lt;= 21: Ace = 11 "This defines what the cards are" if card1 == 11: card1 = 10 card1name = "Jack" if card1 == 12: card1 = 10 card1name = "Queen" if card1 == 13: card1 = 10 card1name = "King" if card1 == 1: card1 = Ace card1name = "Ace" elif card1: card1name = card1 if card2 == 11: card2 = 10 card2name = "Jack" if card2 == 12: card2 = 10 card2name = "Queen" if card2 == 13: card2 = 10 card2name = "King" if card2 == 1: card2 = Ace card2name = "Ace" elif card2: card2name = card2 if card3 == 11: card3 = 10 card3name = "Jack" if card3 == 12: card3 = 10 card3name = "Queen" if card3 == 13: card3 = 10 card3name= "King" if card3 == 1: card3 = Ace card3name = "Ace" elif card3: card3name = card3 if card4 == 11: card4 = 10 card4name = "Jack" if card4 == 12: card4 = 10 card4name = "Queen" if card4 == 13: card4 = 10 card4name = "King" if card4 == 1: card4 = Ace card4name = "Ace" elif card4: card4name = card4 if card5 == 11: card5 = 10 card5name = "Jack" if card5 == 12: card5 = 10 card5name = "Queen" if card5 == 13: card5 = 10 card5name = "King" if card5 == 1: card5 = Ace card5name = "Ace" elif card5: card5name = card5 "This creates the totals of your hand" total2 = card1 + card2 total3 = card1 + card2 + card3 print("You hand is ", card1name," and", card2name) print("The total of your hand is", total2) decision = input("Do you want to HIT or STAND?").lower() "This is the decision for Hit or Stand" if 'hit' or 'HIT' or 'Hit' in decision: decision = 1 print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if 'STAND' or 'stand' or 'Stand' in decision: print("You have selected STAND") "Dealer's Hand" dealer = card4 + card5 print() print("The dealer's hand is", card4name," and", card5name) if decision == 1 and dealer &lt; total3: print("Congratulations, you beat the dealer!") if decision == 1 and dealer &gt; total3: print("Too bad, the dealer beat you!") </code></pre> <p>Ok, nevermind, i fixed it :D</p> <p>I just changed the Hit and Stand to Yes or No</p> <pre><code>if total2 &lt; 21: decision = input("Do you want to hit? (Yes or No)") "This is the decision for Hit or Stand" if decision == 'Yes': print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if decision == 'No': print("You have selected STAND") </code></pre>
3
2009-02-15T23:34:26Z
551,855
<p>I agreed with SquareCog's comment - some additional information about what you've tried and what's not working and what you're confused about would be helpful.</p> <p>Some info that might be helpful, though:</p> <p>Regarding the generation of numbers between 1-10, ace, king, queen, and jack: it might be helpful to assign each card a numeric index. 2-10 are obvious, and you can make your own values for jack, queen, king, and ace. One thing to especially note is that there's no 1, if you're also generating ace. Once you've assigned numbers, the <a href="http://docs.python.org/library/random.html" rel="nofollow">random module</a> can help.</p> <p>There are standard comparison methods that can be used to recognize the difference between "Hit" or "Stand". Notably the <code>==</code> <a href="http://docs.python.org/library/stdtypes.html#comparisons" rel="nofollow">operator</a>.</p> <p>Since you're generating hands, it should be easy to check whether they are certain combinations. As far as calculating scores, a good starting point would be to use addition.</p> <p><strong>Edit:</strong> based on your subsequent comments, it seems like you might benefit from some of the <a href="http://wiki.python.org/moin/BeginnersGuide/NonProgrammers" rel="nofollow">"Python for non-programmer" guides</a>.</p>
4
2009-02-15T23:42:41Z
[ "python" ]
Help me implement Blackjack in Python (updated)
551,840
<p>I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it:</p> <ol> <li>Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly.</li> <li>Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins.</li> </ol> <p>Ok, this is what i have gotten so far.</p> <pre><code>"This imports the random object into Python, it allows it to generate random numbers." import random print("Hello and welcome to Sam's Black Jack!") input("Press &lt;ENTER&gt; to begin.") card1name = 1 card2name = 1 card3name = 1 card4name = 1 card5name = 1 "This defines the values of the character cards." Ace = 1 Jack = 10 Queen = 10 King = 10 decision = 0 "This generates the cards that are in your hand and the dealer's hand to begin with. card1 = int(random.randrange(12) + 1) card2 = int(random.randrange(12) + 1) card3 = int(random.randrange(12) + 1) card4 = int(random.randrange(12) + 1) card5 = int(random.randrange(12) + 1) total1 = card1 + card2 "This makes the value of the Ace equal 11 if the total of your cards is under 21" if total1 &lt;= 21: Ace = 11 "This defines what the cards are" if card1 == 11: card1 = 10 card1name = "Jack" if card1 == 12: card1 = 10 card1name = "Queen" if card1 == 13: card1 = 10 card1name = "King" if card1 == 1: card1 = Ace card1name = "Ace" elif card1: card1name = card1 if card2 == 11: card2 = 10 card2name = "Jack" if card2 == 12: card2 = 10 card2name = "Queen" if card2 == 13: card2 = 10 card2name = "King" if card2 == 1: card2 = Ace card2name = "Ace" elif card2: card2name = card2 if card3 == 11: card3 = 10 card3name = "Jack" if card3 == 12: card3 = 10 card3name = "Queen" if card3 == 13: card3 = 10 card3name= "King" if card3 == 1: card3 = Ace card3name = "Ace" elif card3: card3name = card3 if card4 == 11: card4 = 10 card4name = "Jack" if card4 == 12: card4 = 10 card4name = "Queen" if card4 == 13: card4 = 10 card4name = "King" if card4 == 1: card4 = Ace card4name = "Ace" elif card4: card4name = card4 if card5 == 11: card5 = 10 card5name = "Jack" if card5 == 12: card5 = 10 card5name = "Queen" if card5 == 13: card5 = 10 card5name = "King" if card5 == 1: card5 = Ace card5name = "Ace" elif card5: card5name = card5 "This creates the totals of your hand" total2 = card1 + card2 total3 = card1 + card2 + card3 print("You hand is ", card1name," and", card2name) print("The total of your hand is", total2) decision = input("Do you want to HIT or STAND?").lower() "This is the decision for Hit or Stand" if 'hit' or 'HIT' or 'Hit' in decision: decision = 1 print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if 'STAND' or 'stand' or 'Stand' in decision: print("You have selected STAND") "Dealer's Hand" dealer = card4 + card5 print() print("The dealer's hand is", card4name," and", card5name) if decision == 1 and dealer &lt; total3: print("Congratulations, you beat the dealer!") if decision == 1 and dealer &gt; total3: print("Too bad, the dealer beat you!") </code></pre> <p>Ok, nevermind, i fixed it :D</p> <p>I just changed the Hit and Stand to Yes or No</p> <pre><code>if total2 &lt; 21: decision = input("Do you want to hit? (Yes or No)") "This is the decision for Hit or Stand" if decision == 'Yes': print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if decision == 'No': print("You have selected STAND") </code></pre>
3
2009-02-15T23:34:26Z
552,111
<p>I've covered the entire thing as a (long) series of exercises.</p> <p><a href="http://homepage.mac.com/s_lott/books/oodesign.html">http://homepage.mac.com/s_lott/books/oodesign.html</a></p> <p>Just read and do the exercises in the book. You'll implement blackjack (and Craps and Roulette, too.)</p>
9
2009-02-16T02:57:38Z
[ "python" ]
Help me implement Blackjack in Python (updated)
551,840
<p>I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it:</p> <ol> <li>Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly.</li> <li>Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins.</li> </ol> <p>Ok, this is what i have gotten so far.</p> <pre><code>"This imports the random object into Python, it allows it to generate random numbers." import random print("Hello and welcome to Sam's Black Jack!") input("Press &lt;ENTER&gt; to begin.") card1name = 1 card2name = 1 card3name = 1 card4name = 1 card5name = 1 "This defines the values of the character cards." Ace = 1 Jack = 10 Queen = 10 King = 10 decision = 0 "This generates the cards that are in your hand and the dealer's hand to begin with. card1 = int(random.randrange(12) + 1) card2 = int(random.randrange(12) + 1) card3 = int(random.randrange(12) + 1) card4 = int(random.randrange(12) + 1) card5 = int(random.randrange(12) + 1) total1 = card1 + card2 "This makes the value of the Ace equal 11 if the total of your cards is under 21" if total1 &lt;= 21: Ace = 11 "This defines what the cards are" if card1 == 11: card1 = 10 card1name = "Jack" if card1 == 12: card1 = 10 card1name = "Queen" if card1 == 13: card1 = 10 card1name = "King" if card1 == 1: card1 = Ace card1name = "Ace" elif card1: card1name = card1 if card2 == 11: card2 = 10 card2name = "Jack" if card2 == 12: card2 = 10 card2name = "Queen" if card2 == 13: card2 = 10 card2name = "King" if card2 == 1: card2 = Ace card2name = "Ace" elif card2: card2name = card2 if card3 == 11: card3 = 10 card3name = "Jack" if card3 == 12: card3 = 10 card3name = "Queen" if card3 == 13: card3 = 10 card3name= "King" if card3 == 1: card3 = Ace card3name = "Ace" elif card3: card3name = card3 if card4 == 11: card4 = 10 card4name = "Jack" if card4 == 12: card4 = 10 card4name = "Queen" if card4 == 13: card4 = 10 card4name = "King" if card4 == 1: card4 = Ace card4name = "Ace" elif card4: card4name = card4 if card5 == 11: card5 = 10 card5name = "Jack" if card5 == 12: card5 = 10 card5name = "Queen" if card5 == 13: card5 = 10 card5name = "King" if card5 == 1: card5 = Ace card5name = "Ace" elif card5: card5name = card5 "This creates the totals of your hand" total2 = card1 + card2 total3 = card1 + card2 + card3 print("You hand is ", card1name," and", card2name) print("The total of your hand is", total2) decision = input("Do you want to HIT or STAND?").lower() "This is the decision for Hit or Stand" if 'hit' or 'HIT' or 'Hit' in decision: decision = 1 print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if 'STAND' or 'stand' or 'Stand' in decision: print("You have selected STAND") "Dealer's Hand" dealer = card4 + card5 print() print("The dealer's hand is", card4name," and", card5name) if decision == 1 and dealer &lt; total3: print("Congratulations, you beat the dealer!") if decision == 1 and dealer &gt; total3: print("Too bad, the dealer beat you!") </code></pre> <p>Ok, nevermind, i fixed it :D</p> <p>I just changed the Hit and Stand to Yes or No</p> <pre><code>if total2 &lt; 21: decision = input("Do you want to hit? (Yes or No)") "This is the decision for Hit or Stand" if decision == 'Yes': print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if decision == 'No': print("You have selected STAND") </code></pre>
3
2009-02-15T23:34:26Z
552,277
<p>In your code, you wrote:</p> <pre><code>Ace = 1 or 11 </code></pre> <p>I'm afraid this doesn't do what you think. Start the python interpreter, and then type <strong><code>1 or 11</code></strong> into it. Here's what I get:</p> <pre><code>&gt;&gt;&gt; 1 or 11 1 </code></pre> <p>What this means is that when you type: <code>Ace = 1 or 11</code>, python first evaluates the <code>1 or 11</code> bit, and then it sets <code>Ace</code> to be that. In other words, your code is equivalent to:</p> <pre><code>Ace = 1 </code></pre> <p>I suggest you forget about the two possible values for an Ace; just leave it as 1 only. Simplify the rules, get something working, and then you can look at making a full blackjack game.</p>
3
2009-02-16T04:36:34Z
[ "python" ]
Help me implement Blackjack in Python (updated)
551,840
<p>I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it:</p> <ol> <li>Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly.</li> <li>Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins.</li> </ol> <p>Ok, this is what i have gotten so far.</p> <pre><code>"This imports the random object into Python, it allows it to generate random numbers." import random print("Hello and welcome to Sam's Black Jack!") input("Press &lt;ENTER&gt; to begin.") card1name = 1 card2name = 1 card3name = 1 card4name = 1 card5name = 1 "This defines the values of the character cards." Ace = 1 Jack = 10 Queen = 10 King = 10 decision = 0 "This generates the cards that are in your hand and the dealer's hand to begin with. card1 = int(random.randrange(12) + 1) card2 = int(random.randrange(12) + 1) card3 = int(random.randrange(12) + 1) card4 = int(random.randrange(12) + 1) card5 = int(random.randrange(12) + 1) total1 = card1 + card2 "This makes the value of the Ace equal 11 if the total of your cards is under 21" if total1 &lt;= 21: Ace = 11 "This defines what the cards are" if card1 == 11: card1 = 10 card1name = "Jack" if card1 == 12: card1 = 10 card1name = "Queen" if card1 == 13: card1 = 10 card1name = "King" if card1 == 1: card1 = Ace card1name = "Ace" elif card1: card1name = card1 if card2 == 11: card2 = 10 card2name = "Jack" if card2 == 12: card2 = 10 card2name = "Queen" if card2 == 13: card2 = 10 card2name = "King" if card2 == 1: card2 = Ace card2name = "Ace" elif card2: card2name = card2 if card3 == 11: card3 = 10 card3name = "Jack" if card3 == 12: card3 = 10 card3name = "Queen" if card3 == 13: card3 = 10 card3name= "King" if card3 == 1: card3 = Ace card3name = "Ace" elif card3: card3name = card3 if card4 == 11: card4 = 10 card4name = "Jack" if card4 == 12: card4 = 10 card4name = "Queen" if card4 == 13: card4 = 10 card4name = "King" if card4 == 1: card4 = Ace card4name = "Ace" elif card4: card4name = card4 if card5 == 11: card5 = 10 card5name = "Jack" if card5 == 12: card5 = 10 card5name = "Queen" if card5 == 13: card5 = 10 card5name = "King" if card5 == 1: card5 = Ace card5name = "Ace" elif card5: card5name = card5 "This creates the totals of your hand" total2 = card1 + card2 total3 = card1 + card2 + card3 print("You hand is ", card1name," and", card2name) print("The total of your hand is", total2) decision = input("Do you want to HIT or STAND?").lower() "This is the decision for Hit or Stand" if 'hit' or 'HIT' or 'Hit' in decision: decision = 1 print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if 'STAND' or 'stand' or 'Stand' in decision: print("You have selected STAND") "Dealer's Hand" dealer = card4 + card5 print() print("The dealer's hand is", card4name," and", card5name) if decision == 1 and dealer &lt; total3: print("Congratulations, you beat the dealer!") if decision == 1 and dealer &gt; total3: print("Too bad, the dealer beat you!") </code></pre> <p>Ok, nevermind, i fixed it :D</p> <p>I just changed the Hit and Stand to Yes or No</p> <pre><code>if total2 &lt; 21: decision = input("Do you want to hit? (Yes or No)") "This is the decision for Hit or Stand" if decision == 'Yes': print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if decision == 'No': print("You have selected STAND") </code></pre>
3
2009-02-15T23:34:26Z
552,520
<p>Here's a tip to get started: Instead of drawing a number between 1 and 10 and doing something different for face cards, draw a number between 1 and 13, and define a function (or even a class) that interprets these numbers as cards. For example, 1 would map to Ace, 11 to Jack, 2 to a deuce, etc.</p>
0
2009-02-16T07:44:17Z
[ "python" ]
Help me implement Blackjack in Python (updated)
551,840
<p>I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it:</p> <ol> <li>Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly.</li> <li>Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins.</li> </ol> <p>Ok, this is what i have gotten so far.</p> <pre><code>"This imports the random object into Python, it allows it to generate random numbers." import random print("Hello and welcome to Sam's Black Jack!") input("Press &lt;ENTER&gt; to begin.") card1name = 1 card2name = 1 card3name = 1 card4name = 1 card5name = 1 "This defines the values of the character cards." Ace = 1 Jack = 10 Queen = 10 King = 10 decision = 0 "This generates the cards that are in your hand and the dealer's hand to begin with. card1 = int(random.randrange(12) + 1) card2 = int(random.randrange(12) + 1) card3 = int(random.randrange(12) + 1) card4 = int(random.randrange(12) + 1) card5 = int(random.randrange(12) + 1) total1 = card1 + card2 "This makes the value of the Ace equal 11 if the total of your cards is under 21" if total1 &lt;= 21: Ace = 11 "This defines what the cards are" if card1 == 11: card1 = 10 card1name = "Jack" if card1 == 12: card1 = 10 card1name = "Queen" if card1 == 13: card1 = 10 card1name = "King" if card1 == 1: card1 = Ace card1name = "Ace" elif card1: card1name = card1 if card2 == 11: card2 = 10 card2name = "Jack" if card2 == 12: card2 = 10 card2name = "Queen" if card2 == 13: card2 = 10 card2name = "King" if card2 == 1: card2 = Ace card2name = "Ace" elif card2: card2name = card2 if card3 == 11: card3 = 10 card3name = "Jack" if card3 == 12: card3 = 10 card3name = "Queen" if card3 == 13: card3 = 10 card3name= "King" if card3 == 1: card3 = Ace card3name = "Ace" elif card3: card3name = card3 if card4 == 11: card4 = 10 card4name = "Jack" if card4 == 12: card4 = 10 card4name = "Queen" if card4 == 13: card4 = 10 card4name = "King" if card4 == 1: card4 = Ace card4name = "Ace" elif card4: card4name = card4 if card5 == 11: card5 = 10 card5name = "Jack" if card5 == 12: card5 = 10 card5name = "Queen" if card5 == 13: card5 = 10 card5name = "King" if card5 == 1: card5 = Ace card5name = "Ace" elif card5: card5name = card5 "This creates the totals of your hand" total2 = card1 + card2 total3 = card1 + card2 + card3 print("You hand is ", card1name," and", card2name) print("The total of your hand is", total2) decision = input("Do you want to HIT or STAND?").lower() "This is the decision for Hit or Stand" if 'hit' or 'HIT' or 'Hit' in decision: decision = 1 print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if 'STAND' or 'stand' or 'Stand' in decision: print("You have selected STAND") "Dealer's Hand" dealer = card4 + card5 print() print("The dealer's hand is", card4name," and", card5name) if decision == 1 and dealer &lt; total3: print("Congratulations, you beat the dealer!") if decision == 1 and dealer &gt; total3: print("Too bad, the dealer beat you!") </code></pre> <p>Ok, nevermind, i fixed it :D</p> <p>I just changed the Hit and Stand to Yes or No</p> <pre><code>if total2 &lt; 21: decision = input("Do you want to hit? (Yes or No)") "This is the decision for Hit or Stand" if decision == 'Yes': print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if decision == 'No': print("You have selected STAND") </code></pre>
3
2009-02-15T23:34:26Z
822,440
<p>Check <strong>all</strong> of your inputs. As a young lad, I wrote my blackjack program in Fortran. One of my users pointed out that he could:</p> <ol> <li>Enter a negative number as a bet.</li> <li>Deliberately lose.</li> </ol> <p>The program would then do exactly what it was programmed to do:</p> <ol> <li>Subtract the <em>negative</em> bet from the total won/lost.</li> <li>Which is (of course) equivalent to adding a <em>positive</em> number to the total.</li> </ol> <p>Sometimes, you can win by losing....</p>
0
2009-05-04T22:36:59Z
[ "python" ]
"Interfaces" in Python: Yea or Nay?
552,058
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p> <p>Just so we're clear, an interface in Python would look something like this:</p> <pre><code>class ISomething(object): def some_method(): pass def some_other_method(some_argument): pass </code></pre> <p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p> <p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
16
2009-02-16T02:15:17Z
552,066
<p>My personal opinion is positive regarding these <em>interfaces</em> in Python, though I haven't actually use Python interfaces.</p> <p>I have used them quite a bit in PHP with a project because the interfaces really did make that completeness testing you mentioned quite simple.</p>
1
2009-02-16T02:22:55Z
[ "python", "documentation", "interface", "coding-style" ]
"Interfaces" in Python: Yea or Nay?
552,058
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p> <p>Just so we're clear, an interface in Python would look something like this:</p> <pre><code>class ISomething(object): def some_method(): pass def some_other_method(some_argument): pass </code></pre> <p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p> <p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
16
2009-02-16T02:15:17Z
552,068
<p>Seems kind of unnecessary to me - when I'm writing classes like that I usually just make the base class (your <code>ISomething</code>) with no methods, and mention in the actual documentation which methods subclasses are supposed to override.</p>
5
2009-02-16T02:24:33Z
[ "python", "documentation", "interface", "coding-style" ]
"Interfaces" in Python: Yea or Nay?
552,058
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p> <p>Just so we're clear, an interface in Python would look something like this:</p> <pre><code>class ISomething(object): def some_method(): pass def some_other_method(some_argument): pass </code></pre> <p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p> <p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
16
2009-02-16T02:15:17Z
552,076
<p>I'm about to do something similar with my Python project, the only things I would add are:</p> <ul> <li>Extra long, in-depth doc strings for each interface and all the abstract methods.</li> <li>I would add in all the required arguments so there's a definitive list.</li> <li>Raise an exception instead of 'pass'.</li> <li>Prefix all methods so they are obviously part of the interface - interface Foo: def foo_method1()</li> </ul>
3
2009-02-16T02:33:21Z
[ "python", "documentation", "interface", "coding-style" ]