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 |
|---|---|---|---|---|---|---|---|---|---|
Python in tcsh | 616,440 | 5 | 2009-03-05T20:16:30Z | 616,558 | 9 | 2009-03-05T20:54:26Z | [
"python",
"tcsh"
] | I don't have much experience with tcsh, but I'm interested in learning. I've been having issues getting Python to see PYTHONPATH. I can echo $PYTHONPATH, and it is correct, but when I start up Python, my paths do not show up in sys.path. Any ideas?
EDIT:
```
[dmcdonal@tg-steele ~]$ echo $PYTHONPATH
/home/ba01/u116/dm... | How are you setting PYTHONPATH? You might be confusing tcsh's set vs. setenv. Use "set" to set what tcsh calls *shell variables* and use "setenv" to set *environment variables*. So, you need to use setenv in order for Python to see it. For example:
```
$ set FOO='bar'
$ echo $FOO
bar
$ python -c 'import os; print os.g... |
How do I duplicate sys.stdout to a log file in python? | 616,645 | 105 | 2009-03-05T21:12:13Z | 616,672 | 57 | 2009-03-05T21:21:21Z | [
"python",
"tee"
] | Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?
My app has two modes. In interactive mode, I want all output to go to the... | **The `print` statement will call the `write()` method of any object you assign to sys.stdout.**
I would spin up a small class to write to two places at once...
```
import sys
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open("log.dat", "a")
def write(self,... |
How do I duplicate sys.stdout to a log file in python? | 616,645 | 105 | 2009-03-05T21:12:13Z | 616,686 | 102 | 2009-03-05T21:24:48Z | [
"python",
"tee"
] | Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?
My app has two modes. In interactive mode, I want all output to go to the... | I had this same issue before and found this snippet very useful:
```
class Tee(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
self.file.close()
def write(sel... |
How do I duplicate sys.stdout to a log file in python? | 616,645 | 105 | 2009-03-05T21:12:13Z | 616,709 | 52 | 2009-03-05T21:31:47Z | [
"python",
"tee"
] | Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?
My app has two modes. In interactive mode, I want all output to go to the... | What you really want is `logging` module from standard library. Create a logger and attach two handlers, one would be writing to a file and the other to stdout or stderr.
See [Logging to multiple destinations](http://docs.python.org/library/logging.html#logging-to-multiple-destinations) for details |
How do I duplicate sys.stdout to a log file in python? | 616,645 | 105 | 2009-03-05T21:12:13Z | 648,322 | 8 | 2009-03-15T18:49:54Z | [
"python",
"tee"
] | Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?
My app has two modes. In interactive mode, I want all output to go to the... | (Ah, just re-read your question and see that this doesn't quite apply.)
Here is a sample program that makes uses the [python logging module](http://docs.python.org/library/logging.html). This logging module has been in all versions since 2.3. In this sample the logging is configurable by command line options.
In quit... |
How do I duplicate sys.stdout to a log file in python? | 616,645 | 105 | 2009-03-05T21:12:13Z | 651,718 | 30 | 2009-03-16T19:00:09Z | [
"python",
"tee"
] | Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?
My app has two modes. In interactive mode, I want all output to go to the... | Since you're comfortable spawning external processes from your code, you could use `tee` itself. I don't know of any Unix system calls that do exactly what `tee` does.
```
import subprocess, os, sys
# Unbuffer output
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
tee = subprocess.Popen(["tee", "log.txt"], stdin... |
How do I duplicate sys.stdout to a log file in python? | 616,645 | 105 | 2009-03-05T21:12:13Z | 3,423,392 | 9 | 2010-08-06T11:39:55Z | [
"python",
"tee"
] | Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?
My app has two modes. In interactive mode, I want all output to go to the... | I wrote a `tee()` implementation in Python that should work for most cases, and it works on Windows also.
<https://github.com/pycontribs/tendo>
Also, you can use it in combination with `logging` module from Python if you want. |
How do I detect if my appengine app is being accessed by an iphone/ipod touch? | 617,202 | 11 | 2009-03-05T23:46:26Z | 738,766 | 7 | 2009-04-10T20:27:02Z | [
"iphone",
"python",
"google-app-engine",
"web-applications"
] | I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax? | This is the syntax I was looking for, works with iphone and ipod touch:
```
uastring = self.request.headers.get('user_agent')
if "Mobile" in uastring and "Safari" in uastring:
# do iphone / ipod stuff
``` |
How to find whether a number belongs to a particular range in Python? | 618,093 | 30 | 2009-03-06T08:49:08Z | 618,099 | 23 | 2009-03-06T08:51:47Z | [
"python",
"range"
] | Suppose I want to check if `x` belongs to range 0 to 0.5. How can I do it? | ```
print 'yes' if 0 < x < 0.5 else 'no'
```
[`range()`](http://docs.python.org/library/functions.html#range) is for generating arrays of consecutive integers |
How to find whether a number belongs to a particular range in Python? | 618,093 | 30 | 2009-03-06T08:49:08Z | 618,100 | 59 | 2009-03-06T08:53:15Z | [
"python",
"range"
] | Suppose I want to check if `x` belongs to range 0 to 0.5. How can I do it? | No, you can't do that. `range()` expects integer arguments. If you want to know if `x` is inside this range try some form of this:
```
print 0.0 <= x <= 0.5
```
Be careful with your upper limit. If you use `range()` it is excluded (`range(0, 5)` does not include 5!) |
Python regex split a string by one of two delimiters | 618,551 | 7 | 2009-03-06T11:36:13Z | 618,562 | 13 | 2009-03-06T11:42:11Z | [
"python",
"regex"
] | I wanted to cut up a string of email addresses which may be separated by any combination of commas and white-space.
And I thought it would be pretty straight-forward :
```
sep = re.compile('(\s*,*)+')
print sep.split("""[email protected], [email protected]
[email protected],,[email protected]""")
```
But it isn't. I can't find a regex that won't leave... | Doh!
It's just this.
```
sep = re.compile('[\s,]+')
``` |
Django: using <select multiple> and POST | 618,557 | 34 | 2009-03-06T11:39:14Z | 618,626 | 86 | 2009-03-06T12:06:52Z | [
"python",
"django",
"http"
] | I'm using something like this in my template
```
<select multiple="multiple" name="services" id="services" size="5">
{% for service in services %}
<option value="{{service.id}}">{{service}}</option>
{% endfor %}
</select>
```
When I view the POST data in Firebug or the Django debug, I see it only sends ... | ```
request.POST.getlist('services')
``` |
Optimizing Jinja2 Environment creation | 618,827 | 8 | 2009-03-06T13:19:58Z | 1,020,013 | 8 | 2009-06-19T21:02:24Z | [
"python",
"google-app-engine",
"jinja2"
] | My application is running on Google App Engine and most of requests constantly gets yellow flag due to high CPU usage. Using profiler I tracked the issue down to the routine of creating `jinja2.Environment` instance.
I'm creating the instance at module level:
```
from jinja2 import Environment, FileSystemLoader
jinja... | Armin suggested to pre-compile Jinja2 templates to python code, and use the compiled templates in production. So I've made a compiler/loader for that, and it now renders some complex templates 13 times faster, throwing away **all** the parsing overhead. The related discussion with link to the repository is [here](http:... |
dateutil.rrule.rrule.between() gives only dates after now | 618,910 | 4 | 2009-03-06T13:48:08Z | 618,939 | 10 | 2009-03-06T13:58:08Z | [
"python",
"python-dateutil",
"rrule"
] | From the IPython console:
```
In [16]: b
Out[16]: datetime.datetime(2008, 3, 1, 0, 0)
In [17]: e
Out[17]: datetime.datetime(2010, 5, 2, 0, 0)
In [18]: rrule(MONTHLY).between(b, e, inc=True)
Out[18]:
[datetime.datetime(2009, 3, 6, 14, 42, 1),
datetime.datetime(2009, 4, 6, 14, 42, 1),
datetime.datetime(2009, 5, 6, 1... | You need to pass `b` into rrule, like this:
```
rrule(MONTHLY, dtstart = b).between(b, e, inc=True)
```
From these docs (<http://labix.org/python-dateutil>), it looks like calling rrule without specifying dtstart will use datetime.datetime.now() as the start point for the sequence that you're later applying `between`... |
What does PyPy have to offer over CPython, Jython, and IronPython? | 619,437 | 28 | 2009-03-06T16:25:49Z | 619,544 | 38 | 2009-03-06T16:46:37Z | [
"python",
"interpreter",
"pypy"
] | From what I have seen and read on blogs, PyPy is a very ambitious project. What are some advantages it will bring to the table over its siblings (CPython, Jython, and IronPython)? Is it speed, cross-platform compatibility (including mobile platforms), the ability to use c-extensions without the GIL, or is this more of ... | PyPy is really two projects:
* An interpreter compiler toolchain allowing you to write interpreters in RPython (a static subset of Python) and have cross-platform interpreters compiled standalone, for the JVM, for .NET (etc)
* An implementation of Python in RPython
These two projects allow for *many* things.
* Maint... |
Progammatically restart windows to make system logs think user logged out | 620,154 | 4 | 2009-03-06T19:44:12Z | 620,194 | 10 | 2009-03-06T19:53:01Z | [
"python",
"windows",
"automation"
] | I'm hoping to make a quick script to log-out/restart windows at a set time. For example, start a script to "Restart windows in ten minutes". For this implementation I don't need it to run in the background or pop=up on its own. I just want to set the script and walk away knowing that the computer will log-out/restart a... | The shutdown command in batch will shutdown the computer
-s to turn it off,
-f to force it,
-t xx to have it shutdown in x seconds,
use the subprocess module in python to call it.
Since you want it to shutdown at a specific time, to automate the job completely you'd need to use something like autosys. Set the script... |
Convert Year/Month/Day to Day of Year in Python | 620,305 | 60 | 2009-03-06T20:34:32Z | 620,322 | 17 | 2009-03-06T20:37:27Z | [
"python",
"datetime"
] | I'm using the Python "datetime" module, i.e.:
```
>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 13:24:58.857946
```
and I would like to compute the day of year that is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. [Here's web-based DateTime calculator... | Couldn't you use [`strftime`](http://docs.python.org/library/datetime.html#strftime-behavior)?
```
>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 15:37:02.484000
>>> today.strftime('%j')
'065'
```
### Edit
As noted in the comments, if you wish to do comparisons or calculations wit... |
Convert Year/Month/Day to Day of Year in Python | 620,305 | 60 | 2009-03-06T20:34:32Z | 623,312 | 133 | 2009-03-08T09:27:24Z | [
"python",
"datetime"
] | I'm using the Python "datetime" module, i.e.:
```
>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 13:24:58.857946
```
and I would like to compute the day of year that is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. [Here's web-based DateTime calculator... | There is a very simple solution:
```
day_of_year = datetime.now().timetuple().tm_yday
``` |
Convert Year/Month/Day to Day of Year in Python | 620,305 | 60 | 2009-03-06T20:34:32Z | 13,032,755 | 7 | 2012-10-23T14:28:51Z | [
"python",
"datetime"
] | I'm using the Python "datetime" module, i.e.:
```
>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 13:24:58.857946
```
and I would like to compute the day of year that is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. [Here's web-based DateTime calculator... | [DZinX's answer](http://stackoverflow.com/a/623312/40785) is a great answer for the question. I found this question while looking for the inverse function. I found this to work :
```
import datetime
datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S')
>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)
datet... |
How to import a Django project settings.py Python file from a sub-directory? | 620,342 | 16 | 2009-03-06T20:42:11Z | 620,462 | 14 | 2009-03-06T21:21:17Z | [
"python",
"django"
] | I created a sub-directory of my Django project called `bin` where I want to put all command-line run Python scripts. Some of these scripts need to import my Django project `settings.py` file that is in a parent directory of `bin`.
How can I import the `settings.py` file from a sub-directory of the project?
The code t... | I think your approach may be over-complicating something that Django 1.x provides for you. As long as your project is in your python path, you can set the environment variable DJANGO\_SETTINGS\_MODULE at the top of your script like so:
```
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
```
In y... |
How to import a Django project settings.py Python file from a sub-directory? | 620,342 | 16 | 2009-03-06T20:42:11Z | 622,457 | 10 | 2009-03-07T20:38:00Z | [
"python",
"django"
] | I created a sub-directory of my Django project called `bin` where I want to put all command-line run Python scripts. Some of these scripts need to import my Django project `settings.py` file that is in a parent directory of `bin`.
How can I import the `settings.py` file from a sub-directory of the project?
The code t... | This is going one level up from your question, but probably the best solution here is to implement your scripts as [custom manage.py (django-admin.py) commands](http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#howto-custom-management-commands). This gives you all of Django's functionality (includi... |
How to jump to a particular line in a huge text file? | 620,367 | 74 | 2009-03-06T20:49:52Z | 620,397 | 18 | 2009-03-06T20:58:06Z | [
"python",
"text-files"
] | Are there any alternatives to the code below:
```
startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
```
If I'm processing a huge text... | [linecache](http://docs.python.org/library/linecache.html):
> The [`linecache`](https://docs.python.org/3/library/linecache.html#module-linecache) module allows one to get any line from a Python source file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single... |
How to jump to a particular line in a huge text file? | 620,367 | 74 | 2009-03-06T20:49:52Z | 620,480 | 12 | 2009-03-06T21:25:53Z | [
"python",
"text-files"
] | Are there any alternatives to the code below:
```
startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
```
If I'm processing a huge text... | I'm probably spoiled by abundant ram, but 15 M is not huge. Reading into memory with `readlines()` is what I usually do with files of this size. Accessing a line after that is trivial. |
How to jump to a particular line in a huge text file? | 620,367 | 74 | 2009-03-06T20:49:52Z | 620,492 | 67 | 2009-03-06T21:28:23Z | [
"python",
"text-files"
] | Are there any alternatives to the code below:
```
startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
```
If I'm processing a huge text... | You can't jump ahead without reading in the file at least once, since you don't know where the line breaks are. You could do something like:
```
# Read in the file once and build a list of line offsets
line_offset = []
offset = 0
for line in file:
line_offset.append(offset)
offset += len(line)
file.seek(0)
# ... |
How to jump to a particular line in a huge text file? | 620,367 | 74 | 2009-03-06T20:49:52Z | 620,494 | 19 | 2009-03-06T21:28:28Z | [
"python",
"text-files"
] | Are there any alternatives to the code below:
```
startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
```
If I'm processing a huge text... | You don't really have that many options if the lines are of different length... you sadly need to process the line ending characters to know when you've progressed to the next line.
You can, however, dramatically speed this up AND reduce memory usage by changing the last parameter to "open" to something not 0.
0 mean... |
SQLAlchemy Obtain Primary Key With Autoincrement Before Commit | 620,610 | 32 | 2009-03-06T22:07:19Z | 620,831 | 66 | 2009-03-06T23:10:07Z | [
"python",
"sql",
"sqlalchemy"
] | When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing?
I would like to place two operations inside a transaction however one of the operations will depend on what primary... | You don't need to `commit`, you just need to `flush`. Here's some sample code. After the call to [flush](http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.flush) you can access the primary key that was assigned. Note this is with SA 0.4.8.
```
from sqlalchemy import *
from sqlalc... |
Another Django Forms : Foreign Key in Hidden Field | 621,212 | 8 | 2009-03-07T02:59:08Z | 621,917 | 15 | 2009-03-07T14:40:39Z | [
"python",
"django",
"forms"
] | Another Django Form question.
My form :
```
class PlanForm(forms.ModelForm):
owner = forms.ModelChoiceField(label="",
queryset=Profile.objects.all(),
widget=forms.HiddenInput())
etc...
class Meta:
model = Plan
```
Owner, in ... | I suspect that the `__unicode__` method for the Profile model instance, or the `repr` thereof is set to return a value other than `self.id`. For example, I just set this up:
```
# models.py
class Profile(models.Model):
name = models.CharField('profile name', max_length=10)
def __unicode__(self):
retur... |
Another Django Forms : Foreign Key in Hidden Field | 621,212 | 8 | 2009-03-07T02:59:08Z | 621,973 | 7 | 2009-03-07T15:14:33Z | [
"python",
"django",
"forms"
] | Another Django Form question.
My form :
```
class PlanForm(forms.ModelForm):
owner = forms.ModelChoiceField(label="",
queryset=Profile.objects.all(),
widget=forms.HiddenInput())
etc...
class Meta:
model = Plan
```
Owner, in ... | Hmm...
This might actually be a security hole.
Suppose a malicious attacker crafted a POST (say, by using XmlHttpRequest from FireBug) and set the profile term to some wacky value, like, your profile ID. Probably not what you wanted?
If possible, you may want to get the profile from the request object itself, rather... |
How to slice a list from an element n to the end in python? | 621,354 | 14 | 2009-03-07T05:17:34Z | 621,357 | 33 | 2009-03-07T05:19:31Z | [
"python"
] | I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:
```
>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
To my understanding, python slice means lst[sta... | You can leave one end of the slice open by not specifying the value.
```
test[3:] = [3, 4, 5, 6, 7, 8, 9]
test[:3] = [0, 1, 2]
``` |
How to slice a list from an element n to the end in python? | 621,354 | 14 | 2009-03-07T05:17:34Z | 621,521 | 19 | 2009-03-07T08:15:31Z | [
"python"
] | I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:
```
>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
To my understanding, python slice means lst[sta... | If you're using a variable as the range endpoint, you can use `None`.
```
start = 4
end = None
test[start:end]
``` |
What does re.compile(r'[[]]') match? | 621,560 | 4 | 2009-03-07T08:59:27Z | 621,568 | 16 | 2009-03-07T09:11:20Z | [
"python",
"regex"
] | With Python's re module, why do the following act differently:
```
>>> r = re.compile(r'[][]')
>>> r.findall(r'[]')
['[', ']']
>>> r = re.compile(r'[[]]')
>>> r.findall(r'[]')
['[]']
>>> r.findall(r'][')
[]
``` | The regular expression "[[]]" matches the substring "[]". The first [ in the expression begins a character class, and the first ] ends it. There is only one character ([) in the class, and then it has to be followed by the second ]. So the expression is "any of the characters in "[", followed by a "]". |
Python and random keys of 21 char max | 621,649 | 7 | 2009-03-07T10:36:54Z | 621,770 | 23 | 2009-03-07T12:26:47Z | [
"python",
"encryption",
"key"
] | I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ?
For now i use 'userid[:10]' + creation time: ddhhmmss + r... | If I read your question correctly, you want to generate some arbitrary identifier token which must be 21 characters max. Does it need to be highly resistant to guessing? The example you gave isn't "crytographically strong" in that it can be guessed by searching well less than 1/2 of the entire possible keyspace.
You d... |
Unable to import python-mysqldb | 621,968 | 2 | 2009-03-07T15:12:02Z | 621,972 | 10 | 2009-03-07T15:13:48Z | [
"python",
"import",
"mysql"
] | I installed python-mysqldb using
```
sudo apt-get install python-mysqldb
```
I have tried to use it unsuccessfully. The following commands do not work in Python prompt:
```
import python-mysqldb
```
Or
```
import mysqldb
```
How can I solve this problem? | The package name is "MySQLdb". Case counts. |
Python Reflection and Type Conversion | 622,161 | 7 | 2009-03-07T17:15:41Z | 622,173 | 11 | 2009-03-07T17:21:42Z | [
"python",
"reflection",
"type-conversion",
"introspection",
"python-datamodel"
] | In Python, functions like str(), int(), float(), etc. are generally used to perform type conversions. However, these require you to know at development time what type you want to convert to. A subproblem of some Python code I'm trying to write is as follows:
Given two variables, `foo` and `bar`, find the type of `foo`... | Use `foo.__class__` to get the type of `foo`. Then call it to convert bar to the type of foo:
```
def conv(foo, bar) :
return foo.__class__(bar)
```
Of course, this only works if the type of `foo` has a constructor that knows how to convert bar. |
Python Reflection and Type Conversion | 622,161 | 7 | 2009-03-07T17:15:41Z | 622,217 | 16 | 2009-03-07T17:57:32Z | [
"python",
"reflection",
"type-conversion",
"introspection",
"python-datamodel"
] | In Python, functions like str(), int(), float(), etc. are generally used to perform type conversions. However, these require you to know at development time what type you want to convert to. A subproblem of some Python code I'm trying to write is as follows:
Given two variables, `foo` and `bar`, find the type of `foo`... | that would be best:
```
type(foo)(bar)
``` |
Increment Page Hit Count in Django | 622,652 | 16 | 2009-03-07T22:42:05Z | 623,860 | 31 | 2009-03-08T16:46:13Z | [
"python",
"django",
"django-models"
] | I have a table with an `IntegerField` (`hit_count`), and when a page is visited (for example, `http://site/page/3`) I want record ID 3's `hit_count` column in the database to increment by 1.
The query should be like:
```
update table set hit_count = hit_count + 1 where id = 3
```
Can I do this with the standard Djan... | If you use Django 1.1+, just use [F expressions](http://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model):
```
from django.db.models import F
...
MyModel.objects.filter(id=...).update(hit_count=F('hit_count')+1)
```
This will perform a single atomic database query.
As gerdem... |
Unable to install Python without sudo access | 622,744 | 29 | 2009-03-07T23:42:54Z | 622,810 | 84 | 2009-03-08T00:33:25Z | [
"python",
"installation",
"sudo"
] | I extracted, configured and used make for the installation package in my server.
However, I could not use *make install*. I get the error
```
[~/wepapps/python/Python-2.6.1]# make install
/usr/bin/install -c python /usr/local/bin/python2.6
/usr/bin/install: cannot create regular file `/usr/local/bin/python2.6': Permi... | > How can I install to a path under my home directory?
```
mkdir /home/masi/.local
cd Python-2.6.1
make clean
./configure --prefix=/home/masi/.local
make
make install
```
Then run using:
```
/home/masi/.local/bin/python
```
Similarly if you have scripts (eg. CGI) that require your own user version of Python you ha... |
Django Passing Custom Form Parameters to Formset | 622,982 | 113 | 2009-03-08T03:36:08Z | 623,030 | 43 | 2009-03-08T04:24:10Z | [
"python",
"django",
"forms",
"django-forms"
] | > This was fixed in Django 1.9 with [form\_kwargs](https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms).
I have a Django Form that looks like this:
```
class ServiceForm(forms.Form):
option = forms.ModelChoiceField(queryset=ServiceOption.objects.none())
rate... | I would build the form class dynamically in a function, so that it has access to the affiliate via closure:
```
def make_service_form(affiliate):
class ServiceForm(forms.Form):
option = forms.ModelChoiceField(
queryset=ServiceOption.objects.filter(affiliate=affiliate))
rate = forms.... |
Django Passing Custom Form Parameters to Formset | 622,982 | 113 | 2009-03-08T03:36:08Z | 623,198 | 9 | 2009-03-08T07:08:41Z | [
"python",
"django",
"forms",
"django-forms"
] | > This was fixed in Django 1.9 with [form\_kwargs](https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms).
I have a Django Form that looks like this:
```
class ServiceForm(forms.Form):
option = forms.ModelChoiceField(queryset=ServiceOption.objects.none())
rate... | I like the closure solution for being "cleaner" and more Pythonic (so +1 to mmarshall answer) but Django forms also have a callback mechanism you can use for filtering querysets in formsets.
It's also not documented, which I think is an indicator the Django devs might not like it as much.
So you basically create your... |
Django Passing Custom Form Parameters to Formset | 622,982 | 113 | 2009-03-08T03:36:08Z | 624,013 | 92 | 2009-03-08T18:00:26Z | [
"python",
"django",
"forms",
"django-forms"
] | > This was fixed in Django 1.9 with [form\_kwargs](https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms).
I have a Django Form that looks like this:
```
class ServiceForm(forms.Form):
option = forms.ModelChoiceField(queryset=ServiceOption.objects.none())
rate... | I would use [functools.partial](http://docs.python.org/2/library/functools.html#functools.partial) and [functools.wraps](http://docs.python.org/2/library/functools.html#functools.wraps):
```
from functools import partial, wraps
from django.forms.formsets import formset_factory
ServiceFormSet = formset_factory(wraps(S... |
Django Passing Custom Form Parameters to Formset | 622,982 | 113 | 2009-03-08T03:36:08Z | 813,647 | 9 | 2009-05-01T23:00:06Z | [
"python",
"django",
"forms",
"django-forms"
] | > This was fixed in Django 1.9 with [form\_kwargs](https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms).
I have a Django Form that looks like this:
```
class ServiceForm(forms.Form):
option = forms.ModelChoiceField(queryset=ServiceOption.objects.none())
rate... | I wanted to place this as a comment to Carl Meyers answer, but since that requires points I just placed it here. This took me 2 hours to figure out so I hope it will help someone.
A note about using the inlineformset\_factory.
I used that solution my self and it worked perfect, until I tried it with the inlineformset... |
Django Passing Custom Form Parameters to Formset | 622,982 | 113 | 2009-03-08T03:36:08Z | 25,766,319 | 8 | 2014-09-10T13:09:20Z | [
"python",
"django",
"forms",
"django-forms"
] | > This was fixed in Django 1.9 with [form\_kwargs](https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms).
I have a Django Form that looks like this:
```
class ServiceForm(forms.Form):
option = forms.ModelChoiceField(queryset=ServiceOption.objects.none())
rate... | As of commit e091c18f50266097f648efc7cac2503968e9d217 on Tue Aug 14 23:44:46 2012 +0200 the accepted solution can't work anymore.
The current version of django.forms.models.modelform\_factory() function uses a "type construction technique", calling the type() function on the passed form to get the metaclass type, then... |
Django Passing Custom Form Parameters to Formset | 622,982 | 113 | 2009-03-08T03:36:08Z | 25,915,489 | 12 | 2014-09-18T14:29:59Z | [
"python",
"django",
"forms",
"django-forms"
] | > This was fixed in Django 1.9 with [form\_kwargs](https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms).
I have a Django Form that looks like this:
```
class ServiceForm(forms.Form):
option = forms.ModelChoiceField(queryset=ServiceOption.objects.none())
rate... | This is what worked for me, Django 1.7:
```
from django.utils.functional import curry
lols = {'lols':'lols'}
formset = modelformset_factory(MyModel, form=myForm, extra=0)
formset.form = staticmethod(curry(MyForm, lols=lols))
return formset
#form.py
class MyForm(forms.ModelForm):
def __init__(self, lols, *ar... |
For my app, how many threads would be optimal? | 623,054 | 3 | 2009-03-08T04:44:41Z | 623,070 | 13 | 2009-03-08T04:57:01Z | [
"python",
"multithreading"
] | I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is,... | You will probably find your application is bandwidth limited not CPU or I/O limited.
As such, add as many as you like until performance begins to degrade.
You may come up against other limits depending on your network setup. Like if you're behind an ADSL router, there will be a limit on the number of concurrent NAT s... |
For my app, how many threads would be optimal? | 623,054 | 3 | 2009-03-08T04:44:41Z | 623,138 | 7 | 2009-03-08T05:54:32Z | [
"python",
"multithreading"
] | I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is,... | I would use one thread and [twisted](http://twistedmatrix.com/) with either a deferred semaphore or a task cooperator if you already have an easy way to feed an arbitrarily long list of URLs in.
It's extremely unlikely you'll be able to make a multi-threaded crawler that's faster or smaller than a twisted-based crawle... |
Why can't I directly add attributes to any python object? | 623,520 | 21 | 2009-03-08T12:46:56Z | 623,531 | 32 | 2009-03-08T12:54:54Z | [
"python",
"attributes",
"object"
] | I have this code:
```
>>> class G:
... def __init__(self):
... self.x = 20
...
>>> gg = G()
>>> gg.x
20
>>> gg.y = 2000
```
And this code:
```
>>> from datetime import datetime
>>> my_obj = datetime.now()
>>> my_obj.interesting = 1
*** AttributeError: 'datetime.datetime' object has no attribute 'interesting'
`... | My guess, is that the implementation of datetime uses [\_\_slots\_\_](http://docs.python.org/reference/datamodel.html#id3) for better performance.
When using `__slots__`, the interpreter reserves storage for just the attributes listed, nothing else. This gives better performance and uses less storage, but it also mean... |
Why can't I directly add attributes to any python object? | 623,520 | 21 | 2009-03-08T12:46:56Z | 623,544 | 18 | 2009-03-08T13:07:39Z | [
"python",
"attributes",
"object"
] | I have this code:
```
>>> class G:
... def __init__(self):
... self.x = 20
...
>>> gg = G()
>>> gg.x
20
>>> gg.y = 2000
```
And this code:
```
>>> from datetime import datetime
>>> my_obj = datetime.now()
>>> my_obj.interesting = 1
*** AttributeError: 'datetime.datetime' object has no attribute 'interesting'
`... | It's written in C
<http://svn.python.org/view/python/trunk/Modules/datetimemodule.c?view=markup>
It doesn't seem to implement setattr. |
What should I be aware of when moving from asp.net to python for web development? | 624,062 | 3 | 2009-03-08T18:34:58Z | 624,079 | 8 | 2009-03-08T18:44:05Z | [
"asp.net",
"python"
] | I'm thinking about converting an app from Asp.net to python. I would like to know: what are the key comparisons to be aware of when moving a asp.net app to python(insert framework)?
Does python have user controls? Master pages? | First, Python is a language, while ASP.NET is a web framework. In fact, you can code ASP.NET applications using [IronPython](http://www.codeplex.com/IronPython).
If you want to leave ASP.NET behind and go with the Python "stack," then you can choose from several different web application frameworks, including [Django]... |
How do I make a Django ModelForm menu item selected by default? | 624,265 | 9 | 2009-03-08T20:56:46Z | 624,308 | 7 | 2009-03-08T21:19:46Z | [
"python",
"django",
"django-forms"
] | I am working on a Django app. One of my models, "User", includes a "gender" field, as defined below:
```
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)
```
I am using a ModelForm to generate a "new user" HTML form. My... | Surely `default` will do the trick?
e.g.
```
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M', null=True)
``` |
How do I make a Django ModelForm menu item selected by default? | 624,265 | 9 | 2009-03-08T20:56:46Z | 624,361 | 15 | 2009-03-08T21:45:42Z | [
"python",
"django",
"django-forms"
] | I am working on a Django app. One of my models, "User", includes a "gender" field, as defined below:
```
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)
```
I am using a ModelForm to generate a "new user" HTML form. My... | If you need a blank form with a default value selected, then pass an 'initial' dictionary to the constructor of your model form using the name of your field as the key:
```
form = MyModelForm (initial={'gender':'M'})
```
-OR-
You can override certain attributes of a ModelForm using the declarative nature of the Form... |
Why am I getting an invalid syntax easy_install error? | 624,492 | 4 | 2009-03-08T22:51:58Z | 624,499 | 18 | 2009-03-08T22:58:13Z | [
"python",
"easy-install"
] | I need to use easy\_install to install a package. I installed the enthought distribution, and popped into IDLE to say:
```
>>> easy_install SQLobject
SyntaxError: invalid syntax
```
What am I doing wrong? `easy_install` certainly exists, as does the package. help('easy\_install') gives me some basic help. `import eas... | easy\_install is a shell command. You don't need to put it in a python script.
```
easy_install SQLobject
```
Type that straight into a bash (or other) shell, as long as easy\_install is in your path. |
Why aren't signals simply called events? | 624,844 | 4 | 2009-03-09T02:42:37Z | 624,865 | 24 | 2009-03-09T02:52:18Z | [
"python",
"signals",
"django-signals"
] | From what I can tell, in Python and and Django, signals are simply delegated events. Is there anything that functionally differentiates them from the typical notion of events in C#, Java, ActionScript, etc? | Actually, "signals" have been around longer than events have. In the earliest usage, a signal was an asynchronous way for processes to get notified that events had occurred. Since Unix is much older than Django (and since a lot of the Django work came from pydispatcher, where the original stuff was done), the name has ... |
how to detect whether a python variable is a function? | 624,926 | 321 | 2009-03-09T03:31:30Z | 624,930 | 24 | 2009-03-09T03:33:49Z | [
"python"
] | I have a variable, `x`, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
```
>>> isinstance(x, function)
```
But that gives me:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
```
The reason I pick... | The following should return a boolean:
```
callable(x)
``` |
how to detect whether a python variable is a function? | 624,926 | 321 | 2009-03-09T03:31:30Z | 624,939 | 401 | 2009-03-09T03:39:02Z | [
"python"
] | I have a variable, `x`, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
```
>>> isinstance(x, function)
```
But that gives me:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
```
The reason I pick... | If this is for Python 2.x or for Python 3.2+, you can also use `callable()`. It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: <http://bugs.python.org/issue10518>. You can do this with:
```
callable(obj)
```
If this is for Python 3.x but before 3.2, check if... |
how to detect whether a python variable is a function? | 624,926 | 321 | 2009-03-09T03:31:30Z | 624,948 | 198 | 2009-03-09T03:47:57Z | [
"python"
] | I have a variable, `x`, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
```
>>> isinstance(x, function)
```
But that gives me:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
```
The reason I pick... | Builtin types that don't have constructors in the built-in namespace (e.g. functions, generators, methods) are in the `types` module. You can use `types.FunctionType` in an isinstance call.
```
In [1]: import types
In [2]: types.FunctionType
Out[2]: <type 'function'>
In [3]: def f(): pass
...:
In [4]: isinstance(f,... |
how to detect whether a python variable is a function? | 624,926 | 321 | 2009-03-09T03:31:30Z | 624,966 | 16 | 2009-03-09T03:58:55Z | [
"python"
] | I have a variable, `x`, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
```
>>> isinstance(x, function)
```
But that gives me:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
```
The reason I pick... | `callable(x)` *will* return true if the object passed can be called in Python, but the function does not exist in Python 3.0, and properly speaking will not distinguish between:
```
class A(object):
def __call__(self):
return 'Foo'
def B():
return 'Bar'
a = A()
b = B
print type(a), callable(a)
print... |
how to detect whether a python variable is a function? | 624,926 | 321 | 2009-03-09T03:31:30Z | 4,234,284 | 20 | 2010-11-20T18:27:53Z | [
"python"
] | I have a variable, `x`, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
```
>>> isinstance(x, function)
```
But that gives me:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
```
The reason I pick... | Python's 2to3 tool (<http://docs.python.org/dev/library/2to3.html>) suggests:
```
import collections
isinstance(obj, collections.Callable)
```
It seems this was chosen instead of the `hasattr(x, '__call__')` method because of <http://bugs.python.org/issue7006>. |
how to detect whether a python variable is a function? | 624,926 | 321 | 2009-03-09T03:31:30Z | 8,302,728 | 66 | 2011-11-28T21:40:27Z | [
"python"
] | I have a variable, `x`, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
```
>>> isinstance(x, function)
```
But that gives me:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
```
The reason I pick... | [Since Python 2.1](http://docs.python.org/library/inspect.html#module-inspect) you can import `isfunction` from the [`inspect`](http://docs.python.org/library/inspect.html) module.
```
>>> from inspect import isfunction
>>> def f(): pass
>>> isfunction(f)
True
>>> isfunction(lambda x: x)
True
``` |
how to detect whether a python variable is a function? | 624,926 | 321 | 2009-03-09T03:31:30Z | 13,605,330 | 9 | 2012-11-28T12:42:38Z | [
"python"
] | I have a variable, `x`, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
```
>>> isinstance(x, function)
```
But that gives me:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
```
The reason I pick... | If you want to detect everything that syntactically looks like a function: a function, method, built-in fun/meth, lambda ... but **exclude** callable objects (objects with `__call__` method defined), then try this one:
```
import types
isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.MethodType, typ... |
how to detect whether a python variable is a function? | 624,926 | 321 | 2009-03-09T03:31:30Z | 18,704,793 | 30 | 2013-09-09T18:42:29Z | [
"python"
] | I have a variable, `x`, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
```
>>> isinstance(x, function)
```
But that gives me:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
```
The reason I pick... | The accepted answer was at the time it was offered thought to be correct; As it
turns out, there is *no substitute* for `callable()`, which is back in python
3.2: Specifically, `callable()` checks the `tp_call` field of the object being
tested. There is no plain python equivalent. Most of the suggested tests are
correc... |
Python __init__ and self what do they do? | 625,083 | 344 | 2009-03-09T05:09:51Z | 625,096 | 14 | 2009-03-09T05:18:20Z | [
"python",
"oop"
] | I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
```
def method(self, blah):
def __init__(?):
....
....
```
What does self ... | `__init__` does act like a constructor. You'll need to pass "self" to any class functions as the first argument if you want them to behave as non-static methods. "self" are instance variables for your class. |
Python __init__ and self what do they do? | 625,083 | 344 | 2009-03-09T05:09:51Z | 625,097 | 92 | 2009-03-09T05:18:21Z | [
"python",
"oop"
] | I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
```
def method(self, blah):
def __init__(?):
....
....
```
What does self ... | Yep, you are right, these are oop constructs.
init is the constructor for a class. The self parameter refers to the instance of the object (like **this** in C++).
```
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
```
The init method gets called when memory for the object is alloc... |
Python __init__ and self what do they do? | 625,083 | 344 | 2009-03-09T05:09:51Z | 625,098 | 315 | 2009-03-09T05:18:46Z | [
"python",
"oop"
] | I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
```
def method(self, blah):
def __init__(?):
....
....
```
What does self ... | In this code:
```
class A(object):
def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print self.x + ' ' + foo
```
... the `self` variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an objec... |
Python __init__ and self what do they do? | 625,083 | 344 | 2009-03-09T05:09:51Z | 625,133 | 21 | 2009-03-09T05:41:21Z | [
"python",
"oop"
] | I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
```
def method(self, blah):
def __init__(?):
....
....
```
What does self ... | In short:
1. `self` as it suggests, refers to *itself*- the object which has called the method. That is, if you have N objects calling the method, then `self.a` will refer to a separate instance of the variable for each of the N objects. Imagine N copies of the variable `a` for each object
2. `__init__` is what is cal... |
Python __init__ and self what do they do? | 625,083 | 344 | 2009-03-09T05:09:51Z | 625,174 | 9 | 2009-03-09T06:09:20Z | [
"python",
"oop"
] | I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
```
def method(self, blah):
def __init__(?):
....
....
```
What does self ... | The 'self' is a reference to the class instance
```
class foo:
def bar(self):
print "hi"
```
Now we can create an instance of foo and call the method on it, the self parameter is added by Python in this case:
```
f = foo()
f.bar()
```
But it can be passed in as well if the method call isn't in the c... |
Python __init__ and self what do they do? | 625,083 | 344 | 2009-03-09T05:09:51Z | 626,081 | 11 | 2009-03-09T12:50:30Z | [
"python",
"oop"
] | I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
```
def method(self, blah):
def __init__(?):
....
....
```
What does self ... | note that `self` could actually be any valid python identifier. For example, we could just as easily write, from Chris B's example:
```
class A(object):
def __init__(foo):
foo.x = 'Hello'
def method_a(bar, foo):
print bar.x + ' ' + foo
```
and it would work exactly the same. It is however rec... |
Python __init__ and self what do they do? | 625,083 | 344 | 2009-03-09T05:09:51Z | 12,552,203 | 12 | 2012-09-23T12:02:55Z | [
"python",
"oop"
] | I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
```
def method(self, blah):
def __init__(?):
....
....
```
What does self ... | Basically, you need to use the 'self' keyword when using a variable in multiple functions within the same class. As for **init**, it's used to setup default values incase no other functions from within that class are called. |
Python __init__ and self what do they do? | 625,083 | 344 | 2009-03-09T05:09:51Z | 16,474,519 | 13 | 2013-05-10T03:03:13Z | [
"python",
"oop"
] | I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
```
def method(self, blah):
def __init__(?):
....
....
```
What does self ... | Try out this code. Hope it helps many C programmers like me to Learn Py.
```
#! /usr/bin/python2
class Person:
'''Doc - Inside Class '''
def __init__(self, name):
'''Doc - __init__ Constructor'''
self.n_name = name
def show(self, n1, n2):
'''Doc - Inside Show'''
... |
Python __init__ and self what do they do? | 625,083 | 344 | 2009-03-09T05:09:51Z | 17,260,649 | 74 | 2013-06-23T12:15:34Z | [
"python",
"oop"
] | I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
```
def method(self, blah):
def __init__(?):
....
....
```
What does self ... | # A brief illustrative example
In the hope it might help a little, here's a simple example I used to understand the difference between a variable declared inside a class, and a variable declared inside an `__init__` function:
```
class MyClass(object):
i = 123
def __init__(self):
self.i = 345
a = ... |
Python __init__ and self what do they do? | 625,083 | 344 | 2009-03-09T05:09:51Z | 21,032,703 | 11 | 2014-01-09T22:39:09Z | [
"python",
"oop"
] | I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
```
def method(self, blah):
def __init__(?):
....
....
```
What does self ... | Had trouble undestanding this myself. Even after reading the answers here.
To properly understand the `__init__` method you need to understand self.
**The self Parameter**
The arguments accepted by the `__init__` method are :
```
def __init__(self, arg1, arg2):
```
But we only actually pass it two arguments :
```... |
Python __init__ and self what do they do? | 625,083 | 344 | 2009-03-09T05:09:51Z | 32,386,319 | 7 | 2015-09-03T22:19:24Z | [
"python",
"oop"
] | I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
```
def method(self, blah):
def __init__(?):
....
....
```
What does self ... | 1. **`__init__`** is basically a function which will **"initialize"**/**"activate"** the properties of the class for a specific object, once created and matched to the corresponding class..
2. **`self`** represents that object which will inherit those properties. |
wxpython auinotebook close tab event | 625,714 | 7 | 2009-03-09T10:26:40Z | 625,851 | 8 | 2009-03-09T11:17:31Z | [
"python",
"wxpython",
"wxwidgets"
] | What event is used when I close a tab in an auinotebook? I tested with
EVT\_AUINOTEBOOK\_PAGE\_CLOSE(D). It didn't work.
I would also like to fire a right click on the tab itself event.
Where can I find all the events that can be used with the aui manager/notebook? Might just be my poor searching skills, but I can't ... | This is the bind command you want:
```
self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSED, self.close, self.nb)
```
To detect a right click on the tab (e.g. to show a custom context menu):
```
self.Bind(wx.aui.EVT_AUINOTEBOOK_TAB_RIGHT_DOWN, self.right, self.nb)
```
Here's a list of the aui notebook events:
```
EVT_AUIN... |
File editing in python | 626,617 | 3 | 2009-03-09T15:12:30Z | 626,666 | 8 | 2009-03-09T15:21:22Z | [
"python",
"svn"
] | I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories.
The problem is I'm not replacing in place. I'm opening files, passing the contents i... | I suspect the problem is that you are in fact editing wrong files. Subversion should never raise any errors about check sums when you are just modifying your tracked files -- independently of *how* you are modifying them.
Maybe you are accidentally editing files in the `.svn` directory? In `.svn/text-base`, Subversion... |
What's the difference between list and tuples? | 626,759 | 555 | 2009-03-09T15:41:25Z | 626,764 | 24 | 2009-03-09T15:41:59Z | [
"python",
"list",
"tuples"
] | What's the difference?
What are the advantages / disadvantages of tuples / lists? | Lists are mutable; tuples are not.
From [docs.python.org/2/tutorial/datastructures.html](http://docs.python.org/2/tutorial/datastructures.html)
> Tuples are immutable, and usually contain an heterogeneous sequence of
> elements that are accessed via unpacking (see later in this section)
> or indexing (or even by attr... |
What's the difference between list and tuples? | 626,759 | 555 | 2009-03-09T15:41:25Z | 626,768 | 54 | 2009-03-09T15:42:38Z | [
"python",
"list",
"tuples"
] | What's the difference?
What are the advantages / disadvantages of tuples / lists? | The key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it.
So if you're going to need to change the values use a List.
Benefits to tuples:
1. Slight performance improvement.
2. As a tuple is immutable it can be used as a key in a dictionary.
3. ... |
What's the difference between list and tuples? | 626,759 | 555 | 2009-03-09T15:41:25Z | 626,871 | 636 | 2009-03-09T16:02:51Z | [
"python",
"list",
"tuples"
] | What's the difference?
What are the advantages / disadvantages of tuples / lists? | Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. **Tuples have structure, lists have order.**
Using this distinction makes code more explic... |
What's the difference between list and tuples? | 626,759 | 555 | 2009-03-09T15:41:25Z | 627,165 | 136 | 2009-03-09T17:14:47Z | [
"python",
"list",
"tuples"
] | What's the difference?
What are the advantages / disadvantages of tuples / lists? | If you went for a walk, you could note your coordinates at any instant in an (x,y) tuple.
If you wanted to record your journey, you could append your location every few seconds to a list.
But you couldn't do it the other way around. |
What's the difference between list and tuples? | 626,759 | 555 | 2009-03-09T15:41:25Z | 627,901 | 8 | 2009-03-09T20:29:55Z | [
"python",
"list",
"tuples"
] | What's the difference?
What are the advantages / disadvantages of tuples / lists? | Lists are intended to be homogeneous sequences, while tuples are heterogeneous data structures. |
What's the difference between list and tuples? | 626,759 | 555 | 2009-03-09T15:41:25Z | 16,097,958 | 11 | 2013-04-19T05:43:14Z | [
"python",
"list",
"tuples"
] | What's the difference?
What are the advantages / disadvantages of tuples / lists? | Lists are for looping, tuples are for structures i.e. `"%s %s" %tuple`.
Lists are usually homogeneous, tuples are usually heterogeneous.
Lists are for variable length, tuples are for fixed length. |
What's the difference between list and tuples? | 626,759 | 555 | 2009-03-09T15:41:25Z | 18,181,253 | 10 | 2013-08-12T07:06:24Z | [
"python",
"list",
"tuples"
] | What's the difference?
What are the advantages / disadvantages of tuples / lists? | It's [been mentioned](http://stackoverflow.com/a/626871/915501) that the difference is largely semantic: people expect a tuple and list to represent different information. But this goes further than a guideline, some libraries actually behave differently based on what they are passed. Take numpy for example (copied fro... |
What's the difference between list and tuples? | 626,759 | 555 | 2009-03-09T15:41:25Z | 18,892,969 | 157 | 2013-09-19T11:07:28Z | [
"python",
"list",
"tuples"
] | What's the difference?
What are the advantages / disadvantages of tuples / lists? | Difference between list and tuple
1. **Literal**
```
someTuple = (1,2)
someList = [1,2]
```
2. **Size**
```
a = tuple(range(1000))
b = list(range(1000))
a.__sizeof__() # 8024
b.__sizeof__() # 9088
```
Due to the smaller size of a tuple operation with it a bit faster but not that m... |
How do I find the Windows common application data folder using Python? | 626,796 | 28 | 2009-03-09T15:48:55Z | 626,841 | 10 | 2009-03-09T15:58:23Z | [
"python",
"windows",
"application-data",
"common-files"
] | I would like my application to store some data for access by all users. Using Python, how can I find where the data should go? | Take a look at <http://ginstrom.com/code/winpaths.html>. This is a simple module that will retrieve Windows folder information. The module implements `get_common_appdata` to get the App Data folder for all users. |
How do I find the Windows common application data folder using Python? | 626,796 | 28 | 2009-03-09T15:48:55Z | 626,927 | 37 | 2009-03-09T16:12:41Z | [
"python",
"windows",
"application-data",
"common-files"
] | I would like my application to store some data for access by all users. Using Python, how can I find where the data should go? | If you don't want to add a dependency for a third-party module like winpaths, I would recommend using the environment variables already available in Windows:
* [**What environment variables are available in Windows?**](http://windowsitpro.com/article/articleid/23873/what-environment-variables-are-available-in-windows.... |
How do I find the Windows common application data folder using Python? | 626,796 | 28 | 2009-03-09T15:48:55Z | 1,448,255 | 10 | 2009-09-19T09:57:14Z | [
"python",
"windows",
"application-data",
"common-files"
] | I would like my application to store some data for access by all users. Using Python, how can I find where the data should go? | From <http://snipplr.com/view.php?codeview&id=7354>
```
homedir = os.path.expanduser('~')
# ...works on at least windows and linux.
# In windows it points to the user's folder
# (the one directly under Documents and Settings, not My Documents)
# In windows, you can choose to care about local versus roaming profi... |
How to remove an element from a list by index in Python? | 627,435 | 623 | 2009-03-09T18:16:11Z | 627,441 | 300 | 2009-03-09T18:17:48Z | [
"python",
"list"
] | How to remove an element from a list by index in Python?
I found the `list.remove` method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed. | You probably want `pop`:
```
a = ['a', 'b', 'c', 'd']
a.pop(1)
# now a is ['a', 'c', 'd']
```
By default, `pop` without any arguments removes the last item:
```
a = ['a', 'b', 'c', 'd']
a.pop()
# now a is ['a', 'b', 'c']
``` |
How to remove an element from a list by index in Python? | 627,435 | 623 | 2009-03-09T18:16:11Z | 627,453 | 730 | 2009-03-09T18:21:24Z | [
"python",
"list"
] | How to remove an element from a list by index in Python?
I found the `list.remove` method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed. | Use `del` and specify the element you want to delete with the index:
```
In [9]: a = range(10)
In [10]: a
Out[10]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [11]: del a[-1]
In [12]: a
Out[12]: [0, 1, 2, 3, 4, 5, 6, 7, 8]
```
[Here](http://docs.python.org/tutorial/datastructures.html#the-del-statement) is the section from the... |
How to remove an element from a list by index in Python? | 627,435 | 623 | 2009-03-09T18:16:11Z | 19,466,364 | 31 | 2013-10-19T13:10:02Z | [
"python",
"list"
] | How to remove an element from a list by index in Python?
I found the `list.remove` method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed. | [`pop`](https://docs.python.org/library/stdtypes.html#mutable-sequence-types) is also useful to remove and keep an item from a list. Where `del` actually trashes the item.
```
>>> x = [1, 2, 3, 4]
>>> p = x.pop(1)
>>> p
2
``` |
How to remove an element from a list by index in Python? | 627,435 | 623 | 2009-03-09T18:16:11Z | 24,352,671 | 41 | 2014-06-22T15:21:00Z | [
"python",
"list"
] | How to remove an element from a list by index in Python?
I found the `list.remove` method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed. | Like others mentioned pop and del are *the* efficient ways to remove an item of given index.
Yet just for the sake of completion ( since the same thing can be done via many ways in python ):
**Using slices ( This does not do inplace removal of item from original list ) :**
( Also this will be the least efficient meth... |
How can I use named arguments in a decorator? | 627,501 | 4 | 2009-03-09T18:37:20Z | 627,519 | 7 | 2009-03-09T18:43:30Z | [
"python",
"language-features",
"decorator"
] | If I have the following function:
```
def intercept(func):
# do something here
@intercept(arg1=20)
def whatever(arg1,arg2):
# do something here
```
I would like for intercept to fire up only when **arg1** is 20. I would like to be able to pass named parameters to the function. How could I accomplish this?
Here'... | ```
from functools import wraps
def intercept(target,**trigger):
def decorator(func):
names = getattr(func,'_names',None)
if names is None:
code = func.func_code
names = code.co_varnames[:code.co_argcount]
@wraps(func)
def decorated(*args,**kwargs):
... |
How can I use named arguments in a decorator? | 627,501 | 4 | 2009-03-09T18:37:20Z | 628,309 | 10 | 2009-03-09T22:38:50Z | [
"python",
"language-features",
"decorator"
] | If I have the following function:
```
def intercept(func):
# do something here
@intercept(arg1=20)
def whatever(arg1,arg2):
# do something here
```
I would like for intercept to fire up only when **arg1** is 20. I would like to be able to pass named parameters to the function. How could I accomplish this?
Here'... | Remember that
```
@foo
def bar():
pass
```
is equivalent to:
```
def bar():
pass
bar = foo(bar)
```
so if you do:
```
@foo(x=3)
def bar():
pass
```
that's equivalent to:
```
def bar():
pass
bar = foo(x=3)(bar)
```
so your decorator needs to look something like this:
```
def foo(x=1):
def wr... |
Next step after PHP: Perl or Python? | 627,721 | 20 | 2009-03-09T19:45:26Z | 627,731 | 10 | 2009-03-09T19:48:40Z | [
"python",
"perl"
] | It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear *others' opinions*.
I have experience with **PHP 5**, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.
Professionals may agree about PHP not b... | I'd go with Perl. Not everyone will agree with me here, but it's a great language well suited to system administration work, and it'll expose you to some more functional programming constructs. It's a great language for learning how to use the smallest amount of code for a given task, as well.
For the usage scenario y... |
Next step after PHP: Perl or Python? | 627,721 | 20 | 2009-03-09T19:45:26Z | 627,764 | 11 | 2009-03-09T19:56:31Z | [
"python",
"perl"
] | It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear *others' opinions*.
I have experience with **PHP 5**, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.
Professionals may agree about PHP not b... | Honestly, the "majority" of my programming has been in Perl and PHP and I recently decided to do my latest project in Python, and I must admit it is very nice to program with. I was hesitant of the whole no curly braces thing as that's what I've always done, but it is really very clean. At the end of the day, though, y... |
Next step after PHP: Perl or Python? | 627,721 | 20 | 2009-03-09T19:45:26Z | 627,788 | 7 | 2009-03-09T20:01:48Z | [
"python",
"perl"
] | It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear *others' opinions*.
I have experience with **PHP 5**, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.
Professionals may agree about PHP not b... | I have no experience with Python. I vouch strongly to learn Perl, not out of attrition, but because there is a TON to learn in the platform. The key concepts of Perl are: Do What I Mean ([DWIM](http://en.wikipedia.org/wiki/DWIM)) and There's More Than One Way To Do It ([TMTOWTDI](http://en.wikipedia.org/wiki/There%5Fis... |
Next step after PHP: Perl or Python? | 627,721 | 20 | 2009-03-09T19:45:26Z | 627,794 | 7 | 2009-03-09T20:02:32Z | [
"python",
"perl"
] | It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear *others' opinions*.
I have experience with **PHP 5**, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.
Professionals may agree about PHP not b... | I haven't worked with Python much, but I can tell why I *didn't* like about Perl when I used it.
1. OO support feels tacked on. OO in perl is very different from OO support in the other languages I've used (which include things like PHP, Java, and C#)
2. TMTOWTDI (There's More Than One Way To Do It). Good idea in theo... |
Next step after PHP: Perl or Python? | 627,721 | 20 | 2009-03-09T19:45:26Z | 627,862 | 24 | 2009-03-09T20:20:42Z | [
"python",
"perl"
] | It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear *others' opinions*.
I have experience with **PHP 5**, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.
Professionals may agree about PHP not b... | Perl is a very nice language and CPAN has a ton of mature modules that will save you a lot of time. Furthermore, Perl is really moving forwards nowadays with a lot of interesting projects (unlike what uninformed fanboys like to spread around). Even a [Perl 6 implementation](http://rakudo.org/) is by now releasing worki... |
Next step after PHP: Perl or Python? | 627,721 | 20 | 2009-03-09T19:45:26Z | 629,604 | 7 | 2009-03-10T10:32:52Z | [
"python",
"perl"
] | It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear *others' opinions*.
I have experience with **PHP 5**, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.
Professionals may agree about PHP not b... | I recently made the step from Perl over to Python, after a couple of Perl-only years. Soon thereafter I discovered I had started to read through all kinds of Python-code just as it were any other easy to read text â something I've never done with Perl. Having to delve into third-party Perl code has always been kind o... |
Python dlopen/dlfunc/dlsym wrappers | 627,786 | 3 | 2009-03-09T20:01:36Z | 627,820 | 7 | 2009-03-09T20:09:46Z | [
"python",
"linker",
"dlopen"
] | Anybody knows if actually exists a wrapper or ported library to access to Unix dynamic linker on Python? | Would [ctypes](http://docs.python.org/library/ctypes.html) do what you want? |
Django Form Preview - How to work with 'cleaned_data' | 628,132 | 3 | 2009-03-09T21:39:21Z | 628,470 | 9 | 2009-03-09T23:46:11Z | [
"python",
"django",
"django-models",
"django-forms"
] | Thanks to Insin for answering a previous [question](http://stackoverflow.com/questions/625800/django-form-preview-adding-the-user-to-the-form-before-save) related to this one.
His answer worked and works well, however, I'm perplexed at the provision of 'cleaned\_data', or more precisely, how to use it?
```
class Regi... | I've never tried what you're doing here with a ModelForm before, but you might be able to use the \*\* operator to expand your cleaned\_data dictionary into the keyword arguments expected for your Registration constructor:
```
registration = Registration (**cleaned_data)
```
The constructor to your model classes t... |
How to run an operation on a collection in Python and collect the results? | 628,150 | 4 | 2009-03-09T21:45:56Z | 628,159 | 10 | 2009-03-09T21:48:40Z | [
"python",
"list",
"lambda"
] | How to run an operation on a collection in Python and collect the results?
So if I have a list of 100 numbers, and I want to run a function like this for each of them:
```
Operation ( originalElement, anotherVar ) # returns new number.
```
and collect the result like so:
result = another list...
How do I do it? Ma... | [List comprehensions.](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) In Python they look something like:
```
a = [f(x) for x in bar]
```
Where f(x) is some function and bar is a sequence.
You can define f(x) as a partially applied function with a construct like:
```
def foo(x):
return... |
Single implementation to cover both single and multiple values in Python? | 628,162 | 4 | 2009-03-09T21:49:37Z | 628,173 | 9 | 2009-03-09T21:53:08Z | [
"python",
"list"
] | Say you have a value like this:
n = 5
and a method that returns the factorial of it, like so:
Factorial ( 5 )
How do you handle multiple values:
nums = [1,2,3,4,5]
Factorial ( nums )
so it returns the factorials of all these values as a list.
What's the cleanest way to handle this, without writing 2 methods? Do... | [List comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions):
```
[fac(n) for n in nums]
```
**EDIT:**
Sorry, I misunderstood, you want a method that handles both sequences and single values? I can't imagine why you wouldn't do this with two methods.
```
def factorial(n):
# impl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.