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 |
|---|---|---|---|---|---|---|---|---|---|
Good language to develop a game server in? | 392,624 | 11 | 2008-12-25T08:25:54Z | 392,627 | 19 | 2008-12-25T08:30:16Z | [
"c#",
"java",
"python",
"networking"
] | I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like ... | I hate to say it, and I know I'm risking a down mod here, but it doesn't sound like there's a language out there for you. All programming languages have their quirks and programmers simply have to adapt to them. It's completely possible to write a working server in Python without classes (eliminating the "self" variabl... |
Good language to develop a game server in? | 392,624 | 11 | 2008-12-25T08:25:54Z | 392,650 | 7 | 2008-12-25T08:55:56Z | [
"c#",
"java",
"python",
"networking"
] | I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like ... | What kind of performance do you need?
twisted is great for servers that need lots of concurrency, as is erlang. Either supports massive concurrency easily and has facilities for distributed computing.
If you want to span more than one core in a python app, do the same thing you'd do if you wanted to span more than on... |
Good language to develop a game server in? | 392,624 | 11 | 2008-12-25T08:25:54Z | 392,672 | 7 | 2008-12-25T09:23:36Z | [
"c#",
"java",
"python",
"networking"
] | I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like ... | Speaking of pure performance, if you can run Java 6 you get about 1:1 performance when compared to optimized C++ (special cases notwithstanding, sometimes Java is faster, sometimes C++), the only problem you will have is of course stuff like database libraries, interconnectivity, scalability and such. I believe there's... |
Good language to develop a game server in? | 392,624 | 11 | 2008-12-25T08:25:54Z | 392,814 | 16 | 2008-12-25T13:50:59Z | [
"c#",
"java",
"python",
"networking"
] | I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like ... | Erlang is a language which is designed around concurrency and distribution over several servers, which is perfect for server software. Some links about Erlang and game-servers:
<http://www.devmaster.net/articles/mmo-scalable-server/>
<http://www.erlang-consulting.com/euc2005/mmog/mmog_in_erlang.htm>
I'm thinking of ... |
Good language to develop a game server in? | 392,624 | 11 | 2008-12-25T08:25:54Z | 392,911 | 13 | 2008-12-25T15:57:19Z | [
"c#",
"java",
"python",
"networking"
] | I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like ... | I might be going slightly off-topic here, but the topic interests me as I have (hobby-wise) worked on quite a few game servers (MMORPG servers) - on others' code as well as mine. There is literature out there that will be of interest to you, drop me a note if you want some references.
One thing that strikes me in your... |
How to make a color from a number | 392,728 | 4 | 2008-12-25T10:56:00Z | 392,732 | 10 | 2008-12-25T10:58:37Z | [
"python",
"colors"
] | I have a function that returns a float from 0 to 255. I would like to make a gradient in red color from this, but I need a string in "#FFFFFF" format. Is there a function for that? | You could use:
```
"#%02X0000" % x
``` |
Length of generator output | 393,053 | 81 | 2008-12-25T18:50:18Z | 393,059 | 26 | 2008-12-25T18:53:39Z | [
"python",
"generator",
"iterable"
] | Python provides a nice method for getting length of an eager iterable, `len(x)` that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:
```
def iterlen(x):
n = 0
try:
while True:
next(x)
... | There isn't one because you can't do it in the general case - what if you have a lazy infinite generator? For example:
```
def fib():
a, b = 0, 1
while True:
a, b = b, a + b
yield a
```
This never terminates but will generate the Fibonacci numbers. You can get as many Fibanacci numbers as you ... |
Length of generator output | 393,053 | 81 | 2008-12-25T18:50:18Z | 393,134 | 7 | 2008-12-25T19:55:48Z | [
"python",
"generator",
"iterable"
] | Python provides a nice method for getting length of an eager iterable, `len(x)` that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:
```
def iterlen(x):
n = 0
try:
while True:
next(x)
... | You can use enumerate() to loop through the generated data stream, then return the last number -- the number of items.
I tried to use itertools.count() with itertools.izip() but no luck. This is the best/shortest answer I've come up with:
```
#!/usr/bin/python
import itertools
def func():
for i in 'yummy beer':... |
Length of generator output | 393,053 | 81 | 2008-12-25T18:50:18Z | 7,223,557 | 161 | 2011-08-28T20:04:50Z | [
"python",
"generator",
"iterable"
] | Python provides a nice method for getting length of an eager iterable, `len(x)` that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:
```
def iterlen(x):
n = 0
try:
while True:
next(x)
... | The easiest way is probably just `sum(1 for _ in gen)` where gen is your generator. |
Python sqlite3 and concurrency | 393,554 | 54 | 2008-12-26T06:51:54Z | 393,576 | 34 | 2008-12-26T07:10:39Z | [
"python",
"sqlite"
] | I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:
```
con... | You can use consumer-producer pattern. For example you can create queue that is shared between threads. First thread that fetches data from the web enqueues this data in the shared queue. Another thread that owns database connection dequeues data from the queue and passes it to the database. |
Python sqlite3 and concurrency | 393,554 | 54 | 2008-12-26T06:51:54Z | 393,984 | 10 | 2008-12-26T16:51:24Z | [
"python",
"sqlite"
] | I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:
```
con... | Switch to [multiprocessing](http://docs.python.org/library/multiprocessing.html). It is much better, scales well, can go beyond the use of multiple cores by using multiple CPUs, and the interface is the same as using python threading module.
Or, as Ali suggested, just use [SQLAlchemy's thread pooling mechanism](http:/... |
Python sqlite3 and concurrency | 393,554 | 54 | 2008-12-26T06:51:54Z | 394,331 | 13 | 2008-12-26T21:59:14Z | [
"python",
"sqlite"
] | I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:
```
con... | You shouldn't be using threads at all for this. This is a trivial task for [twisted](http://twistedmatrix.com/) and that would likely take you significantly further anyway.
Use only one thread, and have the completion of the request trigger an event to do the write.
twisted will take care of the scheduling, callbacks... |
Python sqlite3 and concurrency | 393,554 | 54 | 2008-12-26T06:51:54Z | 2,578,401 | 12 | 2010-04-05T12:41:29Z | [
"python",
"sqlite"
] | I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:
```
con... | The following found on [mail.python.org.pipermail.1239789](http://mail.python.org/pipermail/python-list/2010-March/1239789.html)
I have found the solution. I don't know why python documentation has not a single word about this option. So we have to add a new keyword argument to connection function
and we will be ... |
Python sqlite3 and concurrency | 393,554 | 54 | 2008-12-26T06:51:54Z | 2,894,830 | 115 | 2010-05-24T05:03:46Z | [
"python",
"sqlite"
] | I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:
```
con... | Contrary to popular belief, newer versions of sqlite3 **do** support access from multiple threads.
This can be enabled via optional keyword argument `check_same_thread`:
```
sqlite.connect(":memory:", check_same_thread=False)
``` |
What values to use for FastCGI maxrequests, maxspare, minspare, maxchildren? | 393,629 | 5 | 2008-12-26T08:49:51Z | 393,636 | 13 | 2008-12-26T09:00:13Z | [
"python",
"django",
"fastcgi"
] | I'm running a Django app using FastCGI and lighttpd.
Can somebody explain me what I should consider when deciding what value to use for maxrequests, maxspare, minspare, maxchildren?
These options are not too well documented, but seem quite important.
Don't just tell me what they do; I want to understand what *implic... | Let's start with the definition
```
maxrequests: How many requests does a child server before being killed
and a new one forked
maxspare : Maximum number of spare processes to keep running
minspare : Minimum number of spare processes to prefork
maxchildren: Hard limit number of pr... |
python and regular expression with unicode | 393,843 | 57 | 2008-12-26T14:40:04Z | 393,856 | 75 | 2008-12-26T14:57:57Z | [
"python",
"regex",
"character-properties"
] | I need to delete some unicode symbols from the string 'Ø¨ÙØ³ÙÙ
٠اÙÙÙÙÙÙ Ø§ÙØ±ÙÙØÙÙ
ÙÙ°ÙÙ Ø§ÙØ±ÙÙØÙÙÙ
Ù'
I know they exist here for sure. I try:
```
re.sub('([\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+)', '', 'Ø¨ÙØ³ÙÙ
٠اÙÙÙÙÙÙ Ø§ÙØ±ÙÙØÙÙ
ÙÙ°ÙÙ Ø§ÙØ±ÙÙØÙÙÙ
Ù')
```... | Are you using python 2.x or 3.0?
If you're using 2.x, try making the regex string a unicode-escape string, with 'u'. Since it's regex it's good practice to make your regex string a raw string, with 'r'. Also, putting your entire pattern in parentheses is superfluous.
```
re.sub(ur'[\u064B-\u0652\u06D4\u0670\u0674\u06... |
python and regular expression with unicode | 393,843 | 57 | 2008-12-26T14:40:04Z | 393,915 | 44 | 2008-12-26T15:55:11Z | [
"python",
"regex",
"character-properties"
] | I need to delete some unicode symbols from the string 'Ø¨ÙØ³ÙÙ
٠اÙÙÙÙÙÙ Ø§ÙØ±ÙÙØÙÙ
ÙÙ°ÙÙ Ø§ÙØ±ÙÙØÙÙÙ
Ù'
I know they exist here for sure. I try:
```
re.sub('([\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+)', '', 'Ø¨ÙØ³ÙÙ
٠اÙÙÙÙÙÙ Ø§ÙØ±ÙÙØÙÙ
ÙÙ°ÙÙ Ø§ÙØ±ÙÙØÙÙÙ
Ù')
```... | Use [unicode](http://www.amk.ca/python/howto/unicode) strings. Use the [re.UNICODE](http://docs.python.org/library/re.html#re.UNICODE) flag.
```
>>> myre = re.compile(ur'[\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+',
re.UNICODE)
>>> myre
<_sre.SRE_Pattern object at 0xb20b378>
>>> mystr = u'ب... |
Scripting inside a Python application | 393,871 | 4 | 2008-12-26T15:12:10Z | 393,897 | 8 | 2008-12-26T15:36:49Z | [
"python",
"scripting"
] | I'd like to include **Python scripting** in one of my applications, that is written in Python itself.
My application must be able to call external Python functions (written by the user) as **callbacks**. There must be some control on code execution; for example, if the user provided code with syntax errors, the applic... | Use `__import__` to import the files provided by the user. This function will return a module. Use that to call the functions from the imported file.
Use `try..except` both on `__import__` and on the actual call to catch errors.
Example:
```
m = None
try:
m = __import__("external_module")
except:
# invalid m... |
Scripting inside a Python application | 393,871 | 4 | 2008-12-26T15:12:10Z | 393,921 | 7 | 2008-12-26T16:01:20Z | [
"python",
"scripting"
] | I'd like to include **Python scripting** in one of my applications, that is written in Python itself.
My application must be able to call external Python functions (written by the user) as **callbacks**. There must be some control on code execution; for example, if the user provided code with syntax errors, the applic... | If you'd like the user to interactively enter commands, I can highly recommend the [code](http://docs.python.org/library/code.html) module, part of the standard library. The InteractiveConsole and InteractiveInterpreter objects allow for easy entry and evaluation of user input, and errors are handled very nicely, with ... |
Python POST data using mod_wsgi | 394,465 | 14 | 2008-12-26T23:35:59Z | 394,543 | 21 | 2008-12-27T01:22:33Z | [
"python",
"mod-wsgi"
] | This must be a very simple question, but I don't seem to be able to figure out.
I'm using apache + mod\_wsgi to host my python application, and I'd like to get the post content submitted in one of the forms -however, neither the environment values, nor sys.stdin contains any of this data. Mind giving me a quick hand?
... | [PEP 333](http://www.python.org/dev/peps/pep-0333/) says [you must read environ['wsgi.input']](http://www.python.org/dev/peps/pep-0333/#input-and-error-streams).
I just saved the following code and made apache's mod\_wsgi run it. It works.
You must be doing something wrong.
```
from pprint import pformat
def applic... |
Python POST data using mod_wsgi | 394,465 | 14 | 2008-12-26T23:35:59Z | 1,038,071 | 13 | 2009-06-24T12:31:53Z | [
"python",
"mod-wsgi"
] | This must be a very simple question, but I don't seem to be able to figure out.
I'm using apache + mod\_wsgi to host my python application, and I'd like to get the post content submitted in one of the forms -however, neither the environment values, nor sys.stdin contains any of this data. Mind giving me a quick hand?
... | Be aware that technically speaking calling read() or read(-1) on wsgi.input is a violation of the WSGI specification even though Apache/mod\_wsgi allows it. This is because the WSGI specification requires that a valid length argument be supplied. The WSGI specification also says you shouldn't read more data than is spe... |
Override a method at instance level | 394,770 | 33 | 2008-12-27T07:12:07Z | 394,779 | 80 | 2008-12-27T07:35:02Z | [
"python"
] | Is there a way in Python to override a class method at instance level?
For example:
```
class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
``` | Yes, it's possible:
```
class Dog:
def bark(self):
print "Woof"
def new_bark(self):
print "Woof Woof"
foo = Dog()
funcType = type(Dog.bark)
# "Woof"
foo.bark()
# replace bark with new_bark for this object only
foo.bark = funcType(new_bark, foo, Dog)
foo.bark()
# "Woof Woof"
``` |
Override a method at instance level | 394,770 | 33 | 2008-12-27T07:12:07Z | 394,788 | 20 | 2008-12-27T07:46:45Z | [
"python"
] | Is there a way in Python to override a class method at instance level?
For example:
```
class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
``` | ```
class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
def new_bark():
print "WoOoOoF!!"
boby.bark = new_bark
boby.bark() # WoOoOoF!!
```
You can use the `boby` variable inside the function if you need. Since you are overriding the method just for this one inst... |
Override a method at instance level | 394,770 | 33 | 2008-12-27T07:12:07Z | 395,006 | 23 | 2008-12-27T13:44:45Z | [
"python"
] | Is there a way in Python to override a class method at instance level?
For example:
```
class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
``` | Please do not do this as shown. You code becomes unreadable when you monkeypatch an instance to be different from the class.
You cannot debug monkeypatched code.
When you find a bug in `boby` and `print type(boby)`, you'll see that (a) it's a Dog, but (b) for some obscure reason it doesn't bark correctly. This is a n... |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 394,814 | 3,110 | 2008-12-27T08:44:19Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | Yes, it was [added](https://mail.python.org/pipermail/python-dev/2005-September/056846.html) in version 2.5.
The syntax is:
```
a if condition else b
```
First `condition` is evaluated, then either `a` or `b` is returned based on the [Boolean](https://en.wikipedia.org/wiki/Boolean_data_type) value of `condition`
... |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 394,815 | 70 | 2008-12-27T08:44:23Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | From [the documentation](https://docs.python.org/3/reference/expressions.html#conditional-expressions):
> Conditional expressions (sometimes called a âternary operatorâ) have the lowest priority of all Python operations.
>
> The expression `x if C else y` first evaluates the condition, *C* (*not x*); if *C* is tru... |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 394,887 | 152 | 2008-12-27T10:48:27Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | For versions prior to 2.5, there's the trick:
```
[expression] and [on_true] or [on_false]
```
It can give wrong results when `on_true`
has a false boolean value.1
Although it does have the benefit of evaluating expressions left to right, which is clearer in my opinion.
1. [Is there an equivalent of Câs â?:â... |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 470,376 | 359 | 2009-01-22T18:58:09Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | You can index into a tuple:
```
(falseValue, trueValue)[test]
```
`test` needs to return *True* or *False*.
It might be safer to always implement it as:
```
(falseValue, trueValue)[test == True]
```
or you can use the built-in [`bool()`](https://docs.python.org/3.3/library/functions.html#bool) to assure a [Boolea... |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 1,855,173 | 40 | 2009-12-06T11:51:50Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | @up:
Unfortunately, the
```
(falseValue, trueValue)[test]
```
solution doesn't have short-circuit behaviour; thus both falseValue and trueValue are evaluated regardless of the condition. This could be suboptimal or even buggy (i.e. both trueValue and falseValue could be methods and have side-effects).
One solution ... |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 2,919,360 | 79 | 2010-05-27T07:56:06Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | *expression1* if *condition* else *expression2*
```
>>> a = 1
>>> b = 2
>>> 1 if a > b else -1
-1
>>> 1 if a > b else -1 if a < b else 0
-1
``` |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 10,314,837 | 30 | 2012-04-25T11:40:11Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | For Python 2.5 and newer there is a specific syntax:
```
[on_true] if [cond] else [on_false]
```
In older Pythons a ternary operator is not implemented but it's possible to simulate it.
```
cond and on_true or on_false
```
Though, there is a potential problem, which if `cond` evaluates to `True` and `on_true` evalu... |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 14,321,907 | 19 | 2013-01-14T15:56:09Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | You might often find
```
cond and on_true or on_false
```
but this lead to problem when on\_true == 0
```
>>> x = 0
>>> print x == 0 and 0 or 1
1
>>> x = 1
>>> print x == 0 and 0 or 1
1
```
where you would expect for a normal ternary operator this result
```
>>> x = 0
>>> print 0 if x == 0 else 1
0
>>> x = 1
>>... |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 20,093,702 | 10 | 2013-11-20T10:44:12Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | Simulating the python ternary operator.
For example
```
a, b, x, y = 1, 2, 'a greather than b', 'b greater than a'
result = (lambda:y, lambda:x)[a > b]()
```
output:
```
'b greater than a'
``` |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 30,052,371 | 33 | 2015-05-05T12:00:09Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | An operator for a conditional expression in Python was added in 2006 as part of [Python Enhancement Proposal 308](https://www.python.org/dev/peps/pep-0308/). Its form differ from common `?:` operator and it's:
```
<expression1> if <condition> else <expression2>
```
which is equivalent to:
```
if <condition>: <expres... |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 31,429,254 | 11 | 2015-07-15T11:33:41Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | Absolutely, and it is incredibly easy to understand.
```
general syntax : first_expression if bool_expression== true else second_expression
Example: x= 3 if 3 > 2 else 4
# assigns 3 to x if the boolean expression evaluates to true or 4 if it is false
``` |
Does Python have a ternary conditional operator? | 394,809 | 2,655 | 2008-12-27T08:32:18Z | 33,765,206 | 12 | 2015-11-17T19:14:33Z | [
"python",
"operators",
"ternary-operator",
"conditional-operator",
"python-2.5"
] | If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs? | > # Does Python have a ternary conditional operator?
Yes. From the [grammar file](https://docs.python.org/reference/grammar.html):
```
test: or_test ['if' or_test 'else' test] | lambdef
```
The part of interest is:
```
or_test ['if' or_test 'else' test]
```
So, a ternary conditional operation is of the form:
```
... |
Python threads stack_size and segfaults | 394,895 | 2 | 2008-12-27T11:03:00Z | 394,916 | 9 | 2008-12-27T11:28:29Z | [
"python",
"multithreading",
"segmentation-fault",
"stack-size"
] | A web crawler script that spawns at most 500 threads and each thread basically requests for certain data served from the remote server, which each server's reply is different in content and size from others.
i'm setting stack\_size as 756K's for threads
```
threading.stack_size(756*1024)
```
which enables me to have... | **Why** on earth are you spawning 500 threads? That seems like a terrible idea!
Remove threading completely, use an event loop to do the crawling. Your program will be faster, simpler, and easier to maintain.
Lots of threads waiting for network won't make your program *wait faster*. Instead, collect all open sockets ... |
Can I use a ForeignKey in __unicode__ return? | 395,340 | 11 | 2008-12-27T19:58:22Z | 395,347 | 24 | 2008-12-27T20:02:38Z | [
"python",
"django",
"django-models"
] | I have the following classes: Ingredients, Recipe and RecipeContent...
```
class Ingredient(models.Model):
name = models.CharField(max_length=30, primary_key=True)
qty_on_stock = models.IntegerField()
def __unicode__(self):
return self.name
class Recipe(models.Model):
name = models.CharField(... | ```
class RecipeContent(models.Model):
...
def __unicode__(self):
# You can access ForeignKey properties through the field name!
return self.recipe.name
``` |
How to download a file over http with authorization in python 3.0, working around bugs? | 395,451 | 6 | 2008-12-27T21:45:47Z | 395,481 | 19 | 2008-12-27T22:04:53Z | [
"python",
"python-3.x",
"urllib"
] | I have a script that I'd like to continue using, but it looks like I either have to find some workaround for a bug in Python 3, or downgrade back to 2.6, and thus having to downgrade other scripts as well...
Hopefully someone here have already managed to find a workaround.
The problem is that due to the new changes i... | Direct from the Py3k docs: <http://docs.python.org/dev/py3k/library/urllib.request.html#examples>
```
import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
... |
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X? | 395,509 | 6 | 2008-12-27T22:23:48Z | 395,568 | 12 | 2008-12-27T23:09:42Z | [
"python",
"mysql",
"django",
"osx",
"sysadmin"
] | I'm new to the Mac OS X, and I'm just about ready to throw my brand new [MacBook Pro](http://en.wikipedia.org/wiki/MacBook_Pro) out the window. Every tutorial on setting up a Django development environment on [Mac OS X Leopard](http://en.wikipedia.org/wiki/Mac_OS_X_Leopard) is insidiously wrong. They are all skipping o... | Did the MySQL and MySQL-dev installations go smoothly? Can you run MySQL, connect to it and so on? Does `/usr/local/mysql/include` contain lots of header files? (I've got 46 header files there, for reference).
If so, MySQL should be good to go. There are still a few manual steps required to compile MySQL-python, howev... |
Threads in Python | 395,704 | 6 | 2008-12-28T02:22:38Z | 395,716 | 13 | 2008-12-28T02:40:43Z | [
"python",
"multithreading"
] | General tutorial or good resource on how to use threads in Python?
When to use threads, how they are effective, and some general background on threads [specific to Python]? | Threads should be used when you want two things to run at once, or want something to run in the background without slowing down the main process.
My recommendation is to only use threads if you have to. They generally add complexity to a program.
The main documentation for threading is here: <http://docs.python.org... |
Threads in Python | 395,704 | 6 | 2008-12-28T02:22:38Z | 396,055 | 8 | 2008-12-28T10:22:05Z | [
"python",
"multithreading"
] | General tutorial or good resource on how to use threads in Python?
When to use threads, how they are effective, and some general background on threads [specific to Python]? | One thing to remember before spending time and effort in writing a multi-threaded Python application is that there is a [Global Interpreter Lock](http://en.wikipedia.org/wiki/Global_Interpreter_Lock) (GIL), so you won't actually be running more than one thread at a time.
This makes threading unsuitable for trying to t... |
How to check whether a variable is a class or not? | 395,735 | 119 | 2008-12-28T03:08:05Z | 395,741 | 17 | 2008-12-28T03:11:54Z | [
"python",
"reflection"
] | I was wondering how to check whether a variable is a class (not an instance!) or not.
I've tried to use the function `isinstance(object, class_or_type_or_tuple)` to do this, but I don't know what type would a class will have.
For example, in the following code
```
class Foo: pass
isinstance(Foo, **???**) # i want ... | ```
>>> class X(object):
... pass
...
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
``` |
How to check whether a variable is a class or not? | 395,735 | 119 | 2008-12-28T03:08:05Z | 395,782 | 178 | 2008-12-28T03:47:00Z | [
"python",
"reflection"
] | I was wondering how to check whether a variable is a class (not an instance!) or not.
I've tried to use the function `isinstance(object, class_or_type_or_tuple)` to do this, but I don't know what type would a class will have.
For example, in the following code
```
class Foo: pass
isinstance(Foo, **???**) # i want ... | Even better: use the [`inspect.isclass`](https://docs.python.org/library/inspect.html#inspect.isclass) function.
```
>>> import inspect
>>> class X(object):
... pass
...
>>> inspect.isclass(X)
True
>>> x = X()
>>> isinstance(x, X)
True
>>> y = 25
>>> isinstance(y, X)
False
``` |
How to check whether a variable is a class or not? | 395,735 | 119 | 2008-12-28T03:08:05Z | 10,123,520 | 29 | 2012-04-12T12:24:08Z | [
"python",
"reflection"
] | I was wondering how to check whether a variable is a class (not an instance!) or not.
I've tried to use the function `isinstance(object, class_or_type_or_tuple)` to do this, but I don't know what type would a class will have.
For example, in the following code
```
class Foo: pass
isinstance(Foo, **???**) # i want ... | The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implemented
```
def isclass(object):
"""Return true if the object is a class.
Class objects provide these attributes:
__doc__ documentation string
__module__ name of module in which th... |
"MetaClass", "__new__", "cls" and "super" - what is the mechanism exactly? | 395,982 | 23 | 2008-12-28T08:41:45Z | 396,109 | 14 | 2008-12-28T11:36:08Z | [
"python",
"types",
"metaclass",
"super"
] | I have read posts like these:
1. [What is a metaclass in Python?](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python)
2. [What are your (concrete) use-cases for metaclasses in Python?](http://stackoverflow.com/questions/392160/what-are-your-concrete-use-cases-for-metaclasses-in-python)
3. [Python'... | OK, you've thrown quite a few concepts into the mix here! I'm going to pull out a few of the specific questions you have.
In general, understanding super, the MRO and metclasses is made much more complicated because there have been lots of changes in this tricky area over the last few versions of Python.
[Python's ow... |
"MetaClass", "__new__", "cls" and "super" - what is the mechanism exactly? | 395,982 | 23 | 2008-12-28T08:41:45Z | 396,192 | 9 | 2008-12-28T14:11:03Z | [
"python",
"types",
"metaclass",
"super"
] | I have read posts like these:
1. [What is a metaclass in Python?](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python)
2. [What are your (concrete) use-cases for metaclasses in Python?](http://stackoverflow.com/questions/392160/what-are-your-concrete-use-cases-for-metaclasses-in-python)
3. [Python'... | Here's the more pragmatic answer.
**It rarely matters**
1. "[What is a metaclass in Python](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python)". Bottom line, `type` is the metaclass of all classes. You have almost no practical use for this.
```
class X(object):
pass
type(X) == t... |
Checking if two strings are permutations of each other in Python | 396,421 | 15 | 2008-12-28T17:25:17Z | 396,430 | 7 | 2008-12-28T17:33:11Z | [
"algorithm",
"python"
] | I'm checking if two strings `a` and `b` are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:
```
sorted(a) == sorted(b)
```
and
```
all(a.c... | I think the first one is the "obvious" way. It is shorter, clearer, and likely to be faster in many cases because Python's built-in sort is highly optimized. |
Checking if two strings are permutations of each other in Python | 396,421 | 15 | 2008-12-28T17:25:17Z | 396,438 | 14 | 2008-12-28T17:40:03Z | [
"algorithm",
"python"
] | I'm checking if two strings `a` and `b` are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:
```
sorted(a) == sorted(b)
```
and
```
all(a.c... | Here is a way which is O(n), asymptotically better than the two ways you suggest.
```
import collections
def same_permutation(a, b):
d = collections.defaultdict(int)
for x in a:
d[x] += 1
for x in b:
d[x] -= 1
return not any(d.itervalues())
## same_permutation([1,2,3],[2,3,1])
#. True... |
Checking if two strings are permutations of each other in Python | 396,421 | 15 | 2008-12-28T17:25:17Z | 396,523 | 14 | 2008-12-28T18:55:35Z | [
"algorithm",
"python"
] | I'm checking if two strings `a` and `b` are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:
```
sorted(a) == sorted(b)
```
and
```
all(a.c... | "but the first one is slower when (for example) the first char of a is nowhere in b".
This kind of degenerate-case performance analysis is not a good idea. It's a rat-hole of lost time thinking up all kinds of obscure special cases.
Only do the **O**-style "overall" analysis.
Overall, the sorts are **O**( *n* log( *... |
Checking if two strings are permutations of each other in Python | 396,421 | 15 | 2008-12-28T17:25:17Z | 396,570 | 7 | 2008-12-28T19:36:38Z | [
"algorithm",
"python"
] | I'm checking if two strings `a` and `b` are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:
```
sorted(a) == sorted(b)
```
and
```
all(a.c... | heuristically you're probably better to split them off based on string size.
Pseudocode:
```
returnvalue = false
if len(a) == len(b)
if len(a) < threshold
returnvalue = (sorted(a) == sorted(b))
else
returnvalue = naminsmethod(a, b)
return returnvalue
```
If performance is critical, and string size... |
Python-PostgreSQL psycopg2 interface --> executemany | 396,455 | 6 | 2008-12-28T17:51:48Z | 550,849 | 8 | 2009-02-15T13:13:40Z | [
"python",
"postgresql",
"database",
"psycopg"
] | I am currently analyzing a wikipedia dump file; I am extracting a bunch of data from it using python and persisting it into a PostgreSQL db. I am always trying to make things go faster for this file is huge (18GB). In order to interface with PostgreSQL, I am using psycopg2, but this module seems to mimic many other suc... | just copy all the data into a scratch table with the psql \copy command, or use the psycopg cursor.copy\_in() method. Then:
```
insert into mytable
select * from (
select distinct *
from scratch
) uniq
where not exists (
select 1
from mytable
where mytable.mykey = uniq.mykey
);
```
This will de... |
How to instantiate a class in python | 396,856 | 41 | 2008-12-28T23:36:46Z | 396,871 | 46 | 2008-12-28T23:48:05Z | [
"python",
"python-3.x"
] | So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.
```
class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
... | You can instantiate the class by declaring a variable and calling the class as if it were a function:
```
x = mystuff()
print x.average(9,18,27)
```
However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter w... |
How to instantiate a class in python | 396,856 | 41 | 2008-12-28T23:36:46Z | 396,876 | 30 | 2008-12-28T23:51:21Z | [
"python",
"python-3.x"
] | So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.
```
class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
... | From your example, it seems to me you want to use a static method.
```
class mystuff:
@staticmethod
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
print mystuff.average(9,18,27)
```
Please note that an heavy usage of static methods in python is usuall... |
How to instantiate a class in python | 396,856 | 41 | 2008-12-28T23:36:46Z | 23,840,853 | 7 | 2014-05-24T02:51:04Z | [
"python",
"python-3.x"
] | So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.
```
class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
... | To minimally modify your example, you could amend the code to:
```
class myclass(object):
def __init__(self): # this method creates the class object.
pass
def average(self,a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
... |
In Python, how do I find the date of the first Monday of a given week? | 396,913 | 26 | 2008-12-29T00:42:56Z | 396,926 | 33 | 2008-12-29T01:05:22Z | [
"python",
"datetime"
] | If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?
Many thanks | ```
>>> import time
>>> time.asctime(time.strptime('2008 50 1', '%Y %W %w'))
'Mon Dec 15 00:00:00 2008'
```
Assuming the first day of your week is Monday, use `%U` instead of `%W` if the first day of your week is Sunday. See the documentation for [strptime](http://docs.python.org/library/time.html#time.strptime) for d... |
In Python, how do I find the date of the first Monday of a given week? | 396,913 | 26 | 2008-12-29T00:42:56Z | 396,927 | 8 | 2008-12-29T01:05:54Z | [
"python",
"datetime"
] | If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?
Many thanks | This seems to work, assuming week one can have a Monday falling on a day in the last year.
```
from datetime import date, timedelta
def get_first_dow(year, week):
d = date(year, 1, 1)
d = d - timedelta(d.weekday())
dlt = timedelta(days = (week - 1) * 7)
return d + dlt
``` |
In Python, how do I find the date of the first Monday of a given week? | 396,913 | 26 | 2008-12-29T00:42:56Z | 1,287,862 | 28 | 2009-08-17T13:07:00Z | [
"python",
"datetime"
] | If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?
Many thanks | PEZ's and Gerald Kaszuba's solutions work under assumption that January 1st will always be in the first week of a given year. This assumption is not correct for ISO calendar, see [Python's docs](http://docs.python.org/library/datetime.html#datetime.date.isocalendar) for reference. For example, in ISO calendar, week 1 o... |
In Python, how do I find the date of the first Monday of a given week? | 396,913 | 26 | 2008-12-29T00:42:56Z | 3,314,360 | 12 | 2010-07-22T23:36:23Z | [
"python",
"datetime"
] | If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?
Many thanks | ```
from datetime import date, timedelta
def first_monday(year, week):
d = date(year, 1, 4) # The Jan 4th must be in week 1 according to ISO
return d + timedelta(weeks=(week-1), days=-d.weekday())
``` |
Confusing [...] List in Python: What is it? | 397,034 | 16 | 2008-12-29T02:46:31Z | 397,054 | 23 | 2008-12-29T03:02:35Z | [
"python",
"recursion",
"list",
"recursive-datastructures"
] | So I was writing up a simple binary tree in Python and came across [...]
I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed... | It can also appear if you have a circular structure with a list pointing to itself. Like this:
```
>>> a = [1,2]
>>> a.append(a)
>>> a
[1, 2, [...]]
>>>
```
Since python can't print out the structure (it would be an infinite loop) it uses the ellipsis to show that there is recursion in the structure.
---
I'm not qu... |
Reading the target of a .lnk file in Python? | 397,125 | 16 | 2008-12-29T04:31:27Z | 397,147 | 7 | 2008-12-29T04:53:05Z | [
"python",
"directory",
"shortcut",
"target",
"lnk"
] | I'm trying to read the target file/directory of a shortcut (`.lnk`) file from Python. Is there a headache-free way to do it? The [.lnk spec [PDF]](http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf) is way over my head.
I don't mind using Windows-only APIs.
My ultimate goal is to find the `"(My) Videos... | Alternatively, you could try using [SHGetFolderPath()](http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx). The following code might work, but I'm not on a Windows machine right now so I can't test it.
```
import ctypes
shell32 = ctypes.windll.shell32
# allocate MAX_PATH bytes in buffer
video_folder_path =... |
Reading the target of a .lnk file in Python? | 397,125 | 16 | 2008-12-29T04:31:27Z | 571,573 | 23 | 2009-02-20T22:59:37Z | [
"python",
"directory",
"shortcut",
"target",
"lnk"
] | I'm trying to read the target file/directory of a shortcut (`.lnk`) file from Python. Is there a headache-free way to do it? The [.lnk spec [PDF]](http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf) is way over my head.
I don't mind using Windows-only APIs.
My ultimate goal is to find the `"(My) Videos... | **Create a shortcut using Python (via WSH)**
```
import sys
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
shortcut.Targetpath = "t:\\ftemp"
shortcut.save()
```
**Read the Target of a Shortcut using Python (via WSH)**
```
import sys
import w... |
Why doesn't Python have multiline comments? | 397,148 | 194 | 2008-12-29T04:53:17Z | 397,159 | 27 | 2008-12-29T05:04:11Z | [
"python",
"comments",
"multiline"
] | OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,
```
"""Hello, I am a
multiline comment"""
```
and
```
'''Hello, I am a
multiline comment'''
```
But technically speaking these are strings, correct?
I've googled and read the Python style guide, but I was unable to find ... | This likely goes back to the core concept that there should be one obvious way to do a task. Additional comment styles add unnecessary complications and could decrease readability. |
Why doesn't Python have multiline comments? | 397,148 | 194 | 2008-12-29T04:53:17Z | 397,160 | 11 | 2008-12-29T05:05:00Z | [
"python",
"comments",
"multiline"
] | OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,
```
"""Hello, I am a
multiline comment"""
```
and
```
'''Hello, I am a
multiline comment'''
```
But technically speaking these are strings, correct?
I've googled and read the Python style guide, but I was unable to find ... | Well, the triple-quotes are used as multiline comments in docstrings. And # comments are used as inline comments and people get use to it.
Most of script languages don't have multiline comments either. Maybe that's the cause?
See [PEP 0008](http://www.python.org/dev/peps/pep-0008/), section *Comments*
And see if you... |
Why doesn't Python have multiline comments? | 397,148 | 194 | 2008-12-29T04:53:17Z | 397,161 | 223 | 2008-12-29T05:06:00Z | [
"python",
"comments",
"multiline"
] | OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,
```
"""Hello, I am a
multiline comment"""
```
and
```
'''Hello, I am a
multiline comment'''
```
But technically speaking these are strings, correct?
I've googled and read the Python style guide, but I was unable to find ... | I doubt you'll get a better answer than, "Guido didn't feel the need for multi-line comments".
Guido has [tweeted](https://twitter.com/gvanrossum/status/112670605505077248) about this,
> Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-) |
Why doesn't Python have multiline comments? | 397,148 | 194 | 2008-12-29T04:53:17Z | 397,786 | 31 | 2008-12-29T14:16:05Z | [
"python",
"comments",
"multiline"
] | OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,
```
"""Hello, I am a
multiline comment"""
```
and
```
'''Hello, I am a
multiline comment'''
```
But technically speaking these are strings, correct?
I've googled and read the Python style guide, but I was unable to find ... | Triple-quoted text should NOT be considered multi-line comments; by convention, they are [docstrings](http://www.python.org/dev/peps/pep-0257/#rationale). They should describe what your code does and how to use it, but not for things like commenting out blocks of code.
According to Guido, [multiline comments in Python... |
Why doesn't Python have multiline comments? | 397,148 | 194 | 2008-12-29T04:53:17Z | 397,950 | 59 | 2008-12-29T15:44:08Z | [
"python",
"comments",
"multiline"
] | OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,
```
"""Hello, I am a
multiline comment"""
```
and
```
'''Hello, I am a
multiline comment'''
```
But technically speaking these are strings, correct?
I've googled and read the Python style guide, but I was unable to find ... | Multi-line comments are easily breakable. What if you have the following in a simple calculator program?
```
operation = ''
print("Pick an operation: +-*/")
# Get user input here
```
Try to comment that with a multi-line comment:
```
/*
operation = ''
print("Pick an operation: +-*/")
# Get user input here
*/
```
... |
Why doesn't Python have multiline comments? | 397,148 | 194 | 2008-12-29T04:53:17Z | 398,025 | 8 | 2008-12-29T16:18:23Z | [
"python",
"comments",
"multiline"
] | OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,
```
"""Hello, I am a
multiline comment"""
```
and
```
'''Hello, I am a
multiline comment'''
```
But technically speaking these are strings, correct?
I've googled and read the Python style guide, but I was unable to find ... | From [The Zen of Python](http://www.python.org/dev/peps/pep-0020/):
There should be one-- and preferably only one --obvious way to do it. |
Split by \b when your regex engine doesn't support it | 398,560 | 4 | 2008-12-29T20:22:14Z | 398,584 | 9 | 2008-12-29T20:38:26Z | [
"python",
"regex"
] | How can I split by word boundary in a regex engine that doesn't support it?
python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation.
example input:
```
"hello, foo"
```
expected output:
```
['hello', ', ', 'foo']
```
a... | (\W+) can give you the expected output:
```
>>> re.compile(r'(\W+)').split('hello, foo')
['hello', ', ', 'foo']
``` |
Why can't I subclass datetime.date? | 399,022 | 15 | 2008-12-29T23:08:18Z | 400,583 | 31 | 2008-12-30T15:36:32Z | [
"python",
"oop",
"datetime",
"subclass"
] | Why doesn't the following work (Python 2.5.2)?
```
>>> import datetime
>>> class D(datetime.date):
def __init__(self, year):
datetime.date.__init__(self, year, 1, 1)
>>> D(2008)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 3 arguments (1... | Regarding several other answers, this doesn't have anything to do with dates being implemented in C per se. The `__init__` method does nothing because they are *immutable* objects, therefore the constructor (`__new__`) should do all the work. You would see the same behavior subclassing int, str, etc.
```
>>> import da... |
Why can't I subclass datetime.date? | 399,022 | 15 | 2008-12-29T23:08:18Z | 402,024 | 8 | 2008-12-31T01:19:50Z | [
"python",
"oop",
"datetime",
"subclass"
] | Why doesn't the following work (Python 2.5.2)?
```
>>> import datetime
>>> class D(datetime.date):
def __init__(self, year):
datetime.date.__init__(self, year, 1, 1)
>>> D(2008)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 3 arguments (1... | Please read the Python reference on [*Data model*](http://www.python.org/doc/current/reference/datamodel.html), especially about the `__new__` [special method](http://www.python.org/doc/current/reference/datamodel.html#object.__new__).
Excerpt from that page (my italics):
> `__new__()` is intended mainly to allow sub... |
Failing to send email with the Python example | 399,129 | 18 | 2008-12-29T23:51:33Z | 399,240 | 25 | 2008-12-30T00:48:19Z | [
"python",
"email",
"smtplib"
] | I've been trying (and failing) to figure out how to send email via Python.
Trying the example from here:
<http://docs.python.org/library/smtplib.html#smtplib.SMTP>
but added the line `server = smtplib.SMTP_SSL('smtp.gmail.com', 465)` after I got a bounceback about not having an SSL connection.
Now I'm getting this:
... | The following code works for me:
```
import smtplib
FROMADDR = "my.real.address@gmail.com"
LOGIN = FROMADDR
PASSWORD = "my.real.password"
TOADDRS = ["my.real.address@gmail.com"]
SUBJECT = "Test"
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
% (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += "some te... |
How to integrate pep8.py in Eclipse? | 399,956 | 82 | 2008-12-30T10:39:53Z | 2,296,249 | 23 | 2010-02-19T12:36:16Z | [
"python",
"eclipse",
"pydev",
"pep8"
] | A little background:
* [PEP 8](http://www.python.org/dev/peps/pep-0008/) is the *Style Guide for Python Code*. It contains the conventions all python programmers should follow.
* [pep8.py](http://pypi.python.org/pypi/pep8) is a (very useful) script that checks the code formating of a given python script, according to ... | I don't know how to integrate it for whole project, but I have used it as an external tool to analyze an individual file.
Note that the [`pycodestyle`](https://pypi.python.org/pypi/pycodestyle/) package is the official replacement for and is the newer version of the [`pep8`](https://pypi.python.org/pypi/pep8/) package... |
How to integrate pep8.py in Eclipse? | 399,956 | 82 | 2008-12-30T10:39:53Z | 8,532,188 | 75 | 2011-12-16T09:32:19Z | [
"python",
"eclipse",
"pydev",
"pep8"
] | A little background:
* [PEP 8](http://www.python.org/dev/peps/pep-0008/) is the *Style Guide for Python Code*. It contains the conventions all python programmers should follow.
* [pep8.py](http://pypi.python.org/pypi/pep8) is a (very useful) script that checks the code formating of a given python script, according to ... | As of PyDev 2.3.0, `pep8` is integrated in PyDev by default, even shipping with a default version of it.
Open Window > Preferences
It must be enabled in PyDev > Editor > Code Analysis > pep8.py
Errors/Warnings should be shown as markers (as other things in the regular code analysis).
In the event a file is not anal... |
How to integrate pep8.py in Eclipse? | 399,956 | 82 | 2008-12-30T10:39:53Z | 8,830,316 | 10 | 2012-01-12T04:55:42Z | [
"python",
"eclipse",
"pydev",
"pep8"
] | A little background:
* [PEP 8](http://www.python.org/dev/peps/pep-0008/) is the *Style Guide for Python Code*. It contains the conventions all python programmers should follow.
* [pep8.py](http://pypi.python.org/pypi/pep8) is a (very useful) script that checks the code formating of a given python script, according to ... | 1. Open your Eclipse
2. Go to Help and select Install New Software
3. Click the Add button and a "Add Repository" Dialog box will appear
4. You can use any name you like for it. (I used PyDev)
5. For the location, enter "http://pydev.org/updates"
6. Click Ok.
7. You are now in the process of installation. Just wait for... |
Ignoring XML errors in Python | 399,980 | 5 | 2008-12-30T10:48:33Z | 399,996 | 10 | 2008-12-30T10:57:54Z | [
"python",
"xml",
"minidom"
] | I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser.
Is it possible to ignore them, like a browser for example?
I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible. | There is a library called [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/), I think it's what you're looking for.
As you're trying to parse a invalid XML, the normal XML parser won't work. BeautifulSoup is more fail-tolerant, it can still extract information from invalid XML.
> Beautiful Soup is a Python... |
How do you get Python to write down the code of a function it has in memory? | 399,991 | 4 | 2008-12-30T10:55:43Z | 400,040 | 12 | 2008-12-30T11:18:39Z | [
"python",
"artificial-intelligence"
] | When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.
So I have this .py file that reads like:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
```
Then I execute the file and get the data. Since the program is all on my machine ... | ```
vinko@mithril$ more a.py
def foo(a):
print a
vinko@mithril$ more b.py
import a
import inspect
a.foo(89)
print inspect.getsource(a.foo)
vinko@mithril$ python b.py
89
def foo(a):
print a
``` |
Reading and running a mathematical expression in Python | 400,050 | 5 | 2008-12-30T11:22:43Z | 400,081 | 7 | 2008-12-30T11:43:43Z | [
"python"
] | Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it?
Aside from grabbing a string, file or url I have no idea of where to start with this. | Because python supports some algebraic forms, you could do:
```
eval("1 + 1")
```
But this allows the input to execute about anything defined in your env:
```
eval("__import__('sys').exit(1)")
```
Also, if you want to support something python doesn't support, the approach fails:
```
x³ + y² + c
----------- = 0
... |
Resize image in Python without losing EXIF data | 400,788 | 23 | 2008-12-30T16:42:02Z | 400,838 | 12 | 2008-12-30T17:00:10Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] | I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is ... | ```
import jpeg
jpeg.setExif(jpeg.getExif('foo.jpg'), 'foo-resized.jpg')
```
<http://www.emilas.com/jpeg/> |
Resize image in Python without losing EXIF data | 400,788 | 23 | 2008-12-30T16:42:02Z | 4,270,949 | 10 | 2010-11-24T19:57:13Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] | I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is ... | You can use pyexiv2 to copy EXIF data from source image. In the following example image is resized using PIL library, EXIF data copied with pyexiv2 and image size EXIF fields are set with new size.
```
def resize_image(source_path, dest_path, size):
# resize image
image = Image.open(source_path)
image.thum... |
Resize image in Python without losing EXIF data | 400,788 | 23 | 2008-12-30T16:42:02Z | 22,063,878 | 7 | 2014-02-27T09:13:16Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] | I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is ... | There is actually a really simple way of copying EXIF data from a picture to another with only PIL. Though it doesn't permit to modify the exif tags.
```
image = Image.open('test.jpg')
exif = image.info['exif']
# Your picture process here
image = image.rotate(90)
image.save('test_rotated.jpg', 'JPEG', exif=exif)
```
... |
Define css class in django Forms | 401,025 | 125 | 2008-12-30T18:18:41Z | 401,030 | 66 | 2008-12-30T18:20:28Z | [
"python",
"django",
"forms",
"newforms"
] | Assume I have a form
```
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
```
Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?
I w... | Answered my own question. *Sigh*
<http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs>
I didn't realize it was passed into the widget constructor. |
Define css class in django Forms | 401,025 | 125 | 2008-12-30T18:18:41Z | 401,057 | 59 | 2008-12-30T18:32:11Z | [
"python",
"django",
"forms",
"newforms"
] | Assume I have a form
```
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
```
Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?
I w... | Here is another solution for adding class definitions to the widgets after declaring the fields in the class.
```
def __init__(self, *args, **kwargs):
super(SampleClass, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['class'] = 'my_class'
``` |
Define css class in django Forms | 401,025 | 125 | 2008-12-30T18:18:41Z | 4,272,671 | 23 | 2010-11-25T00:06:15Z | [
"python",
"django",
"forms",
"newforms"
] | Assume I have a form
```
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
```
Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?
I w... | Expanding on the method pointed to at docs.djangoproject.com:
```
class MyForm(forms.Form):
comment = forms.CharField(
widget=forms.TextInput(attrs={'size':'40'}))
```
I thought it was troublesome to have to know the native widget type for every field, and thought it funny to override the default jus... |
Define css class in django Forms | 401,025 | 125 | 2008-12-30T18:18:41Z | 4,667,831 | 13 | 2011-01-12T10:42:45Z | [
"python",
"django",
"forms",
"newforms"
] | Assume I have a form
```
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
```
Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?
I w... | Here is Simple way to alter in view. add below in view just before passing it into template.
```
form = MyForm(instance = instance.obj)
form.fields['email'].widget.attrs = {'class':'here_class_name'}
``` |
Define css class in django Forms | 401,025 | 125 | 2008-12-30T18:18:41Z | 4,676,071 | 128 | 2011-01-13T01:56:34Z | [
"python",
"django",
"forms",
"newforms"
] | Assume I have a form
```
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
```
Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?
I w... | Yet another solution that doesn't require changes in python code and so is better for designers and one-off presentational changes: [django-widget-tweaks](https://github.com/kmike/django-widget-tweaks). Hope somebody will find it useful. |
Define css class in django Forms | 401,025 | 125 | 2008-12-30T18:18:41Z | 18,962,481 | 26 | 2013-09-23T14:55:01Z | [
"python",
"django",
"forms",
"newforms"
] | Assume I have a form
```
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
```
Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?
I w... | This can be done using a custom template filter.
considering you render your form this way :
```
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject }}
... |
Define css class in django Forms | 401,025 | 125 | 2008-12-30T18:18:41Z | 20,573,612 | 12 | 2013-12-13T18:35:43Z | [
"python",
"django",
"forms",
"newforms"
] | Assume I have a form
```
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
```
Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?
I w... | If you want all the fields in the form to inherit a certain class, you just define a parent class, that inherits from `forms.ModelForm`, and then inherit from it
```
class BaseForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BaseForm, self).__init__(*args, **kwargs)
for field_name,... |
Naming Python loggers | 401,277 | 44 | 2008-12-30T19:47:53Z | 402,471 | 63 | 2008-12-31T07:31:40Z | [
"python",
"django",
"logging"
] | In Django, I've got loggers all over the place, currently with hard-coded names.
For module-level logging (i.e., in a module of view functions) I have the urge to do this.
```
log = logging.getLogger(__name__)
```
For class-level logging (i.e., in a class `__init__` method) I have the urge to do this.
```
self.log ... | I typically don't use or find a need for class-level loggers, but I keep my modules at a few classes at most. A simple:
```
import logging
LOG = logging.getLogger(__name__)
```
At the top of the module and subsequent:
```
LOG.info('Spam and eggs are tasty!')
```
from anywhere in the file typically gets me to where ... |
Scaling the y-axis with Matplotlib in Python | 401,787 | 4 | 2008-12-30T23:02:08Z | 401,823 | 7 | 2008-12-30T23:21:52Z | [
"python",
"matplotlib"
] | How to scale the y-axis with [Matplotlib](http://matplotlib.sourceforge.net/)? I don't want to change the y-limit, I just want to extend the physical space.
```
^ ^
| |
| |
+----> |
Before +---->
After
``` | Just use a larger height value when you instantiate the figure:
```
from pylab import *
x = linspace(0, 10*pi, 2**10)
y = sin(x)
figure(figsize=(5, 10))
plot(x, y)
show()
```
Where `figsize=(width, height)` and defaults to `(8, 6)`. Values are in inches (the `dpi` keyword arg can be used to define the [DPI](http://en... |
How to store a dictionary on a Django Model? | 402,217 | 32 | 2008-12-31T03:18:15Z | 402,248 | 13 | 2008-12-31T03:39:18Z | [
"python",
"django",
"orm",
"persistence"
] | I need to store some data in a Django model. These data are not equal to all instances of the model.
At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. I... | If you don't need to query by any of this extra data, then you can store it as a serialized dictionary. Use `repr` to turn the dictionary into a string, and `eval` to turn the string back into a dictionary. Take care with eval that there's no user data in the dictionary, or use a safe\_eval implementation. |
How to store a dictionary on a Django Model? | 402,217 | 32 | 2008-12-31T03:18:15Z | 402,526 | 22 | 2008-12-31T08:19:28Z | [
"python",
"django",
"orm",
"persistence"
] | I need to store some data in a Django model. These data are not equal to all instances of the model.
At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. I... | If it's really dictionary like arbitrary data you're looking for you can probably use a two-level setup with one model that's a container and another model that's key-value pairs. You'd create an instance of the container, create each of the key-value instances, and associate the set of key-value instances with the con... |
How do you uninstall a python package that was installed using distutils? | 402,359 | 72 | 2008-12-31T05:26:14Z | 402,444 | 34 | 2008-12-31T07:00:04Z | [
"python"
] | Can you simply delete the directory from your python installation, or are there any lingering files that you must delete? | It varies based on the options that you pass to `install` and the contents of the [distutils configuration files](http://docs.python.org/install/index.html#inst-config-files) on the system/in the package. I don't believe that any files are modified outside of directories specified in these ways.
Notably, [distutils do... |
How do you uninstall a python package that was installed using distutils? | 402,359 | 72 | 2008-12-31T05:26:14Z | 403,563 | 12 | 2008-12-31T17:31:17Z | [
"python"
] | Can you simply delete the directory from your python installation, or are there any lingering files that you must delete? | The three things that get installed that you will need to delete are:
1. Packages/modules
2. Scripts
3. Data files
Now on my linux system these live in:
1. /usr/lib/python2.5/site-packages
2. /usr/bin
3. /usr/share
But on a windows system they are more likely to be entirely within the Python distribution directory.... |
How do you uninstall a python package that was installed using distutils? | 402,359 | 72 | 2008-12-31T05:26:14Z | 405,406 | 7 | 2009-01-01T20:06:35Z | [
"python"
] | Can you simply delete the directory from your python installation, or are there any lingering files that you must delete? | Yes, it is safe to simply delete anything that distutils installed. That goes for installed folders or .egg files. Naturally anything that depends on that code will no longer work.
If you want to make it work again, simply re-install.
By the way, if you are using distutils also consider using the multi-version featur... |
How do you uninstall a python package that was installed using distutils? | 402,359 | 72 | 2008-12-31T05:26:14Z | 8,471,143 | 11 | 2011-12-12T07:27:00Z | [
"python"
] | Can you simply delete the directory from your python installation, or are there any lingering files that you must delete? | Another time stamp based hack:
1. Create an anchor: `touch /tmp/ts`
2. Reinstall the package to be removed: `python setup.py install --prefix=<PREFIX>`
3. Remove files what are more recent than the anchor file: `find <PREFIX> -cnewer /tmp/ts | xargs rm -r` |
Help--Function Pointers in Python | 402,364 | 3 | 2008-12-31T05:34:38Z | 402,369 | 20 | 2008-12-31T05:41:07Z | [
"python",
"function",
"pointers"
] | My idea of program:
I have a dictionary:
```
options = { 'string' : select_fun(function pointer),
'float' : select_fun(function pointer),
'double' : select_fun(function pointer)
}
```
whatever type comes single function `select_fun(function pointer)` gets called.
Inside `select_fun(function pointer)`,I will have dif... | Could you be more specific on what you're trying to do? You don't have to do anything special to get function pointers in Python -- you can pass around functions like regular objects:
```
def plus_1(x):
return x + 1
def minus_1(x):
return x - 1
func_map = {'+' : plus_1, '-' : minus_1}
func_map['+'](3) # re... |
Caching result of setUp() using Python unittest | 402,483 | 7 | 2008-12-31T07:43:31Z | 402,492 | 14 | 2008-12-31T07:48:46Z | [
"python",
"unit-testing"
] | I currently have a unittest.TestCase that looks like..
```
class test_appletrailer(unittest.TestCase):
def setup(self):
self.all_trailers = Trailers(res = "720", verbose = True)
def test_has_trailers(self):
self.failUnless(len(self.all_trailers) > 1)
# ..more tests..
```
This works fine,... | How about using a class member that only gets initialized once?
```
class test_appletrailer(unittest.TestCase):
all_trailers = None
def setup(self):
# Only initialize all_trailers once.
if self.all_trailers is None:
self.__class__.all_trailers = Trailers(res = "720", verbose = Tru... |
Caching result of setUp() using Python unittest | 402,483 | 7 | 2008-12-31T07:43:31Z | 403,541 | 8 | 2008-12-31T17:25:38Z | [
"python",
"unit-testing"
] | I currently have a unittest.TestCase that looks like..
```
class test_appletrailer(unittest.TestCase):
def setup(self):
self.all_trailers = Trailers(res = "720", verbose = True)
def test_has_trailers(self):
self.failUnless(len(self.all_trailers) > 1)
# ..more tests..
```
This works fine,... | An alternative to the proposed solution would be to use a more featured test runner like [Nose](http://somethingaboutorange.com/mrl/projects/nose/). With Nose, you can have module-level setup functions which will be run once for a test module. Since it is entirely compatible with unittest, you wouldn't have to change a... |
How to determine the variable type in Python? | 402,504 | 607 | 2008-12-31T07:58:57Z | 402,507 | 172 | 2008-12-31T08:02:04Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] | How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?
How do I view it? | You may be looking for the `type()` function.
See the examples below, but there's no "unsigned" type in Python just like Java.
Positive integer:
```
>>> v = 10
>>> type(v)
<type 'int'>
```
*Large* positive integer:
```
>>> v = 100000000000000
>>> type(v)
<type 'long'>
```
Negative integer:
```
>>> v = -10
>>> ty... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.