title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How do I write to the console in Google App Engine?
727,410
42
2009-04-07T20:14:52Z
727,438
31
2009-04-07T20:23:22Z
[ "python", "google-app-engine", "logging" ]
Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, usi...
See <https://cloud.google.com/appengine/docs/python/requests#Python_Logging> and <http://docs.python.org/library/logging.html> You probably want to use something like: ``` logging.debug("value of my var is %s", str(var)) ```
How do I write to the console in Google App Engine?
727,410
42
2009-04-07T20:14:52Z
4,380,470
9
2010-12-07T18:54:45Z
[ "python", "google-app-engine", "logging" ]
Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, usi...
@Manjoor You can do the same thing in java. ``` import java.util.logging.Logger; // ... public class MyServlet extends HttpServlet { private static final Logger log = Logger.getLogger(MyServlet.class.getName()); public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExcepti...
How do I write to the console in Google App Engine?
727,410
42
2009-04-07T20:14:52Z
9,660,319
58
2012-03-12T00:23:48Z
[ "python", "google-app-engine", "logging" ]
Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, usi...
You'll want to use the Python's standard `logging` module. ``` import logging logging.info("hello") logging.debug("hi") # this won't show up by default ``` To see calls to `logging.debug()` in the GoogleAppEngineLauncher Logs console, you have to first add the flag `--dev_appserver_log_level=debug` to your app. Howe...
How can I convert Unicode to uppercase to print it?
727,507
28
2009-04-07T20:41:46Z
727,517
47
2009-04-07T20:45:53Z
[ "python", "unicode", "python-2.x", "case-sensitive", "uppercase" ]
I have this: ``` >>> print 'example' example >>> print 'exámple' exámple >>> print 'exámple'.upper() EXáMPLE ``` What I need to do to print: ``` EXÁMPLE ``` *(Where the 'a' gets its accute accent, but in uppercase.)* I'm using Python 2.6.
I think it's as simple as **not** converting to ASCII first. ``` >>> print u'exámple'.upper() EXÁMPLE ```
How can I convert Unicode to uppercase to print it?
727,507
28
2009-04-07T20:41:46Z
727,571
15
2009-04-07T21:00:48Z
[ "python", "unicode", "python-2.x", "case-sensitive", "uppercase" ]
I have this: ``` >>> print 'example' example >>> print 'exámple' exámple >>> print 'exámple'.upper() EXáMPLE ``` What I need to do to print: ``` EXÁMPLE ``` *(Where the 'a' gets its accute accent, but in uppercase.)* I'm using Python 2.6.
In python 2.x, just convert the string to unicode before calling upper(). Using your code, which is in utf-8 format on this webpage: ``` >>> s = 'exámple' >>> s 'ex\xc3\xa1mple' # my terminal is not utf8. c3a1 is the UTF-8 hex for á >>> s.decode('utf-8').upper() u'EX\xc1MPLE' # c1 is the utf-16 aka unicode for á ...
How can I convert Unicode to uppercase to print it?
727,507
28
2009-04-07T20:41:46Z
3,691,817
7
2010-09-11T16:52:59Z
[ "python", "unicode", "python-2.x", "case-sensitive", "uppercase" ]
I have this: ``` >>> print 'example' example >>> print 'exámple' exámple >>> print 'exámple'.upper() EXáMPLE ``` What I need to do to print: ``` EXÁMPLE ``` *(Where the 'a' gets its accute accent, but in uppercase.)* I'm using Python 2.6.
first off, i only use python 3.1 these days; its central merit is to have disambiguated byte strings from unicode objects. this makes the vast majority of text manipulations much safer than used to be the case. weighing in the trillions of user questions regarding python 2.x encoding problems, the `u'äbc` convention o...
Python __str__ and lists
727,761
58
2009-04-07T21:57:59Z
727,779
84
2009-04-07T22:03:00Z
[ "python" ]
In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this: ``` "[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]" ``` Is there a way t...
Calling string on a python list calls the `__repr__` method on each element inside. For some items, `__str__` and `__repr__` are the same. If you want that behavior, do: ``` def __str__(self): ... def __repr__(self): return self.__str__() ```
Python __str__ and lists
727,761
58
2009-04-07T21:57:59Z
727,780
14
2009-04-07T22:03:09Z
[ "python" ]
In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this: ``` "[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]" ``` Is there a way t...
You can use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) to generate a new list with each item str()'d automatically: ``` print([str(item) for item in mylist]) ```
Display some free text in between Django Form fields
727,917
11
2009-04-07T22:59:06Z
862,987
8
2009-05-14T12:15:26Z
[ "python", "django", "django-forms" ]
I have a form like the following: ``` class MyForm(Form): #personal data firstname = CharField() lastname = CharField() #education data university = CharField() major = CharField() #foobar data foobar = ChoiceField() ``` Since some fields (like foobar) are populated from the database i can't use an...
If you want to customize the form, you don't have to render it `form.as_ul`. Django knows how to render foobar if you have set up the forms model properly...try it...no worries. Look at what python on the server sent your page. For example if it sent a django form like this: `return respond(request, user, 'templateNa...
Display some free text in between Django Form fields
727,917
11
2009-04-07T22:59:06Z
1,705,229
14
2009-11-10T02:07:41Z
[ "python", "django", "django-forms" ]
I have a form like the following: ``` class MyForm(Form): #personal data firstname = CharField() lastname = CharField() #education data university = CharField() major = CharField() #foobar data foobar = ChoiceField() ``` Since some fields (like foobar) are populated from the database i can't use an...
One way to do this without displaying your form in the template using form.as\_ul, is with django-uni-form. First you'll have to download it [here](http://github.com/pydanny/django-uni-form) and install it. Then the code for setting up your form could looks something like this: ``` from uni_form.helpers import FormHel...
Securely Erasing Password in Memory (Python)
728,164
23
2009-04-08T01:13:20Z
728,237
29
2009-04-08T02:01:43Z
[ "python", "security", "passwords" ]
How do you store a password entered by the user in memory and erase it securely after it is no longer need? To elaborate, currently we have the following code: ``` username = raw_input('User name: ') password = getpass.getpass() mail = imaplib.IMAP4(MAIL_HOST) mail.login(username, password) ``` After calling the `lo...
Python doesn't have that low of a level of control over memory. Accept it, and move on. The **best** you can do is to `del password` after calling `mail.login` so that no references to the password string object remain. Any solution that purports to be able to do more than that is only giving you a false sense of secur...
Securely Erasing Password in Memory (Python)
728,164
23
2009-04-08T01:13:20Z
1,753,654
12
2009-11-18T04:32:22Z
[ "python", "security", "passwords" ]
How do you store a password entered by the user in memory and erase it securely after it is no longer need? To elaborate, currently we have the following code: ``` username = raw_input('User name: ') password = getpass.getpass() mail = imaplib.IMAP4(MAIL_HOST) mail.login(username, password) ``` After calling the `lo...
There actually -is- a way to securely erase strings in Python; use the memset C function, as per <http://stackoverflow.com/questions/982682/mark-data-as-sensitive-in-python/983525#983525>
Is there a way to overload += in python?
728,361
12
2009-04-08T03:01:52Z
728,376
36
2009-04-08T03:06:14Z
[ "python", "operator-overloading" ]
I know about the `__add__` method to override plus, but when I use that to override +=, I end up with one of two problems: (1) if `__add__` mutates self, then ``` z = x + y ``` will mutate x when I don't really want x to be mutated there. (2) if `__add__` returns a new object, then ``` tmp = z z += x z += y tmp +=...
Yes. Just override the object's `__iadd__` method, which takes the same parameters as `add`. You can find more information [here](http://docs.python.org/reference/datamodel.html#emulating-numeric-types).
Python "round robin"
728,543
4
2009-04-08T04:38:53Z
728,560
10
2009-04-08T04:47:59Z
[ "python", "iteration", "round-robin" ]
Given multiple (x,y) ordered pairs, I want to compare distances between each one of them. So pretend I have a list of ordered pairs: ``` pairs = [a,b,c,d,e,f] ``` I have a function that takes two ordered pairs and find the distance between them: ``` def distance(a,b): from math import sqrt as sqrt from math ...
``` try: from itertools import combinations except ImportError: def combinations(l, n): if n != 2: raise Exception('This placeholder only good for n=2') for i in range(len(l)): for j in range(i+1, len(l)): yield l[i], l[j] coords_list = [(0,0), (3,4), (6,8)] def...
Python "round robin"
728,543
4
2009-04-08T04:38:53Z
728,567
17
2009-04-08T04:51:52Z
[ "python", "iteration", "round-robin" ]
Given multiple (x,y) ordered pairs, I want to compare distances between each one of them. So pretend I have a list of ordered pairs: ``` pairs = [a,b,c,d,e,f] ``` I have a function that takes two ordered pairs and find the distance between them: ``` def distance(a,b): from math import sqrt as sqrt from math ...
in python 2.6, you can use itertools.permutations ``` import itertools perms = itertools.permutations(pairs, 2) distances = (distance(*p) for p in perms) ``` or ``` import itertools combs = itertools.combinations(pairs, 2) distances = (distance(*c) for c in combs) ```
Correct way to define Python source code encoding
728,891
66
2009-04-08T07:35:05Z
729,016
83
2009-04-08T08:20:41Z
[ "python", "encoding" ]
[PEP 263](http://www.python.org/dev/peps/pep-0263/) defines how to define Python source code encoding. Normally, the first 2 lines of a Python file should start with: ``` #!/usr/bin/python # -*- coding: <encoding name> -*- ``` But I have seen a lot of files starting with: ``` #!/usr/bin/python # -*- encoding: <enco...
Check the docs [here](http://docs.python.org/reference/lexical_analysis.html#encoding-declarations): "If a comment in the first or second line of the Python script matches the regular expression `coding[=:]\s*([-\w.]+)`, this comment is processed as an encoding declaration" "The recommended forms of this expression a...
Correct way to define Python source code encoding
728,891
66
2009-04-08T07:35:05Z
729,017
19
2009-04-08T08:21:12Z
[ "python", "encoding" ]
[PEP 263](http://www.python.org/dev/peps/pep-0263/) defines how to define Python source code encoding. Normally, the first 2 lines of a Python file should start with: ``` #!/usr/bin/python # -*- coding: <encoding name> -*- ``` But I have seen a lot of files starting with: ``` #!/usr/bin/python # -*- encoding: <enco...
PEP 263: > the first or second line must match > the regular > expression "coding[:=]\s\*([-\w.]+)" Obviously "en**coding: UTF-8**" matches. PEP provides some examples: ``` #!/usr/bin/python # vim: set fileencoding=<encoding name> : ``` ``` # This Python file uses the following encoding: utf-8 ...
Correct way to define Python source code encoding
728,891
66
2009-04-08T07:35:05Z
36,163,461
9
2016-03-22T19:28:47Z
[ "python", "encoding" ]
[PEP 263](http://www.python.org/dev/peps/pep-0263/) defines how to define Python source code encoding. Normally, the first 2 lines of a Python file should start with: ``` #!/usr/bin/python # -*- coding: <encoding name> -*- ``` But I have seen a lot of files starting with: ``` #!/usr/bin/python # -*- encoding: <enco...
Just copy paste below statement on the top of your program.It will solve character encoding problems ``` #!/usr/bin/env python # -*- coding: utf-8 -*- ```
Python's eval() and globals()
729,248
6
2009-04-08T09:30:31Z
729,251
9
2009-04-08T09:32:51Z
[ "python", "eval" ]
I'm trying to execute a number of functions using eval(), and I need to create some kind of environment for them to run. It is said in documentation that you can pass globals as a second parameter to eval(). But it seems to not work in my case. Here's the simpified example (I tried two approaches, declaring variable g...
\*test\_variable\* should be global in test.py. You're getting a name error because you're trying to declare a variable global that doesn't yet exist. So your my\_test.py file should be like this: ``` test_variable = None def my_func(): print test_variable ``` And running this from the command prompt: ``` >>> ...
Getting file path of imported module
729,583
28
2009-04-08T11:30:21Z
729,605
33
2009-04-08T11:38:35Z
[ "python" ]
How can I get the file path of a module imported in python. I am using Linux (if it matters). Eg: if I am in my home dir and import a module, it should return back the full path of my home directory.
Modules and packages have a `__file__` attribute that has its path information. If the module was imported relative to current working directory, you'll probably want to get its absolute path. ``` import os.path import my_module print os.path.abspath(my_module.__file__) ```
Getting file path of imported module
729,583
28
2009-04-08T11:30:21Z
729,607
8
2009-04-08T11:40:21Z
[ "python" ]
How can I get the file path of a module imported in python. I am using Linux (if it matters). Eg: if I am in my home dir and import a module, it should return back the full path of my home directory.
I've been using this: ``` import inspect import os class DummyClass: pass print os.path.dirname(os.path.abspath(inspect.getsourcefile(DummyClass)) ``` (Edit: This is a "where am I" function - it returns the directory containing the current module. I'm not quite sure if that's what you want).
How to I get scons to invoke an external script?
729,759
16
2009-04-08T12:36:53Z
730,303
15
2009-04-08T14:33:08Z
[ "python", "latex", "scons", "tex" ]
I'm trying to use scons to build a latex document. In particular, I want to get scons to invoke a python program that generates a file containing a table that is \input{} into the main document. I've looked over the scons documentation but it is not immediately clear to me what I need to do. What I wish to achieve is ...
Something along these lines should do - ``` env.Command ('document.tex', '', 'python table_generator.py') env.PDF ('document.pdf', 'document.tex') ``` It declares that 'document.tex' is generated by calling the Python script, and requests a PDF document to be created from this generatd 'document.tex' file. Note that...
Django Model set foreign key to a field of another Model
730,207
13
2009-04-08T14:12:43Z
730,235
12
2009-04-08T14:18:41Z
[ "python", "django", "django-models" ]
Is there any way to set a foreign key in django to a *field* of another model? For example, imagine I have a ValidationRule object. And I want the rule to define what field in another model is to be validated (as well as some other information, such as whether it can be null, a data-type, range, etc.) Is there a way ...
Yes and no. The FK relationship is described at the class level, and mirrors the FK association in the database, so you can't add extra information directly in the FK parameter. Instead, I'd recommend having a string that holds the field name on the other table: ``` class ValidationRule(models.Model): other = mod...
Django Model set foreign key to a field of another Model
730,207
13
2009-04-08T14:12:43Z
2,000,016
41
2010-01-04T14:56:09Z
[ "python", "django", "django-models" ]
Is there any way to set a foreign key in django to a *field* of another model? For example, imagine I have a ValidationRule object. And I want the rule to define what field in another model is to be validated (as well as some other information, such as whether it can be null, a data-type, range, etc.) Is there a way ...
I haven't tried this, but it seems that since Django 1.0 you can do something like: ``` class Foo(models.Model): foo = models.ForeignKey(Bar, to_field='bar') ``` Documentation for this is [here](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.to_field).
Replace html entities with the corresponding utf-8 characters in Python 2.6
730,299
13
2009-04-08T14:32:42Z
730,330
21
2009-04-08T14:36:29Z
[ "python", "html-entities", "python-2.6" ]
I have a html text like this: ``` &lt;xml ... &gt; ``` and I want to convert it to something readable: ``` <xml ...> ``` Any easy (and fast) way to do it in Python?
<http://docs.python.org/library/htmlparser.html> ``` >>> import HTMLParser >>> pars = HTMLParser.HTMLParser() >>> pars.unescape('&copy; &euro;') u'\xa9 \u20ac' >>> print _ © € ```
django to send AND receive email?
730,573
21
2009-04-08T15:38:53Z
731,515
17
2009-04-08T19:43:37Z
[ "python", "django", "email", "pop3", "django-email" ]
I have gotten quite familiar with django's email sending abilities, but I havn't seen anything about it receiving and processing emails from users. Is this functionality available? A few google searches have not turned up very promising results. Though I did find this: <http://stackoverflow.com/questions/348392/receiv...
There's an app called [jutda-helpdesk](http://code.google.com/p/jutda-helpdesk/) that uses Python's `poplib` and `imaplib` to process incoming emails. You just have to have an account somewhere with POP3 or IMAP access. This is adapted from their [get\_email.py](http://code.google.com/p/jutda-helpdesk/source/browse/tr...
Python/wxPython: Doing work continuously in the background
730,645
12
2009-04-08T15:55:06Z
746,144
7
2009-04-14T02:36:37Z
[ "python", "multithreading", "wxpython", "background" ]
I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes. When the user starts a simulation, and defines an initial state, I want the program to render...
I would use a `threading.Thread` to run the code in the background and `wx.CallAfter` to post updates to my window thread to render them to the user. ``` thread = threading.Thread(target=self.do_work) thread.setDaemon(True) thread.start() ... def do_work(self): # processing code here while processing: ...
Python/wxPython: Doing work continuously in the background
730,645
12
2009-04-08T15:55:06Z
755,846
7
2009-04-16T12:10:02Z
[ "python", "multithreading", "wxpython", "background" ]
I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes. When the user starts a simulation, and defines an initial state, I want the program to render...
There's a fair bit of info on the [wxPython wiki about long running tasks](http://wiki.wxpython.org/LongRunningTasks) that might be useful. They basically make use a thread and `wx.PostEvent` to handle communication between the thread and the main wx event loop.
Try/Except in Python: How do you properly ignore Exceptions?
730,764
393
2009-04-08T16:23:00Z
730,778
561
2009-04-08T16:25:10Z
[ "python", "exception", "exception-handling", "try-except" ]
When you just want to do a try-except without handling the exception, how do you do it in Python? Is the following the right way to do it? ``` try : shutil.rmtree ( path ) except : pass ```
``` try: doSomething() except: pass ``` or ``` try: doSomething() except Exception: pass ``` The difference is, that the first one will also catch `KeyboardInterrupt`, `SystemExit` and stuff like that, which are derived directly from `exceptions.BaseException`, not `exceptions.Exception`. See documentat...
Try/Except in Python: How do you properly ignore Exceptions?
730,764
393
2009-04-08T16:23:00Z
730,806
93
2009-04-08T16:32:32Z
[ "python", "exception", "exception-handling", "try-except" ]
When you just want to do a try-except without handling the exception, how do you do it in Python? Is the following the right way to do it? ``` try : shutil.rmtree ( path ) except : pass ```
> When you just want to do a try catch without handling the exception, how do you do it in Python? It depends on what you mean by "handling." If you mean to catch it without taking any action, the code you posted will work. If you mean that you want to take action on an exception without stopping the exception from ...
Try/Except in Python: How do you properly ignore Exceptions?
730,764
393
2009-04-08T16:23:00Z
736,029
78
2009-04-09T21:48:05Z
[ "python", "exception", "exception-handling", "try-except" ]
When you just want to do a try-except without handling the exception, how do you do it in Python? Is the following the right way to do it? ``` try : shutil.rmtree ( path ) except : pass ```
It's generally considered best-practice to only catch the errors you are interested in, in the case of `shutil.rmtree` it's probably `OSError`: ``` >>> shutil.rmtree("/fake/dir") Traceback (most recent call last): [...] OSError: [Errno 2] No such file or directory: '/fake/dir' ``` If you want to silently ignore t...
Try/Except in Python: How do you properly ignore Exceptions?
730,764
393
2009-04-08T16:23:00Z
2,390,566
39
2010-03-05T23:02:39Z
[ "python", "exception", "exception-handling", "try-except" ]
When you just want to do a try-except without handling the exception, how do you do it in Python? Is the following the right way to do it? ``` try : shutil.rmtree ( path ) except : pass ```
For completeness: ``` >>> def divide(x, y): ... try: ... result = x / y ... except ZeroDivisionError: ... print "division by zero!" ... else: ... print "result is", result ... finally: ... print "executing finally clause" ``` ...from the [python tutorial](http://docs.py...
Try/Except in Python: How do you properly ignore Exceptions?
730,764
393
2009-04-08T16:23:00Z
18,677,839
34
2013-09-07T20:55:51Z
[ "python", "exception", "exception-handling", "try-except" ]
When you just want to do a try-except without handling the exception, how do you do it in Python? Is the following the right way to do it? ``` try : shutil.rmtree ( path ) except : pass ```
First I quote the answer of Jack o'Connor from [this thread](http://stackoverflow.com/questions/574730/python-how-to-ignore-an-exception-and-proceed). The referenced thread got closed so I write here: "There's a new way to do this coming in Python 3.4: ``` from contextlib import suppress with suppress(Exception): ...
Try/Except in Python: How do you properly ignore Exceptions?
730,764
393
2009-04-08T16:23:00Z
28,081,414
17
2015-01-22T04:42:53Z
[ "python", "exception", "exception-handling", "try-except" ]
When you just want to do a try-except without handling the exception, how do you do it in Python? Is the following the right way to do it? ``` try : shutil.rmtree ( path ) except : pass ```
> # How to properly ignore Exceptions? There are now several ways of doing this. ## New in Python 3.4: You can import the `suppress` context manager: ``` from contextlib import suppress ``` But only suppress the most specific exception: ``` with suppress(FileNotFoundError): shutil.rmtree(path) ``` You will s...
Multiprocessing or Multithreading?
731,993
24
2009-04-08T21:44:44Z
732,116
18
2009-04-08T22:21:29Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes. When the user starts a simulation, and defines an initial state, I want the program to render...
**"I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information..."** This is only partially true. Threads are part of a process -- threads share memory trivially. Which is as much of a problem as a help -- two threads with casual disregard for each other can o...
Multiprocessing or Multithreading?
731,993
24
2009-04-08T21:44:44Z
732,119
14
2009-04-08T22:22:13Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes. When the user starts a simulation, and defines an initial state, I want the program to render...
* **Stackless**: uses 1 cpu. "Tasklets" must yield voluntarily. The preemption option doesn't work all the time. * **Threaded**: uses 1 cpu. Native threads share time somewhat randomly after running 20-100 python opcodes. * **Multiprocessing**: uses multiple cpu **Update** Indepth Analysis Use threaded for an easy t...
Multiprocessing or Multithreading?
731,993
24
2009-04-08T21:44:44Z
732,199
10
2009-04-08T22:48:35Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes. When the user starts a simulation, and defines an initial state, I want the program to render...
A process has its own memory space. It makes it more difficult to share information, but also makes the program safer (less need for explicit synchronization). That being said, processes can share the same memory in read-only mode. A thread is cheaper to create or kill, but the main difference is that it shares memory...
Multiprocessing or Multithreading?
731,993
24
2009-04-08T21:44:44Z
732,462
14
2009-04-09T01:21:33Z
[ "python", "multithreading", "multiprocessing", "multicore", "python-stackless" ]
I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes. When the user starts a simulation, and defines an initial state, I want the program to render...
There was a good talk on multiprocessing at Pycon this year. The takeaway message was "Only use multiprocessing unless you're sure you have a problem that it will solve, that cannot be solved with threads; otherwise, use threads." Processes have a lot of overhead, and all data to be shared among processes must be seri...
Serving static files with mod_wsgi and Django
732,190
8
2009-04-08T22:47:16Z
732,692
16
2009-04-09T03:42:00Z
[ "python", "django", "mod-wsgi", "mod-python" ]
I have a django application using mod\_python, fairly typical configuration except that media files are being served by a (I know, not recommended) 'media' directory in the document root. I would like to test and maybe deploy with mod\_wsgi but I cannot figure out how to create something simple to serve static files. m...
I run a a dozen or so Django sites on the same server and here's how I configure the media URL's. Each VirtualHost has the following configuration: ``` Alias /media /path/to/media/ <Directory /path/to/media> Include /etc/apache2/vhosts.d/media.include </Directory> ``` This way I can make any changes to the media...
Serving static files with mod_wsgi and Django
732,190
8
2009-04-08T22:47:16Z
1,037,869
13
2009-06-24T11:50:44Z
[ "python", "django", "mod-wsgi", "mod-python" ]
I have a django application using mod\_python, fairly typical configuration except that media files are being served by a (I know, not recommended) 'media' directory in the document root. I would like to test and maybe deploy with mod\_wsgi but I cannot figure out how to create something simple to serve static files. m...
The mod\_wsgi documentation explains how to setup static files which appear at a URL underneath that which the WSGI application is mounted at. See: [http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#Hosting\_Of\_Static\_Files](http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#Hosting%5FOf%5FSta...
Get Primary Key after Saving a ModelForm in Django
732,952
21
2009-04-09T05:38:47Z
732,973
31
2009-04-09T05:50:11Z
[ "python", "django", "django-models", "django-forms" ]
How do I get the primary key after saving a ModelForm? After the form has been validated and saved, I would like to redirect the user to the contact\_details view which requires the primary key of the contact. ``` def contact_create(request): if request.method == 'POST': form = ContactForm(request.POST) ...
The [ModelForm](http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelform)'s [save](http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method) method returns the saved object. Try this: ``` def contact_create(request): if request.method == 'POST': form = ContactForm(reque...
Best way to format integer as string with leading zeros?
733,454
113
2009-04-09T09:15:33Z
733,461
57
2009-04-09T09:16:59Z
[ "python", "string-formatting" ]
I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python: ``` function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i<($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$i...
You most likely just need to format your integer: ``` '%0*d' % (fill, your_int) ``` For example, ``` >>> '%0*d' % (3, 4) '004' ```
Best way to format integer as string with leading zeros?
733,454
113
2009-04-09T09:15:33Z
733,478
288
2009-04-09T09:23:23Z
[ "python", "string-formatting" ]
I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python: ``` function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i<($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$i...
You can use the `zfill()` method to pad a string with zeros: ``` In [3]: str(1).zfill(2) Out[3]: '01' ```
Best way to format integer as string with leading zeros?
733,454
113
2009-04-09T09:15:33Z
733,576
16
2009-04-09T09:59:49Z
[ "python", "string-formatting" ]
I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python: ``` function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i<($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$i...
Python 2.6 allows this: ``` add_nulls = lambda number, zero_count : "{0:0{1}d}".format(number, zero_count) >>>add_nulls(2,3) '002' ```
Best way to format integer as string with leading zeros?
733,454
113
2009-04-09T09:15:33Z
13,919,632
104
2012-12-17T18:10:33Z
[ "python", "string-formatting" ]
I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python: ``` function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i<($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$i...
The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about. ``` i = random.randint(0,99999) print "%05d" % i ``` which will output an string of length 5. --- Edit: In Pytho...
Access list of tuples
733,574
3
2009-04-09T09:59:02Z
733,582
14
2009-04-09T10:03:41Z
[ "python" ]
I have a list that contains several tuples, like: ``` [('a_key', 'a value'), ('another_key', 'another value')] ``` where the first tuple-values act as dictionary-keys. I'm now searching for a python-like way to access the key/value-pairs, like: `"mylist.a_key"` or `"mylist['a_key']"` without iterating over the list...
You can't do it without any iteration. You will either need iteration to convert it into a dict, at which point key access will become possible sans iteration, or you will need to iterate over it for each key access. Converting to a dict seems the better idea-- in the long run it is more efficient, but more importantly...
What is the difference between a site and an app in Django?
734,255
23
2009-04-09T13:35:00Z
734,297
8
2009-04-09T13:43:20Z
[ "python", "django" ]
I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mysite with on...
From the [Django documentation](http://docs.djangoproject.com/en/dev/intro/tutorial01/): > ## Projects vs. apps > > What’s the difference between a project and an app? An app is a Web application that does something — e.g., a weblog system, a database of public records or a simple poll app. A project is a collecti...
What is the difference between a site and an app in Django?
734,255
23
2009-04-09T13:35:00Z
734,321
24
2009-04-09T13:48:52Z
[ "python", "django" ]
I know a site can have many apps but all the examples I see have the site called "mysite". I figured the site would be the name of your site, like StackOverflow for example. Would you do that and then have apps like "authentication", "questions", and "search"? Or would you really just have a site called mysite with on...
Django actually has 3 concepts here: * **Project** (I think this is what you're calling site): This is the directory that contains all the apps. They share a common runtime invocation and can refer to each other. * **App**: This is a set of views, models, and templates. Apps are often designed so they can be plugged i...
Python mechanize - two buttons of type 'submit'
734,893
27
2009-04-09T16:11:15Z
735,031
7
2009-04-09T16:50:55Z
[ "python", "mechanize" ]
I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the forum a...
I would suggest you to use Twill which uses mechanize (mostly monkeypatched). So say you have form with some fields and two submit buttons with **names** "submit\_to\_preview" and "real\_submit". Following code should work. BTW remember this is not threadsafe so you might want to use locks in case if you want to use t...
Python mechanize - two buttons of type 'submit'
734,893
27
2009-04-09T16:11:15Z
1,685,753
19
2009-11-06T06:17:16Z
[ "python", "mechanize" ]
I have a mechanize script written in python that fills out a web form and is supposed to click on the 'create' button. But there's a problem, the form has two buttons. One for 'add attached file' and one for 'create'. Both are of type 'submit', and the attach button is the first one listed. So when I select the forum a...
I tried using the nr parameter, without any luck. I was able to get it to work with a combination of the name and label parameters, where "label" seems to correspond to the "value" in the HTML: Here are my two submit buttons: ``` <input type="submit" name="Preview" value="Preview" /> <input type="submit" name="Creat...
How to access data when form.is_valid() is false
735,545
36
2009-04-09T19:16:03Z
735,593
17
2009-04-09T19:27:13Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
When I have a valid Django form, I can access the data with form.cleaned\_data. But how do I get at the data a user entered when the form is not valid i.e., form.is\_valid is false. I'm trying to access forms within a form set, so form.data seems to just give me a mess.
See <http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation> > Secondly, once we have decided that > the combined data in the two fields we > are considering aren't valid, we must > remember to remove them from the > cleaned\_data. > > In fact, Django will currently > completely wipe out the c...
How to access data when form.is_valid() is false
735,545
36
2009-04-09T19:16:03Z
1,440,599
33
2009-09-17T18:36:49Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
When I have a valid Django form, I can access the data with form.cleaned\_data. But how do I get at the data a user entered when the form is not valid i.e., form.is\_valid is false. I'm trying to access forms within a form set, so form.data seems to just give me a mess.
You can use ``` form.data['field_name'] ``` This way you get the raw value assigned to the field.
How to access data when form.is_valid() is false
735,545
36
2009-04-09T19:16:03Z
11,005,988
12
2012-06-12T22:51:06Z
[ "python", "django", "forms", "formset", "cleaned-data" ]
When I have a valid Django form, I can access the data with form.cleaned\_data. But how do I get at the data a user entered when the form is not valid i.e., form.is\_valid is false. I'm trying to access forms within a form set, so form.data seems to just give me a mess.
I was struggling with a similar issue, and came across a great discussion here: <https://code.djangoproject.com/ticket/10427> It's not at all well documented, but for a live form, you can view a field's value -- as seen by widgets/users -- with the following: ``` form_name['field_name'].value() ```
Static methods in Python?
735,975
956
2009-04-09T21:23:19Z
735,976
58
2009-04-09T21:24:15Z
[ "python", "static-methods" ]
Is it possible to have static methods in Python so I can call them without initializing a class, like: ``` ClassName.StaticMethod ( ) ```
Yes, check out the [staticmethod](http://docs.python.org/library/functions.html#staticmethod) decorator: ``` >>> class C: ... @staticmethod ... def hello(): ... print "Hello World" ... >>> C.hello() Hello World ```
Static methods in Python?
735,975
956
2009-04-09T21:23:19Z
735,978
1,215
2009-04-09T21:24:36Z
[ "python", "static-methods" ]
Is it possible to have static methods in Python so I can call them without initializing a class, like: ``` ClassName.StaticMethod ( ) ```
Yep, using the [staticmethod](https://docs.python.org/2/library/functions.html#staticmethod) decorator ``` class MyClass(object): @staticmethod def the_static_method(x): print x MyClass.the_static_method(2) # outputs 2 ``` Note that some code might use the old method of defining a static method, usin...
Static methods in Python?
735,975
956
2009-04-09T21:23:19Z
738,102
20
2009-04-10T16:00:50Z
[ "python", "static-methods" ]
Is it possible to have static methods in Python so I can call them without initializing a class, like: ``` ClassName.StaticMethod ( ) ```
You don't really need to use the `@staticmethod` decorator. Just declaring a method (that doesn't expect the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do) Mostly, you just use functions thoug...
Static methods in Python?
735,975
956
2009-04-09T21:23:19Z
10,206,355
127
2012-04-18T09:16:03Z
[ "python", "static-methods" ]
Is it possible to have static methods in Python so I can call them without initializing a class, like: ``` ClassName.StaticMethod ( ) ```
I think that Steven is actually right. To answer the original question, then, in order to set up a class method, simply assume that the first argument is not going to be a calling instance, and then make sure that you only call the method from the class. (Note that this answer refers to Python 3.x. In Python 2.x you'l...
Static methods in Python?
735,975
956
2009-04-09T21:23:19Z
28,122,324
18
2015-01-24T04:34:35Z
[ "python", "static-methods" ]
Is it possible to have static methods in Python so I can call them without initializing a class, like: ``` ClassName.StaticMethod ( ) ```
> **Static methods in Python?** > > Is it possible to have static methods in Python so I can call them > without initializing a class, like: > > ``` > ClassName.StaticMethod() > ``` Yes, static methods can be created like this (although it's a bit more [Pythonic](https://www.python.org/dev/peps/pep-0008/) to use under...
Checking if a string can be converted to float in Python
736,043
55
2009-04-09T21:52:33Z
736,050
101
2009-04-09T21:55:39Z
[ "python", "string", "type-conversion" ]
I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy ``` if element.isdigit(): newelement=int(element) ``` Floating point numbers are more difficult. Right now I'm using partition('.') to split the...
I would just use.. ``` try: float(element) except ValueError: print "Not a float" ``` ..it's simple, and it works Another option would be a regular expression: ``` import re if re.match("^\d+?\.\d+?$", element) is None: print "Not float" ```
Checking if a string can be converted to float in Python
736,043
55
2009-04-09T21:52:33Z
20,929,881
51
2014-01-05T03:56:52Z
[ "python", "string", "type-conversion" ]
I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy ``` if element.isdigit(): newelement=int(element) ``` Floating point numbers are more difficult. Right now I'm using partition('.') to split the...
## Python method to check for float: ``` def isfloat(value): try: float(value) return True except ValueError: return False ``` ## Don't get bit by the goblins hiding in the float boat! DO UNIT TESTING! What is, and is not a float may surprise you: ``` Command to parse Is it a ...
Python Superglobal?
736,335
3
2009-04-10T00:22:48Z
736,359
15
2009-04-10T00:35:38Z
[ "python", "python-3.x" ]
Is there is a super global (like PHP) in Python? I have certain variables I want to use throughout my whole project in separate files, classes, and functions, and I don't want to have to keep declaring it throughout each file.
In theory yes, you can start spewing crud into \_\_builtin\_\_: ``` >>> import __builtin__ >>> __builtin__.rubbish= 3 >>> rubbish 3 ``` But, don't do this; it's horrible evilness that will give your applications programming-cancer. > classes and functions and i don't want to have to keep declaring Put them in modul...
Ping FeedBurner in Django App
736,413
4
2009-04-10T01:00:55Z
736,617
12
2009-04-10T03:14:49Z
[ "python", "django", "xml-rpc" ]
I have a django site, and some of the feeds are published through FeedBurner. I would like to ping FeedBurner whenever I save an instance of a particular model. FeedBurner's website says to use the XML-RPC ping mechanism, but I can't find a lot of documentation on how to implement it. What's the easiest way to do the ...
You can use Django's [`signals`](http://docs.djangoproject.com/en/dev/topics/signals/) feature to get a callback after a model is saved: ``` import xmlrpclib from django.db.models.signals import post_save from app.models import MyModel def ping_handler(sender, instance=None, **kwargs): if instance is None: ...
How to read ID3 Tag in an MP3 using Python?
736,813
12
2009-04-10T05:45:24Z
736,823
12
2009-04-10T05:48:51Z
[ "python", "tags", "mp3", "music", "id3" ]
Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)
Mutagen <https://bitbucket.org/lazka/mutagen> *Edited 14/09/23 with current code host location* eyeD3 <http://eyed3.nicfit.net/>
How to read ID3 Tag in an MP3 using Python?
736,813
12
2009-04-10T05:45:24Z
736,869
15
2009-04-10T06:20:26Z
[ "python", "tags", "mp3", "music", "id3" ]
Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)
[Dive into Python](http://diveintopython.net/object_oriented_framework/index.html) uses MP3 ID3 tags as an example.
How to Modify Choices of ModelMultipleChoiceField
738,301
5
2009-04-10T17:34:26Z
738,463
8
2009-04-10T18:30:45Z
[ "python", "django", "django-forms" ]
Let's say I have some contrived models: ``` class Author(Model): name = CharField() class Book(Model): title = CharField() author = ForeignKey(Author) ``` And let's say I want to use a ModelForm for Book: ``` class BookForm(ModelForm): class Meta: model = Book ``` Simple so far. But let'...
Form objects don't have their fields as attributes, you need to look in the "fields" attribute, which is a dictionary: ``` self.fields['author'].queryset = choices ``` If you want to fully understand what's going on here, you might be interested in [this answer](http://stackoverflow.com/questions/500650/django-model-...
In Python, how do I reference a class generically in a static way, like PHP's "self" keyword?
738,467
18
2009-04-10T18:31:50Z
738,480
21
2009-04-10T18:35:45Z
[ "python", "class" ]
PHP classes can use the keyword "self" in a static context, like this: ``` <?php class Test { public static $myvar = 'a'; public static function t() { echo self::$myvar; // Generically reference the current class. echo Test::$myvar; // Same thing, but not generic. } } ?> ``` Obviously I can't use "sel...
In all cases, `self.__class__` is an object's class. <http://docs.python.org/library/stdtypes.html#special-attributes> In the (very) rare case where you are trying to mess with static methods, you actually need [classmethod](http://docs.python.org/library/functions.html#classmethod) for this. ``` class AllStatic( ob...
In Python, how do I reference a class generically in a static way, like PHP's "self" keyword?
738,467
18
2009-04-10T18:31:50Z
738,552
19
2009-04-10T19:04:47Z
[ "python", "class" ]
PHP classes can use the keyword "self" in a static context, like this: ``` <?php class Test { public static $myvar = 'a'; public static function t() { echo self::$myvar; // Generically reference the current class. echo Test::$myvar; // Same thing, but not generic. } } ?> ``` Obviously I can't use "sel...
This should do the trick: ``` class C(object): my_var = 'a' @classmethod def t(cls): print cls.my_var C.t() ```
Date Ordinal Output?
739,241
18
2009-04-11T00:22:31Z
739,266
29
2009-04-11T00:48:09Z
[ "python" ]
I'm wondering if there is a quick and easy way to output ordinals given a number in python. For example, given the number `1`, I'd like to output `"1st"`, the number `2`, `"2nd"`, et cetera, et cetera. This is for working with dates in a breadcrumb trail ``` Home > Venues > Bar Academy > 2009 > April > 01 ``` ...
Or shorten David's answer with: ``` if 4 <= day <= 20 or 24 <= day <= 30: suffix = "th" else: suffix = ["st", "nd", "rd"][day % 10 - 1] ```
Date Ordinal Output?
739,241
18
2009-04-11T00:22:31Z
739,301
26
2009-04-11T01:11:30Z
[ "python" ]
I'm wondering if there is a quick and easy way to output ordinals given a number in python. For example, given the number `1`, I'd like to output `"1st"`, the number `2`, `"2nd"`, et cetera, et cetera. This is for working with dates in a breadcrumb trail ``` Home > Venues > Bar Academy > 2009 > April > 01 ``` ...
Here's a more general solution: ``` def ordinal(n): if 10 <= n % 100 < 20: return str(n) + 'th' else: return str(n) + {1 : 'st', 2 : 'nd', 3 : 'rd'}.get(n % 10, "th") ```
Date Ordinal Output?
739,241
18
2009-04-11T00:22:31Z
21,668,902
9
2014-02-10T04:04:22Z
[ "python" ]
I'm wondering if there is a quick and easy way to output ordinals given a number in python. For example, given the number `1`, I'd like to output `"1st"`, the number `2`, `"2nd"`, et cetera, et cetera. This is for working with dates in a breadcrumb trail ``` Home > Venues > Bar Academy > 2009 > April > 01 ``` ...
Not sure if it existed 5 years ago when you asked this question, but the [inflect](https://pypi.python.org/pypi/inflect) package has a function to do what you're looking for: ``` >>> import inflect >>> p = inflect.engine() >>> for i in range(1,32): ... print p.ordinal(i) ... 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10t...
Customize/remove Django select box blank option
739,260
58
2009-04-11T00:43:58Z
739,286
30
2009-04-11T00:58:57Z
[ "python", "django", "django-models", "django-forms" ]
I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value a...
from the docs > The blank choice will not be included > if the model field has blank=False and > an explicit default value (the default > value will be initially selected > instead). so set the default and you're ok
Customize/remove Django select box blank option
739,260
58
2009-04-11T00:43:58Z
740,011
65
2009-04-11T12:40:43Z
[ "python", "django", "django-models", "django-forms" ]
I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value a...
Haven't tested this, but based on reading Django's code [here](http://code.djangoproject.com/browser/django/trunk/django/forms/models.py#L680) and [here](http://code.djangoproject.com/browser/django/trunk/django/forms/models.py#L710) I believe it should work: ``` class ThingForm(models.ModelForm): class Meta: mo...
Customize/remove Django select box blank option
739,260
58
2009-04-11T00:43:58Z
741,297
15
2009-04-12T05:13:30Z
[ "python", "django", "django-models", "django-forms" ]
I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value a...
With Carl's answer as a guide and after rooting around the Django source for a couple hours I think this is the complete solution: 1. To remove the empty option (extending Carl's example): ``` class ThingForm(models.ModelForm): class Meta: model = Thing def __init__(self, *args, **kwargs): ...
Customize/remove Django select box blank option
739,260
58
2009-04-11T00:43:58Z
11,721,969
8
2012-07-30T12:50:51Z
[ "python", "django", "django-models", "django-forms" ]
I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value a...
As for the django 1.4 all you need is to set the "default" value and "blank=False" on the choices field ``` class MyModel(models.Model): CHOICES = ( (0, 'A'), (1, 'B'), ) choice_field = models.IntegerField(choices=CHOICES, blank=False, default=0) ```
Customize/remove Django select box blank option
739,260
58
2009-04-11T00:43:58Z
24,868,776
12
2014-07-21T15:22:22Z
[ "python", "django", "django-models", "django-forms" ]
I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value a...
You can use this on your model: ``` class MyModel(models.Model): name = CharField('fieldname', max_length=10, default=None) ``` **default=None** is the answer :D NOTE: I tried this on Django 1.7
Why is my send_mail() command not working in Django?
739,289
4
2009-04-11T01:00:40Z
739,291
11
2009-04-11T01:04:03Z
[ "python", "django", "email" ]
I put the following in my settings.py file. The email address there is a test one. I found the email settings from [Webfaction](https://help.webfaction.com/index.php?%5Fm=knowledgebase&%5Fa=viewarticle&kbarticleid=128&nav=0,3)'s site: ``` EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'hekevintran_test' EMAIL_HO...
I have a Django project on Webfaction right now that is properly sending emails. The only difference between your settings and mine is that I did not specify `EMAIL_PORT` or `EMAIL_USE_TLS`. Try it out without those settings and let Django use the default it has and see if it works. For reference's sake, [the default ...
Easiest way to generate localization files
739,314
19
2009-04-11T01:16:14Z
1,079,473
20
2009-07-03T13:55:24Z
[ "python", "localization", "internationalization", "translation" ]
I'm currently writing an app in Python and need to provide localization for it. I can use gettext and the utilities that come with it to generate .po and .mo files. But editing the .po files for each language, one-by-one, seems a bit tedious. Then, creating directories for each language and generating the .mo files, o...
I've just done this for a project I'm working on, for us the process is like this: First, I have a POTFILES.in file which contains a list of source files needing translation. We actually have two files (e.g. admin.in and user.in), as the admin interface doesn't always need translating. So we can send translators only ...
Google App Engine: Intro to their Data Store API for people with SQL Background?
739,490
7
2009-04-11T04:00:13Z
739,501
13
2009-04-11T04:08:26Z
[ "python", "sql", "google-app-engine", "gql" ]
Does anyone have any good information aside from the Google App Engine docs provided by Google that gives a good overview for people with MS SQL background to porting their knowledge and using Google App Engine Data Store API effectively. For Example, if you have a self created Users Table and a Message Table Where t...
Here is a good link: One to Many Join using Google App Engine. <http://blog.arbingersys.com/2008/04/google-app-engine-one-to-many-join.html> Here is another good link: Many to Many Join using Google App Engine: <http://blog.arbingersys.com/2008/04/google-app-engine-many-to-many-join.html> Here is a good discussion ...
setattr with kwargs, pythonic or not?
739,625
15
2009-04-11T06:31:19Z
739,873
18
2009-04-11T11:04:09Z
[ "python", "initialization" ]
I'm using `__init__()` like this in some SQLAlchemy ORM classes that have many parameters (upto 20). ``` def __init__(self, **kwargs): for k, v in kwargs.iteritems(): setattr(self, k, v) ``` Is it "pythonic" to set attributes like this?
Yes. Another way to do this is. ``` def __init__(self, **kwargs): self.__dict__.update( kwargs ) ```
How to make a chain of function decorators in Python?
739,654
1,920
2009-04-11T07:05:31Z
739,665
2,338
2009-04-11T07:16:18Z
[ "python", "decorator", "python-decorators" ]
How can I make two decorators in Python that would do the following? ``` @makebold @makeitalic def say(): return "Hello" ``` ...which should return: ``` "<b><i>Hello</i></b>" ``` I'm not trying to make `HTML` this way in a real application - just trying to understand how decorators and decorator chaining works.
Check out [the documentation](http://docs.python.org/reference/compound_stmts.html#function) to see how decorators work. Here is what you asked for: ``` def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def makeitalic(fn): def wrapped(): return "<i>" + fn() + "</...
How to make a chain of function decorators in Python?
739,654
1,920
2009-04-11T07:05:31Z
739,667
48
2009-04-11T07:19:12Z
[ "python", "decorator", "python-decorators" ]
How can I make two decorators in Python that would do the following? ``` @makebold @makeitalic def say(): return "Hello" ``` ...which should return: ``` "<b><i>Hello</i></b>" ``` I'm not trying to make `HTML` this way in a real application - just trying to understand how decorators and decorator chaining works.
Python decorators add extra functionality to another function An italics decorator could be like ``` def makeitalic(fn): def newFunc(): return "<i>" + fn() + "</i>" return newFunc ``` Note that a function is defined inside a function. What it basically does is replace a function with the newly define...
How to make a chain of function decorators in Python?
739,654
1,920
2009-04-11T07:05:31Z
739,679
110
2009-04-11T07:32:15Z
[ "python", "decorator", "python-decorators" ]
How can I make two decorators in Python that would do the following? ``` @makebold @makeitalic def say(): return "Hello" ``` ...which should return: ``` "<b><i>Hello</i></b>" ``` I'm not trying to make `HTML` this way in a real application - just trying to understand how decorators and decorator chaining works.
Alternatively, you could write a factory function which return a decorator which wraps the return value of the decorated function in a tag passed to the factory function. For example: ``` from functools import wraps def wrap_in_tag(tag): def factory(func): @wraps(func) def decorator(): ...
How to make a chain of function decorators in Python?
739,654
1,920
2009-04-11T07:05:31Z
739,721
72
2009-04-11T08:00:42Z
[ "python", "decorator", "python-decorators" ]
How can I make two decorators in Python that would do the following? ``` @makebold @makeitalic def say(): return "Hello" ``` ...which should return: ``` "<b><i>Hello</i></b>" ``` I'm not trying to make `HTML` this way in a real application - just trying to understand how decorators and decorator chaining works.
It looks like the other people have already told you how to solve the problem. I hope this will help you understand what decorators are. Decorators are just syntactical sugar. This ``` @decorator def func(): ... ``` expands to ``` def func(): ... func = decorator(func) ```
How to make a chain of function decorators in Python?
739,654
1,920
2009-04-11T07:05:31Z
1,594,484
3,332
2009-10-20T13:05:46Z
[ "python", "decorator", "python-decorators" ]
How can I make two decorators in Python that would do the following? ``` @makebold @makeitalic def say(): return "Hello" ``` ...which should return: ``` "<b><i>Hello</i></b>" ``` I'm not trying to make `HTML` this way in a real application - just trying to understand how decorators and decorator chaining works.
If you are not into long explanations, see [Paolo Bergantino’s answer](http://stackoverflow.com/questions/739654/understanding-python-decorators#answer-739665). # Decorator Basics ## Python’s functions are objects To understand decorators, you must first understand that functions are objects in Python. This has ...
How to make a chain of function decorators in Python?
739,654
1,920
2009-04-11T07:05:31Z
4,012,213
51
2010-10-25T06:18:12Z
[ "python", "decorator", "python-decorators" ]
How can I make two decorators in Python that would do the following? ``` @makebold @makeitalic def say(): return "Hello" ``` ...which should return: ``` "<b><i>Hello</i></b>" ``` I'm not trying to make `HTML` this way in a real application - just trying to understand how decorators and decorator chaining works.
And of course you can return lambdas as well from a decorator function: ``` def makebold(f): return lambda: "<b>" + f() + "</b>" def makeitalic(f): return lambda: "<i>" + f() + "</i>" @makebold @makeitalic def say(): return "Hello" print say() ```
How to make a chain of function decorators in Python?
739,654
1,920
2009-04-11T07:05:31Z
8,633,375
14
2011-12-26T06:13:01Z
[ "python", "decorator", "python-decorators" ]
How can I make two decorators in Python that would do the following? ``` @makebold @makeitalic def say(): return "Hello" ``` ...which should return: ``` "<b><i>Hello</i></b>" ``` I'm not trying to make `HTML` this way in a real application - just trying to understand how decorators and decorator chaining works.
Another way of doing the same thing: ``` class bol(object): def __init__(self, f): self.f = f def __call__(self): return "<b>{}</b>".format(self.f()) class ita(object): def __init__(self, f): self.f = f def __call__(self): return "<i>{}</i>".format(self.f()) @bol @ita def sayhi(): return 'h...
How to make a chain of function decorators in Python?
739,654
1,920
2009-04-11T07:05:31Z
11,673,539
8
2012-07-26T16:11:42Z
[ "python", "decorator", "python-decorators" ]
How can I make two decorators in Python that would do the following? ``` @makebold @makeitalic def say(): return "Hello" ``` ...which should return: ``` "<b><i>Hello</i></b>" ``` I'm not trying to make `HTML` this way in a real application - just trying to understand how decorators and decorator chaining works.
A decorator takes the function definition and creates a new function that executes this function and transforms the result. ``` @deco def do(): ... ``` is eqivarent to: ``` do = deco(do) ``` ## Example: ``` def deco(func): def inner(letter): return func(letter).upper() #upper return inner ``` ...
How to make a chain of function decorators in Python?
739,654
1,920
2009-04-11T07:05:31Z
30,283,056
8
2015-05-17T03:26:24Z
[ "python", "decorator", "python-decorators" ]
How can I make two decorators in Python that would do the following? ``` @makebold @makeitalic def say(): return "Hello" ``` ...which should return: ``` "<b><i>Hello</i></b>" ``` I'm not trying to make `HTML` this way in a real application - just trying to understand how decorators and decorator chaining works.
You *could* make two separate decorators that do what you want as illustrated directly below. Note the use of `*args, **kwargs` in the declaration of the `wrapped()` function which supports the decorated function having multiple arguments (which isn't really necessary for the example `say()` function, but is included f...
Python: Locks from `threading` and `multiprocessing` interchangable?
739,687
5
2009-04-11T07:37:24Z
740,197
7
2009-04-11T14:34:57Z
[ "python", "multithreading", "locking", "multiprocessing" ]
Are the locks from the `threading` module interchangeable with those from the `multiprocessing` module?
You can typically use the two interchangeably, but you need to cognizant of the differences. For example, multiprocessing.Event is backed by a named semaphore, which is sensitive to the platform under the application. Multiprocessing.Lock is backed by Multiprocessing.SemLock - so it needs named semaphores. In essence,...
Iterating over object instances of a given class in Python
739,882
12
2009-04-11T11:13:09Z
739,936
7
2009-04-11T11:57:21Z
[ "python", "oop" ]
Given a class that keeps a registry of its Objects: ``` class Person(object): __registry = [] def __init__(self, name): self.__registry.append(self) self.name = name ``` How would I make the following code work (without using Person.\_\_registry): ``` for personobject in Person: print person...
First, do not use double `__` names. They're reserved for use by Python. If you want "private" use single `_`. Second, keep this kind of thing as simple as possible. Don't waste a lot of time and energy on something complex. This is a simple problem, keep the code as simple as possible to get the job done. ``` class ...
Iterating over object instances of a given class in Python
739,882
12
2009-04-11T11:13:09Z
739,954
18
2009-04-11T12:10:20Z
[ "python", "oop" ]
Given a class that keeps a registry of its Objects: ``` class Person(object): __registry = [] def __init__(self, name): self.__registry.append(self) self.name = name ``` How would I make the following code work (without using Person.\_\_registry): ``` for personobject in Person: print person...
You can make your class object iterable with a simple metaclass. ``` class IterRegistry(type): def __iter__(cls): return iter(cls._registry) class Person(object): __metaclass__ = IterRegistry _registry = [] def __init__(self, name): self._registry.append(self) self.name = name...
How can I get a list of locally installed Python modules?
739,993
533
2009-04-11T12:34:18Z
740,018
631
2009-04-11T12:45:45Z
[ "python", "module", "pip" ]
I would like to get a list of Python modules, which are in my Python installation (UNIX server). **How can you get a list of Python modules installed in your computer?**
``` help('modules') ``` in a Python shell/prompt.
How can I get a list of locally installed Python modules?
739,993
533
2009-04-11T12:34:18Z
4,703,670
173
2011-01-16T03:42:15Z
[ "python", "module", "pip" ]
I would like to get a list of Python modules, which are in my Python installation (UNIX server). **How can you get a list of Python modules installed in your computer?**
Now, these methods I tried myself, and I got exactly what was advertised: All the modules. Alas, really you don't care much about the stdlib, you know what you get with a python install. Really, I want the stuff that *I* installed. What actually, surprisingly, worked just fine was: ``` pip freeze ``` Which returne...
How can I get a list of locally installed Python modules?
739,993
533
2009-04-11T12:34:18Z
9,194,180
59
2012-02-08T13:24:27Z
[ "python", "module", "pip" ]
I would like to get a list of Python modules, which are in my Python installation (UNIX server). **How can you get a list of Python modules installed in your computer?**
* In [`ipython`](http://ipython.org/) you can type "`import``Tab`". * In the standard Python interpreter, you can type "`help('modules')`". * At the command-line, you can use [`pydoc`](http://docs.python.org/library/pydoc.html) `modules`. * In a script, call [`pkgutil.iter_modules()`](http://docs.python.org/library/pkg...
How can I get a list of locally installed Python modules?
739,993
533
2009-04-11T12:34:18Z
10,563,781
9
2012-05-12T12:34:44Z
[ "python", "module", "pip" ]
I would like to get a list of Python modules, which are in my Python installation (UNIX server). **How can you get a list of Python modules installed in your computer?**
Very simple searching using [pkgutil.iter\_modules](http://docs.python.org/library/pkgutil.html#pkgutil.iter_modules) ``` from pkgutil import iter_modules a=iter_modules() while True: try: x=a.next() except: break if 'searchstr' in x[1]: print x[1] ```
How can I get a list of locally installed Python modules?
739,993
533
2009-04-11T12:34:18Z
11,164,710
31
2012-06-22T22:02:06Z
[ "python", "module", "pip" ]
I would like to get a list of Python modules, which are in my Python installation (UNIX server). **How can you get a list of Python modules installed in your computer?**
I just use this to see currently used modules: ``` import sys as s s.modules.keys() ``` which shows all modules running on your python. For all built-in modules use: ``` s.modules ``` Which is a dict containing all modules and import objects.
How can I get a list of locally installed Python modules?
739,993
533
2009-04-11T12:34:18Z
12,107,636
10
2012-08-24T10:28:05Z
[ "python", "module", "pip" ]
I would like to get a list of Python modules, which are in my Python installation (UNIX server). **How can you get a list of Python modules installed in your computer?**
I ran into a custom installed python 2.7 on OS X. It required X11 to list modules installed (both using help and pydoc). To be able to list all modules without installing X11 I ran pydoc as http-server, i.e.: ``` pydoc -p 12345 ``` Then it's possible to direct Safari to `http://localhost:12345/` to see all modules.
How can I get a list of locally installed Python modules?
739,993
533
2009-04-11T12:34:18Z
17,870,160
38
2013-07-25T22:56:32Z
[ "python", "module", "pip" ]
I would like to get a list of Python modules, which are in my Python installation (UNIX server). **How can you get a list of Python modules installed in your computer?**
Since pip version 1.3, you've got access to: ``` pip list ``` Which seems to be syntactic sugar for "pip freeze". It will list all of the modules particular to your installation or virtualenv, along with their version numbers. Unfortunately it does not display the current version number of any module, nor does it was...
How can I get a list of locally installed Python modules?
739,993
533
2009-04-11T12:34:18Z
18,399,722
41
2013-08-23T09:45:31Z
[ "python", "module", "pip" ]
I would like to get a list of Python modules, which are in my Python installation (UNIX server). **How can you get a list of Python modules installed in your computer?**
In normal shell just use ``` pydoc modules ```
How can I get a list of locally installed Python modules?
739,993
533
2009-04-11T12:34:18Z
20,879,819
9
2014-01-02T09:26:40Z
[ "python", "module", "pip" ]
I would like to get a list of Python modules, which are in my Python installation (UNIX server). **How can you get a list of Python modules installed in your computer?**
If we need to know list of installed packages in python , we can use 'help' command like given below (in python shell) ``` >>help('modules package') ```