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 |
|---|---|---|---|---|---|---|---|---|---|
Java "Virtual Machine" vs. Python "Interpreter" parlance? | 441,824 | 110 | 2009-01-14T03:39:32Z | 441,854 | 49 | 2009-01-14T03:56:21Z | [
"java",
"python",
"jvm"
] | It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? | Probably one reason for the different terminology is that one normally thinks of feeding the python interpreter raw human-readable source code and not worrying about bytecode and all that.
In Java, you have to explicitly compile to bytecode and then run just the bytecode, not source code on the VM.
Even though Python... |
Java "Virtual Machine" vs. Python "Interpreter" parlance? | 441,824 | 110 | 2009-01-14T03:39:32Z | 441,973 | 84 | 2009-01-14T05:06:47Z | [
"java",
"python",
"jvm"
] | It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? | A virtual machine is a virtual computing environment with a specific set of atomic well defined instructions that are supported independent of any specific language and it is generally thought of as a sandbox unto itself. The VM is analogous to an instruction set of a specific CPU and tends to work at a more fundamenta... |
Java "Virtual Machine" vs. Python "Interpreter" parlance? | 441,824 | 110 | 2009-01-14T03:39:32Z | 442,210 | 10 | 2009-01-14T07:44:54Z | [
"java",
"python",
"jvm"
] | It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? | **Interpreter**, translates source code into some efficient intermediate representation (code) and immediately executes this.
**Virtual Machine**, explicitly executes stored pre-compiled code built by a compiler which is part of the interpreter system.
A very important characteristic of a virtual machine is that the ... |
Java "Virtual Machine" vs. Python "Interpreter" parlance? | 441,824 | 110 | 2009-01-14T03:39:32Z | 1,732,383 | 75 | 2009-11-13T22:47:18Z | [
"java",
"python",
"jvm"
] | It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? | In this post, "virtual machine" refers to process virtual machines, not to
system virtual machines like Qemu or Virtualbox. A process virtual machine is
simply a program which provides a general programming environment -- a program
which can be programmed.
Java has an interpreter as well as a virtual machine, and Pyth... |
IronPython on ASP.NET MVC | 441,838 | 21 | 2009-01-14T03:45:24Z | 443,078 | 12 | 2009-01-14T14:16:01Z | [
"python",
"asp.net-mvc",
"linq",
"dynamic",
"ironpython"
] | Has anyone tried ASP.NET MVC using IronPython? Having done a lot of Python development recently, it would be nice to continue with the language as I go into a potential ASP.NET MVC project.
I'm especially interested in exploiting the dynamic aspects of Python with .NET features such as LINQ and want to know if this wi... | Yes, [there is an MVC example from the DLR team](http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=17613).
You might also be interested in [Spark](http://sparkviewengine.com/documentation/ironpython). |
IronPython on ASP.NET MVC | 441,838 | 21 | 2009-01-14T03:45:24Z | 4,223,420 | 7 | 2010-11-19T08:59:15Z | [
"python",
"asp.net-mvc",
"linq",
"dynamic",
"ironpython"
] | Has anyone tried ASP.NET MVC using IronPython? Having done a lot of Python development recently, it would be nice to continue with the language as I go into a potential ASP.NET MVC project.
I'm especially interested in exploiting the dynamic aspects of Python with .NET features such as LINQ and want to know if this wi... | Using IronPython in ASP.NET MVC: <http://www.codevoyeur.com/Articles/Tags/ironpython.aspx>
this page contains following articles:
* A Simple IronPython ControllerFactory for ASP.NET MVC
* A Simple IronPython ActionFilter for ASP.NET MVC
* A Simple IronPython Route Mapper for ASP.NET MVC
* An Unobtrusive IronPython Vi... |
Good Python networking libraries for building a TCP server? | 441,849 | 9 | 2009-01-14T03:51:13Z | 441,872 | 10 | 2009-01-14T04:06:30Z | [
"python",
"networking",
"twisted"
] | I was just wondering what network libraries there are out there for Python for building a TCP/IP server. I know that Twisted might jump to mind but the documentation seems scarce, sloppy, and scattered to me.
Also, would using Twisted even have a benefit over rolling my own server with select.select()? | I must agree that the documentation is a bit terse but the tutorial gets you up and running quickly.
<http://twistedmatrix.com/projects/core/documentation/howto/tutorial/index.html>
The event-based programming paradigm of Twisted and it's defereds might be a bit weird at the start (was for me) but it is worth the lea... |
Pre-populate an inline FormSet? | 442,040 | 37 | 2009-01-14T05:49:25Z | 442,061 | 25 | 2009-01-14T06:08:25Z | [
"python",
"django",
"django-forms"
] | I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:
```
class Event(models.Model):
event_id = models.AutoField(primary_key=True)
date = models.DateField()
event_type = m... | So, you're not going to like the answer, partly because I'm not yet done writing the code and partly because it's a lot of work.
What you need to do, as I discovered when I ran into this myself, is:
1. Spend a lot of time reading through the formset and model-formset code to get a feel for how it all works (not helpe... |
Pre-populate an inline FormSet? | 442,040 | 37 | 2009-01-14T05:49:25Z | 3,766,344 | 16 | 2010-09-22T04:35:19Z | [
"python",
"django",
"django-forms"
] | I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:
```
class Event(models.Model):
event_id = models.AutoField(primary_key=True)
date = models.DateField()
event_type = m... | I spent a fair amount of time trying to come up with a solution that I could re-use across sites. James' post contained the key piece of wisdom of extending `BaseInlineFormSet` but strategically invoking calls against `BaseFormSet`.
The solution below is broken into two pieces: a `AdminInline` and a `BaseInlineFormSet... |
Pre-populate an inline FormSet? | 442,040 | 37 | 2009-01-14T05:49:25Z | 16,417,369 | 13 | 2013-05-07T11:01:21Z | [
"python",
"django",
"django-forms"
] | I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:
```
class Event(models.Model):
event_id = models.AutoField(primary_key=True)
date = models.DateField()
event_type = m... | Django 1.4 and higher supports [providing initial values](https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/#providing-initial-values).
In terms of the original question, the following would work:
```
class AttendanceFormSet(models.BaseInlineFormSet):
def __init__(self, *args, **kwargs):
super... |
ReadInt(), ReadByte(), ReadString(), etc. in Python? | 442,188 | 3 | 2009-01-14T07:34:04Z | 442,197 | 8 | 2009-01-14T07:38:17Z | [
"python"
] | The functions ReadInt(), ReadByte(), and ReadString() (to name a few) exist in other languages for reading input from streams. I am trying to read from a socket, and I want to use functions like these. Are they tucked away in Python somewhere under a different way or has someone made a library for it?
Also, there are ... | I think [struct.unpack\_from](http://docs.python.org/library/struct.html#struct.unpack_from) is what you're looking for. |
ReadInt(), ReadByte(), ReadString(), etc. in Python? | 442,188 | 3 | 2009-01-14T07:34:04Z | 4,338,551 | 7 | 2010-12-02T18:37:08Z | [
"python"
] | The functions ReadInt(), ReadByte(), and ReadString() (to name a few) exist in other languages for reading input from streams. I am trying to read from a socket, and I want to use functions like these. Are they tucked away in Python somewhere under a different way or has someone made a library for it?
Also, there are ... | Python's way is using struct.unpack to read binary data.
I'm very used to the BinaryReader and BinaryWriter in C#, so I made this:
```
from struct import *
class BinaryStream:
def __init__(self, base_stream):
self.base_stream = base_stream
def readByte(self):
return self.base_stream.read(1)
... |
Generic catch for python | 442,343 | 33 | 2009-01-14T09:05:20Z | 442,358 | 60 | 2009-01-14T09:12:41Z | [
"python",
"exception"
] | I have some extremely weird behavior that seems to result in silent exceptions. How can I write a general try catch where I can debug all exceptions. Something along the lines of:
```
try:
# something that fails
except e:
print e
```
A bit more about the problem at hand in detail:
I have a Django app that on... | Exceptions are already printed by default before program termination. If you want to send the error somewhere else (not print it) you can do this:
```
try:
something()
except Exception as e:
send_somewhere(traceback.format_exception(*sys.exc_info()))
raise # reraises the exception
```
note that this forma... |
How to properly interact with a process using subprocess module | 443,057 | 6 | 2009-01-14T14:07:12Z | 443,080 | 11 | 2009-01-14T14:16:38Z | [
"python",
"subprocess"
] | I'm having problems redirecting stdio of another program using subprocess module. Just reading from stdout results in hanging, and Popen.communicate() works but it closes pipes after reading/writing. What's the easiest way to implement this?
I was playing around with this on windows:
```
import subprocess
proc = subp... | Doesn't fit 100% to your example but helps to understand the underlying issue: Process P starts child C. Child C writes something to its stdout. stdout of C is a pipe which has a 4096 character buffer and the output is shorter than that. Now, C waits for some input. For C, everything is fine.
P waits for the output wh... |
Why does Paramiko hang if you use it while loading a module? | 443,387 | 8 | 2009-01-14T15:35:25Z | 450,895 | 13 | 2009-01-16T16:01:36Z | [
"python",
"multithreading",
"ssh",
"module",
"paramiko"
] | Put the following into a file **hello.py** (and `easy_install paramiko` if you haven't got it):
```
hostname,username,password='fill','these','in'
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(hostname=hostname, username=username, password=password)
i,o,e = ... | Paramiko uses separate threads for the underlying transport.
You should *never* have a module that spawns a thread as a side effect of importing. As I understand it, there is a single import lock available, so when a child thread from your module attempts another import, it can block indefinitely, because your main thr... |
Addressing instance name string in __init__(self) in Python | 443,775 | 4 | 2009-01-14T16:55:48Z | 443,868 | 7 | 2009-01-14T17:13:51Z | [
"python",
"instance",
"instantiation"
] | I am doing something like this:
```
class Class(object):
def __init__(self):
self.var=#new instance name string#
```
How do I make the \_\_ init \_\_ method of my instance to use the instance name string for 'c'? Say in case:
```
c=Class()
```
I want c.var equal to 'c'.
Thanks for your replies, I am im... | Python doesn't have variables, it has [objects and names](http://effbot.org/zone/python-objects.htm). When you do
```
c = Class()
```
you're doing two things:
1. Creating a new object of type `Class`
2. Binding the object to the name `c` in the current scope.
The object you created doesn't have any concept of a "va... |
Python: Callbacks, Delegates, ... ? What is common? | 443,885 | 21 | 2009-01-14T17:20:28Z | 444,057 | 14 | 2009-01-14T18:07:35Z | [
"python",
"events",
"delegates",
"callback"
] | Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on.
Is there a common way? Which default language concepts or additional modules are there and which can you recommend? | Personally I don't see a difference between callbacks, listeners, and delegates.
The [observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) (a.k.a listeners, a.k.a "multiple callbacks") is easy to implement - just hold a list of observers, and add or remove callables from it. These callables can be function... |
How to create python bytes object from long hex string? | 443,967 | 39 | 2009-01-14T17:42:50Z | 443,985 | 26 | 2009-01-14T17:46:38Z | [
"python",
"hex",
"byte"
] | I have a long sequence of hex digits in a string, such as
> 000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44
only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3? | Try the [binascii module](http://doc.astro-wise.org/binascii.html#-unhexlify)
```
from binascii import unhexlify
b = unhexlify(myhexstr)
``` |
How to create python bytes object from long hex string? | 443,967 | 39 | 2009-01-14T17:42:50Z | 443,990 | 37 | 2009-01-14T17:47:20Z | [
"python",
"hex",
"byte"
] | I have a long sequence of hex digits in a string, such as
> 000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44
only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3? | You can do this with the hex codec. ie:
```
>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'
``` |
How to create python bytes object from long hex string? | 443,967 | 39 | 2009-01-14T17:42:50Z | 444,005 | 21 | 2009-01-14T17:50:38Z | [
"python",
"hex",
"byte"
] | I have a long sequence of hex digits in a string, such as
> 000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44
only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3? | ```
result = bytes.fromhex(some_hex_string)
``` |
How to create python bytes object from long hex string? | 443,967 | 39 | 2009-01-14T17:42:50Z | 17,160,152 | 18 | 2013-06-18T03:37:20Z | [
"python",
"hex",
"byte"
] | I have a long sequence of hex digits in a string, such as
> 000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44
only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3? | Works in Python 2.7 and higher including python3:
```
result = bytearray.fromhex('deadbeef')
```
**Note:** There seems to be a bug with the `bytearray.fromhex()` function in Python 2.6. The python.org documentation states that the function accepts a string as an argument, but when applied, the following error is thro... |
python - readable list of objects | 444,058 | 5 | 2009-01-14T18:07:54Z | 444,073 | 8 | 2009-01-14T18:12:20Z | [
"python",
"list"
] | This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;
```
<__main__.evolutions instance at 0x01B8EA08>
```
but instead to show a selected attribute o... | If you want to just display a particular attribute of each class instance, you can do
```
print([obj.attr for obj in my_list_of_objs])
```
Which will print out the `attr` attribute of each object in the list `my_list_of_objs`. Alternatively, you can define the `__str__()` method for your class, which specifies how to... |
sqlalchemy, turning a list of IDs to a list of objects | 444,475 | 17 | 2009-01-14T20:08:32Z | 457,057 | 10 | 2009-01-19T09:49:39Z | [
"python",
"sqlalchemy"
] | I have sequence of IDs I want to retrieve. It's simple:
```
session.query(Record).filter(Record.id.in_(seq)).all()
```
Is there a better way to do it? | Your code is absolutety fine.
`IN` is like a bunch of `X=Y` joined with `OR` and is pretty fast in contemporary databases.
However, if your list of IDs is long, you could make the query a bit more efficient by passing a sub-query returning the list of IDs. |
convert a string of bytes into an int (python) | 444,591 | 76 | 2009-01-14T20:46:17Z | 444,610 | 61 | 2009-01-14T20:52:39Z | [
"python",
"string",
"bytearray"
] | How can I convert a string of bytes into an int in python?
Say like this: `'y\xcc\xa6\xbb'`
I came up with a clever/stupid way of doing it:
```
sum(ord(c) << (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))
```
I know there has to be something builtin or in the standard library that does this more simply...
T... | You can also use the `struct` module to do this:
```
>>> struct.unpack("<L", "y\xcc\xa6\xbb")[0]
3148270713L
``` |
convert a string of bytes into an int (python) | 444,591 | 76 | 2009-01-14T20:46:17Z | 444,814 | 51 | 2009-01-14T21:42:52Z | [
"python",
"string",
"bytearray"
] | How can I convert a string of bytes into an int in python?
Say like this: `'y\xcc\xa6\xbb'`
I came up with a clever/stupid way of doing it:
```
sum(ord(c) << (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))
```
I know there has to be something builtin or in the standard library that does this more simply...
T... | As Greg said, you can use struct if you are dealing with binary values, but if you just have a "hex number" but in byte format you might want to just convert it like:
```
s = 'y\xcc\xa6\xbb'
num = int(s.encode('hex'), 16)
```
...this is the same as:
```
num = struct.unpack(">L", s)[0]
```
...except it'll work for a... |
convert a string of bytes into an int (python) | 444,591 | 76 | 2009-01-14T20:46:17Z | 9,634,417 | 138 | 2012-03-09T12:56:38Z | [
"python",
"string",
"bytearray"
] | How can I convert a string of bytes into an int in python?
Say like this: `'y\xcc\xa6\xbb'`
I came up with a clever/stupid way of doing it:
```
sum(ord(c) << (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))
```
I know there has to be something builtin or in the standard library that does this more simply...
T... | In Python 3.2 and later, use
```
>>> int.from_bytes(b'y\xcc\xa6\xbb', byteorder='big')
2043455163
```
or
```
>>> int.from_bytes(b'y\xcc\xa6\xbb', byteorder='little')
3148270713
```
according to the endianness of your byte-string.
This also works for bytestring-integers of arbitrary length, and for two's-complement... |
Cleanest way to run/debug python programs in windows | 445,595 | 18 | 2009-01-15T04:01:14Z | 445,618 | 8 | 2009-01-15T04:14:05Z | [
"python",
"windows",
"python-idle"
] | Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much.
However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters.
IDLE lets me r... | You can easily widen the Windows console by doing the following:
* click the icon for the console window in the upper right
* select **Properties** from the menu
* click the **Layout** tab
* change the **Window Size** > Width to 140
This can also be saved universally by changing the **Defaults** on the menu. |
Cleanest way to run/debug python programs in windows | 445,595 | 18 | 2009-01-15T04:01:14Z | 445,682 | 31 | 2009-01-15T04:49:05Z | [
"python",
"windows",
"python-idle"
] | Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much.
However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters.
IDLE lets me r... | For an interactive interpreter, nothing beats [IPython](http://ipython.scipy.org/). It's superb. It's also free and open source. On Windows, you'll want to install the readline library. Instructions for that are on the IPython installation documentation.
[Winpdb](http://winpdb.org/) is my Python debugger of choice. It... |
GAE - How to live with no joins? | 445,827 | 13 | 2009-01-15T06:07:25Z | 446,471 | 13 | 2009-01-15T11:58:10Z | [
"python",
"google-app-engine",
"join",
"gae-datastore"
] | ## Example Problem:
### Entities:
* User contains name and a list of friends (User references)
* Blog Post contains title, content, date and Writer (User)
### Requirement:
I want a page that displays the title and a link to the blog of the last 10 posts by a user's friend. I would also like the ability to keep pagi... | If you look at how the SQL solution you provided will be executed, it will go basically like this:
1. Fetch a list of friends for the current user
2. For each user in the list, start an index scan over recent posts
3. Merge-join all the scans from step 2, stopping when you've retrieved enough entries
You can carry ou... |
GAE - How to live with no joins? | 445,827 | 13 | 2009-01-15T06:07:25Z | 1,043,333 | 7 | 2009-06-25T11:06:54Z | [
"python",
"google-app-engine",
"join",
"gae-datastore"
] | ## Example Problem:
### Entities:
* User contains name and a list of friends (User references)
* Blog Post contains title, content, date and Writer (User)
### Requirement:
I want a page that displays the title and a link to the blog of the last 10 posts by a user's friend. I would also like the ability to keep pagi... | This topic is covered in a Google io talk:
<http://code.google.com/events/io/sessions/BuildingScalableComplexApps.html>
Basically the Google team suggest using list properties and what they call relational index entities, an example application can be found here: <http://pubsub-test.appspot.com/> |
Django: how do you serve media / stylesheets and link to them within templates | 446,026 | 41 | 2009-01-15T08:35:50Z | 447,991 | 47 | 2009-01-15T18:56:51Z | [
"python",
"css",
"django",
"django-templates",
"media"
] | Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.
I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template,... | I just had to figure this out myself.
settings.py:
```
MEDIA_ROOT = 'C:/Server/Projects/project_name/static/'
MEDIA_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/media/'
```
urls.py:
```
from django.conf import settings
...
if settings.DEBUG:
urlpatterns += patterns('',
(r'^static/(?P<path>.*)$', 'django.view... |
Django: how do you serve media / stylesheets and link to them within templates | 446,026 | 41 | 2009-01-15T08:35:50Z | 479,391 | 10 | 2009-01-26T10:49:00Z | [
"python",
"css",
"django",
"django-templates",
"media"
] | Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.
I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template,... | Django already has a context process for MEDIA\_URL, see [Django's documentation](http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-media).
It should be availbale by default (unless you've customized CONTEXT\_PROCESSORS and forgot to add it) in a RequestContext. |
How can I check for Python version in a program that uses new language features? | 446,052 | 194 | 2009-01-15T08:45:28Z | 446,061 | 88 | 2009-01-15T08:50:17Z | [
"python",
"version"
] | If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?
How do I get control early enough to issue an error message
and exit?
For example, I have a program that uses the ternery operator... | You can test using `eval`:
```
try:
eval("1 if True else 2")
except SyntaxError:
# doesn't have ternary
```
Also, `with` *is* available in Python 2.5, just add `from __future__ import with_statement` .
EDIT: to get control early enough, you could split it do different `.py` files and check compatibility in the m... |
How can I check for Python version in a program that uses new language features? | 446,052 | 194 | 2009-01-15T08:45:28Z | 446,075 | 18 | 2009-01-15T08:55:44Z | [
"python",
"version"
] | If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?
How do I get control early enough to issue an error message
and exit?
For example, I have a program that uses the ternery operator... | Try
```
import platform
platform.python_version()
```
Should give you a string like "2.3.1". If this is not exactly waht you want there is a rich set of data available through the "platform" build-in. What you want should be in there somewhere. |
How can I check for Python version in a program that uses new language features? | 446,052 | 194 | 2009-01-15T08:45:28Z | 446,136 | 86 | 2009-01-15T09:26:51Z | [
"python",
"version"
] | If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?
How do I get control early enough to issue an error message
and exit?
For example, I have a program that uses the ternery operator... | Have a wrapper around your program that does the following.
```
import sys
req_version = (2,5)
cur_version = sys.version_info
if cur_version >= req_version:
import myApp
myApp.run()
else:
print "Your Python interpreter is too old. Please consider upgrading."
```
You can also consider using `sys.version()`,... |
How can I check for Python version in a program that uses new language features? | 446,052 | 194 | 2009-01-15T08:45:28Z | 446,181 | 7 | 2009-01-15T09:43:38Z | [
"python",
"version"
] | If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?
How do I get control early enough to issue an error message
and exit?
For example, I have a program that uses the ternery operator... | Sets became part of the core language in Python 2.4, in order to stay backwards compatible. I did this back then, which will work for you as well:
```
if sys.version_info < (2, 4):
from sets import Set as set
``` |
How can I check for Python version in a program that uses new language features? | 446,052 | 194 | 2009-01-15T08:45:28Z | 3,132,402 | 21 | 2010-06-28T12:38:59Z | [
"python",
"version"
] | If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?
How do I get control early enough to issue an error message
and exit?
For example, I have a program that uses the ternery operator... | Probably the best way to do do this version comparison is to use the `sys.hexversion`. This is important because comparing version tuples will not give you the desired result in all python versions.
```
import sys
if sys.hexversion < 0x02060000:
print "yep!"
else:
print "oops!"
``` |
How can I check for Python version in a program that uses new language features? | 446,052 | 194 | 2009-01-15T08:45:28Z | 7,642,536 | 7 | 2011-10-04T01:52:20Z | [
"python",
"version"
] | If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?
How do I get control early enough to issue an error message
and exit?
For example, I have a program that uses the ternery operator... | Although the question is:
How do I get control early enough to issue an error message and exit?
The question that I answer is:
How do I get control early enough to issue an error message before starting the app?
I can answer it a lot differently then the other posts.
Seems answers so far are trying to solve your ques... |
How can I check for Python version in a program that uses new language features? | 446,052 | 194 | 2009-01-15T08:45:28Z | 31,052,037 | 9 | 2015-06-25T13:39:04Z | [
"python",
"version"
] | If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?
How do I get control early enough to issue an error message
and exit?
For example, I have a program that uses the ternery operator... | ```
import sys
# prints whether python is version 3 or not
python_version = sys.version_info.major
if python_version == 3:
print("is python 3")
else:
print("not python 3")
``` |
Possible values from sys.platform? | 446,209 | 34 | 2009-01-15T10:02:59Z | 446,210 | 22 | 2009-01-15T10:03:16Z | [
"python",
"cross-platform"
] | What are the possible return values from the following command?
```
import sys
print sys.platform
```
I know there is a lot of possibilities, so I'm mainly interested in the "main" ones (Windows, Linux, Mac OS) | Mac OS X (10.4, 10.5, 10.7, 10.8):
```
darwin
```
Linux (2.6 kernel):
```
linux2
```
Windows XP 32 bit:
```
win32
```
Versions in brackets have been checked - other/newer versions are likely to be the same. |
Possible values from sys.platform? | 446,209 | 34 | 2009-01-15T10:02:59Z | 446,215 | 19 | 2009-01-15T10:04:52Z | [
"python",
"cross-platform"
] | What are the possible return values from the following command?
```
import sys
print sys.platform
```
I know there is a lot of possibilities, so I'm mainly interested in the "main" ones (Windows, Linux, Mac OS) | > As others have indicated, sys.platform
> is derived from the name that the
> system vendor gives their system.
> However, Python also adds
> plat- to sys.path, so
> you can look at all the plat-\*
> directories in the Python
> distribution.
>
> This gives you the list
>
> aix3 aix4 atheos beos5 darwin freebsd2
> free... |
Possible values from sys.platform? | 446,209 | 34 | 2009-01-15T10:02:59Z | 13,874,620 | 28 | 2012-12-14T07:49:05Z | [
"python",
"cross-platform"
] | What are the possible return values from the following command?
```
import sys
print sys.platform
```
I know there is a lot of possibilities, so I'm mainly interested in the "main" ones (Windows, Linux, Mac OS) | ```
.---------------------.----------.
| System | Value |
|---------------------|----------|
| Linux (2.x and 3.x) | linux2 |
| Windows | win32 |
| Windows/Cygwin | cygwin |
| Mac OS X | darwin |
| OS/2 | os2 |
| OS/2 EMX | os2emx |
|... |
How do I reverse Unicode decomposition using Python? | 446,222 | 5 | 2009-01-15T10:08:25Z | 446,291 | 7 | 2009-01-15T10:33:47Z | [
"python",
"unicode"
] | Using Python 2.5, I have some text in stored in a unicode object:
> Dinis e Isabel, uma difı´cil relac¸aËo
> conjugal e polı´tica
This appears to be [decomposed Unicode](http://www.unicode.org/reports/tr15/#Decomposition). Is there a generic way in Python to reverse the decomposition, so I end up with:
> Dinis... | I think you are looking for this:
```
>>> import unicodedata
>>> print unicodedata.normalize("NFC",u"c\u0327")
ç
``` |
How can I deploy a Perl/Python/Ruby script without installing an interpreter? | 446,685 | 21 | 2009-01-15T13:21:14Z | 446,712 | 23 | 2009-01-15T13:28:05Z | [
"python",
"ruby",
"perl"
] | I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.
This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be ... | You can use [Perl Archive Toolkit](http://search.cpan.org/perldoc?PAR) to bring a minimal perl core + needed modules + your Perl program with you.
And you can even convert it using [PAR Packer](http://search.cpan.org/perldoc?pp) to a windows exe file that will run just like any other program, from an end user's perspe... |
How can I deploy a Perl/Python/Ruby script without installing an interpreter? | 446,685 | 21 | 2009-01-15T13:21:14Z | 446,741 | 30 | 2009-01-15T13:37:12Z | [
"python",
"ruby",
"perl"
] | I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.
This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be ... | You can get Windows executables in all three languages.
* As usual with Perl, there's more than one way to do it:
+ [PAR Packer](http://search.cpan.org/perldoc?pp) (free/open-source)
+ [perl2exe](http://www.indigostar.com/perl2exe.htm) (shareware)
+ [PerlApp](http://community.activestate.com/products/PerlDevKit)... |
How can I deploy a Perl/Python/Ruby script without installing an interpreter? | 446,685 | 21 | 2009-01-15T13:21:14Z | 449,470 | 8 | 2009-01-16T03:58:59Z | [
"python",
"ruby",
"perl"
] | I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.
This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be ... | Using [PAR, the Perl Aachiver](http://search.cpan.org/perldoc?PAR) has already been mentioned in other answers, and is an excellent solution. There's a short tutorial on [building executables using PAR](http://perltraining.com.au/tips/2008-05-23.html) that was published as a [Perl Tip](http://perltraining.com.au/tips/)... |
Where to get/How to build Windows binary of mod_wsgi with python 3.0 support? | 447,015 | 5 | 2009-01-15T14:48:24Z | 1,037,956 | 9 | 2009-06-24T12:06:29Z | [
"python",
"apache",
"visual-c++",
"mod-wsgi"
] | I wanted to experiment a little with python 3.0 at home. I got python 3.0 working, I've played around with some scripts, and I thought it would be fun to try to make a small web-project with it.
As I was googling, it turned out, that mod\_python, for some reasons, will not be able to support python 3.0.
The only othe... | Binaries for Windows are now being supplied from the mod\_wsgi site for Apache 2.2 and Python 2.6 and 3.0. Python 3.0 is only supported for mod\_wsgi 3.0 onwards. See:
<http://code.google.com/p/modwsgi/downloads/list>
---
UPDATE July 2015
The above link is no longer valid. Instead see:
* <https://github.com/Graham... |
What is the difference between encode/decode? | 447,107 | 122 | 2009-01-15T15:13:59Z | 447,401 | 11 | 2009-01-15T16:15:39Z | [
"python",
"string",
"unicode",
"character-encoding",
"python-2.x"
] | I've never been sure that I understand the difference between str/unicode decode and encode.
I know that `str().decode()` is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.
I know that `unicode().encode()` converts unicode c... | mybytestring.encode(somecodec) is meaningful for these values of `somecodec`:
* base64
* bz2
* zlib
* hex
* quopri
* rot13
* string\_escape
* uu
I am not sure what decoding an already decoded unicode text is good for. Trying that with any encoding seems to always try to encode with the system's default encoding first... |
What is the difference between encode/decode? | 447,107 | 122 | 2009-01-15T15:13:59Z | 448,383 | 45 | 2009-01-15T20:41:48Z | [
"python",
"string",
"unicode",
"character-encoding",
"python-2.x"
] | I've never been sure that I understand the difference between str/unicode decode and encode.
I know that `str().decode()` is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.
I know that `unicode().encode()` converts unicode c... | To represent a unicode string as a string of bytes is known as **encoding**. Use `u'...'.encode(encoding)`.
Example:
```
>>> u'æøå'.encode('utf8')
'\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5'
>>> u'æøå'.encode('latin1')
'\xc3\xa6\xc3\xb8\xc3\xa5'
>>> u'æøå'.encode('ascii')
Unico... |
What is the difference between encode/decode? | 447,107 | 122 | 2009-01-15T15:13:59Z | 449,281 | 83 | 2009-01-16T02:06:33Z | [
"python",
"string",
"unicode",
"character-encoding",
"python-2.x"
] | I've never been sure that I understand the difference between str/unicode decode and encode.
I know that `str().decode()` is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.
I know that `unicode().encode()` converts unicode c... | The `decode` method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone.
`unicode().decode()` will perform an implicit *encoding* of `s... |
What is the difference between encode/decode? | 447,107 | 122 | 2009-01-15T15:13:59Z | 452,378 | 9 | 2009-01-16T23:11:40Z | [
"python",
"string",
"unicode",
"character-encoding",
"python-2.x"
] | I've never been sure that I understand the difference between str/unicode decode and encode.
I know that `str().decode()` is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.
I know that `unicode().encode()` converts unicode c... | anUnicode.**encode**('encoding') results in a **string** object and can be called on a unicode object
aString.**decode**('encoding') results in an **unicode** object and can be called on a string, encoded in given encoding.
---
Some more explanations:
You can create some unicode object, which doesn't have any encod... |
Django: Increment blog entry view count by one. Is this efficient? | 447,117 | 16 | 2009-01-15T15:15:31Z | 447,433 | 12 | 2009-01-15T16:22:34Z | [
"python",
"database",
"django",
"performance"
] | I have the following code in my index view.
```
latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10]
for entry in latest_entry_list:
entry.views = entry.views + 1
entry.save()
```
If there are ten (the limit) rows returned from the initial query, will the save issue 10 ... | You could handle the updates in a single transaction, which could improve performance significantly. Use a separate function, decorated with @transaction.commit\_manually.
```
@transaction.commit_manually
def update_latest_entries(latest_entry_list):
for entry in latest_entry_list:
entry.views += 1
... |
Django: Increment blog entry view count by one. Is this efficient? | 447,117 | 16 | 2009-01-15T15:15:31Z | 889,463 | 37 | 2009-05-20T18:23:57Z | [
"python",
"database",
"django",
"performance"
] | I have the following code in my index view.
```
latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10]
for entry in latest_entry_list:
entry.views = entry.views + 1
entry.save()
```
If there are ten (the limit) rows returned from the initial query, will the save issue 10 ... | You can use `F()` objects for this.
Here is how you import `F`: `from django.db.models import F`
**[New in Django 1.1](http://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once).**
Calls to update can also use F() objects to update one field based on the value of another field in the... |
Porting library from Java to Python | 448,095 | 6 | 2009-01-15T19:23:22Z | 448,137 | 9 | 2009-01-15T19:32:22Z | [
"java",
"python"
] | I'm about to port a smallish library from Java to Python and wanted some advice (smallish ~ a few thousand lines of code). I've studied the Java code a little, and noticed some design patterns that are common in both languages. However, there were definitely some Java-only idioms (singletons, etc) present that are gene... | If it were me, I'd consider doing the work by hand. A couple thousand lines of code isn't a lot of code, and by rewriting it yourself (rather than translating it automatically), you'll be in a position to decide how to take advantage of Python idioms appropriately. (FWIW, I worked Java almost exclusively for 9 years, a... |
Python - downloading a file over HTTP with progress bar and basic authentication | 448,207 | 8 | 2009-01-15T19:52:18Z | 448,277 | 7 | 2009-01-15T20:12:47Z | [
"python",
"http",
"download"
] | I'm using `urllib.urlretrieve` to download a file, and implementing a download progress bar using the `reporthook` parameter. Since `urlretrieve` doesn't directly support authentication, I came up with
```
import urllib
def urlretrieve_with_basic_auth(url, filename=None, reporthook=None, data=None,
... | [urlgrabber](http://linux.duke.edu/projects/urlgrabber/) has built-in support for progress bars, authentication, and more. |
What is __init__.py for? | 448,271 | 751 | 2009-01-15T20:09:09Z | 448,279 | 554 | 2009-01-15T20:13:24Z | [
"python",
"module"
] | What is `__init__.py` for in a Python source directory? | It's a part of a package. [Here's the documentation.](http://docs.python.org/tutorial/modules.html#packages)
> The `__init__.py` files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as `string`, from unintentionally hiding valid mo... |
What is __init__.py for? | 448,271 | 751 | 2009-01-15T20:09:09Z | 448,292 | 15 | 2009-01-15T20:18:32Z | [
"python",
"module"
] | What is `__init__.py` for in a Python source directory? | It facilitates importing other python files. When you placed this file in a directory (say stuff)containing other py files, then you can do something like import stuff.other.
```
root\
stuff\
other.py
morestuff\
another.py
```
Without this `__init__.py` inside the directory stuff, you could... |
What is __init__.py for? | 448,271 | 751 | 2009-01-15T20:09:09Z | 448,311 | 64 | 2009-01-15T20:22:58Z | [
"python",
"module"
] | What is `__init__.py` for in a Python source directory? | The `__init__.py` file makes Python treat directories containing it as modules.
Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported. |
What is __init__.py for? | 448,271 | 751 | 2009-01-15T20:09:09Z | 4,116,384 | 323 | 2010-11-07T03:31:14Z | [
"python",
"module"
] | What is `__init__.py` for in a Python source directory? | Files named `__init__.py` are used to mark directories on disk as Python package directories.
If you have the files
```
mydir/spam/__init__.py
mydir/spam/module.py
```
and `mydir` is on your path, you can import the code in `module.py` as
```
import spam.module
```
or
```
from spam import module
```
If you remove... |
What is __init__.py for? | 448,271 | 751 | 2009-01-15T20:09:09Z | 18,979,314 | 263 | 2013-09-24T10:38:34Z | [
"python",
"module"
] | What is `__init__.py` for in a Python source directory? | In addition to labeling a directory as a Python package and defining `__all__`, **`__init__.py` allows you to define any variable at the package level.** Doing so is often convenient if a package defines something that will be imported frequently, in an API-like fashion. This pattern promotes adherence to the Pythonic ... |
What is __init__.py for? | 448,271 | 751 | 2009-01-15T20:09:09Z | 21,019,300 | 25 | 2014-01-09T11:45:10Z | [
"python",
"module"
] | What is `__init__.py` for in a Python source directory? | In Python the definition of package is very simple. Like Java the hierarchical structure and the directory structure are the same. But you have to have `__init__.py` in a package. I will explain the `__init__.py` file with the example below:
```
package_x/
|-- __init__.py
|-- subPackage_a/
|------ __init__.py
|--... |
What is __init__.py for? | 448,271 | 751 | 2009-01-15T20:09:09Z | 27,757,676 | 25 | 2015-01-03T17:41:14Z | [
"python",
"module"
] | What is `__init__.py` for in a Python source directory? | `__init__.py` will treat the directory it is in as a loadable module.
For people who prefer reading code, I put [Two-Bit Alchemist's](http://stackoverflow.com/users/2588818/two-bit-alchemist) comment here.
```
$ find /tmp/mydir/
/tmp/mydir/
/tmp/mydir//spam
/tmp/mydir//spam/__init__.py
/tmp/mydir//spam/module.py
$ cd... |
What is __init__.py for? | 448,271 | 751 | 2009-01-15T20:09:09Z | 29,509,611 | 25 | 2015-04-08T08:29:37Z | [
"python",
"module"
] | What is `__init__.py` for in a Python source directory? | 1. For convenience: The other users will not need to know your functions' exact location.
```
your_package/
__init__.py
file1.py/
file2.py/
...
fileN.py
# in __init__.py
from file1 import *
from file2 import *
...
from fileN import *
# in file1.py
def add():
... |
Setting up Python on Windows/ Apache? | 449,055 | 6 | 2009-01-16T00:02:42Z | 450,097 | 22 | 2009-01-16T11:08:32Z | [
"python",
"wamp",
"mod-python"
] | I want to get a simple Python "hello world" web page script to run on Windows Vista/ Apache but hit different walls. I'm using WAMP. I've installed `mod_python` and the module shows, but I'm not quite sure what I'm supposed to do in e.g. http.conf (things like AddHandler mod\_python .py either bring me to a file not fo... | Stay away from `mod_python`. One common misleading idea is that `mod_python` is like `mod_php`, but for python. That is not true. [Wsgi](http://wsgi.org) is the standard to run python web applications, defined by [PEP 333](http://www.python.org/dev/peps/pep-0333/). So use [`mod_wsgi`](http://code.google.com/p/modwsgi/)... |
Are there any good 3rd party GUI products for Python? | 449,168 | 5 | 2009-01-16T01:11:49Z | 449,252 | 8 | 2009-01-16T01:49:55Z | [
"python",
"user-interface"
] | In .Net you have companies like DevEpxress, and Infragistics that offer a range of GUI widgets. Is there any market like that for Python GUI widgets? I'm thinking specifically about widgets like the DevExpress xtraGrid Suite.
Edit 01-16-09: For Example:
<http://www.devexpress.com/Downloads/NET/OnlineDemos.xml>
<http:... | There are a number of GUI Toolkits available for Python. Obviously, the toolkit you choose will determine your selection of 3rd party widgets.
**The Contenders**
Python comes with [Tkinter](http://wiki.python.org/moin/TkInter) which is easy to use, but not great looking.
There are some very popular cross platform GU... |
How do I determine the size of an object in Python? | 449,560 | 271 | 2009-01-16T05:07:12Z | 450,034 | 316 | 2009-01-16T10:42:37Z | [
"python",
"object",
"memory",
"memory-management",
"sizeof"
] | In C, we can find the size of an `int`, `char`, etc. I want to know how to get size of objects like a string, integer, etc. in Python.
Related question: [How many bytes per element are there in a Python list (tuple)?](http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple... | Just use the [sys.getsizeof](http://docs.python.org/library/sys.html#sys.getsizeof) function defined in the `sys` module.
> `sys.getsizeof(object[, default])`:
>
> Return the size of an object in bytes.
> The object can be any type of object.
> All built-in objects will return
> correct results, but this does not
> ha... |
How do I determine the size of an object in Python? | 449,560 | 271 | 2009-01-16T05:07:12Z | 450,351 | 11 | 2009-01-16T13:00:14Z | [
"python",
"object",
"memory",
"memory-management",
"sizeof"
] | In C, we can find the size of an `int`, `char`, etc. I want to know how to get size of objects like a string, integer, etc. in Python.
Related question: [How many bytes per element are there in a Python list (tuple)?](http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple... | This can be more complicated than it looks depending on how you want to count things. For instance, if you have a list of ints, do you want the size of the list containing the *references* to the ints? (ie. list only, not what is contained in it), or do you want to include the actual data pointed to, in which case you ... |
How do I determine the size of an object in Python? | 449,560 | 271 | 2009-01-16T05:07:12Z | 3,373,511 | 60 | 2010-07-30T16:33:00Z | [
"python",
"object",
"memory",
"memory-management",
"sizeof"
] | In C, we can find the size of an `int`, `char`, etc. I want to know how to get size of objects like a string, integer, etc. in Python.
Related question: [How many bytes per element are there in a Python list (tuple)?](http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple... | For numpy arrays, `getsizeof` doesn't work - for me it always returns 40 for some reason:
```
from pylab import *
from sys import getsizeof
A = rand(10)
B = rand(10000)
```
Then (in ipython):
```
In [64]: getsizeof(A)
Out[64]: 40
In [65]: getsizeof(B)
Out[65]: 40
```
Happily, though:
```
In [66]: A.nbytes
Out[66]... |
How do I determine the size of an object in Python? | 449,560 | 271 | 2009-01-16T05:07:12Z | 30,316,760 | 88 | 2015-05-19T04:26:33Z | [
"python",
"object",
"memory",
"memory-management",
"sizeof"
] | In C, we can find the size of an `int`, `char`, etc. I want to know how to get size of objects like a string, integer, etc. in Python.
Related question: [How many bytes per element are there in a Python list (tuple)?](http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple... | > # How do I determine the size of an object in Python?
The answer, "Just use sys.getsizeof" is not a complete answer.
That answer *does* work for builtin objects directly, but it does not account for what those objects may contain, specifically, what types, such as tuples, lists, dicts, and sets contain. They can co... |
How can I split a url string up into separate parts in Python? | 449,775 | 9 | 2009-01-16T07:43:22Z | 449,782 | 8 | 2009-01-16T07:49:55Z | [
"python",
"url",
"parsing"
] | I decided that I'll learn python tonight :)
I know C pretty well (wrote an OS in it) so I'm not a noob in programming so everything in python seems pretty easy, but I don't know how to solve this problem :
let's say I have this address:
<http://example.com/random/folder/path.html>
Now how can I create two strings from... | I have no experience with python, but I found the urlparse module, which should do the job:
<http://docs.python.org/library/urlparse.html> |
How can I split a url string up into separate parts in Python? | 449,775 | 9 | 2009-01-16T07:43:22Z | 449,805 | 8 | 2009-01-16T08:11:11Z | [
"python",
"url",
"parsing"
] | I decided that I'll learn python tonight :)
I know C pretty well (wrote an OS in it) so I'm not a noob in programming so everything in python seems pretty easy, but I don't know how to solve this problem :
let's say I have this address:
<http://example.com/random/folder/path.html>
Now how can I create two strings from... | If this is the extent of your URL parsing, Python's inbuilt rpartition will do the job:
```
>>> URL = "http://example.com/random/folder/path.html"
>>> Segments = URL.rpartition('/')
>>> Segments[0]
'http://example.com/random/folder'
>>> Segments[2]
'path.html'
```
From [Pydoc](http://www.python.org/doc/3.0/library/st... |
How can I split a url string up into separate parts in Python? | 449,775 | 9 | 2009-01-16T07:43:22Z | 449,811 | 36 | 2009-01-16T08:14:36Z | [
"python",
"url",
"parsing"
] | I decided that I'll learn python tonight :)
I know C pretty well (wrote an OS in it) so I'm not a noob in programming so everything in python seems pretty easy, but I don't know how to solve this problem :
let's say I have this address:
<http://example.com/random/folder/path.html>
Now how can I create two strings from... | The urlparse module in python 2.x (or urllib.parse in python 3.x) would be the way to do it.
```
>>> from urllib.parse import urlparse
>>> url = 'http://example.com/random/folder/path.html'
>>> parse_object = urlparse(url)
>>> parse_object.netloc
'example.com'
>>> parse_object.path
'/random/folder/path.html'
>>> parse... |
What is the correct way to backup ZODB blobs? | 451,952 | 6 | 2009-01-16T20:51:01Z | 2,664,479 | 12 | 2010-04-18T23:51:13Z | [
"python",
"plone",
"zope",
"zodb",
"blobstorage"
] | I am using plone.app.blob to store large ZODB objects in a blobstorage directory. This reduces size pressure on Data.fs but I have not been able to find any advice on backing up this data.
I am already backing up Data.fs by pointing a network backup tool at a directory of repozo backups. Should I simply point that too... | It should be safe to do a repozo backup of the Data.fs followed by an rsync of the blobstorage directory, as long as the database doesn't get packed while those two operations are happening.
This is because, at least when using blobs with FileStorage, modifications to a blob always results in the creation of a new fil... |
Making a method private in a python subclass | 451,963 | 24 | 2009-01-16T20:53:50Z | 452,023 | 26 | 2009-01-16T21:09:56Z | [
"python",
"oop",
"inheritance"
] | Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :
```
class A:
def __init__(self):
#do something here
def method(self):
#some code here
class B(A):
def __init__(self):
... | There's no way to truly do this in Python. Rather unpythonic, it is.
As Guido would say, we're all consenting adults here.
Here's a good [summary of the philosophy behind everything in Python being public](http://mail.python.org/pipermail/tutor/2003-October/025932.html). |
Making a method private in a python subclass | 451,963 | 24 | 2009-01-16T20:53:50Z | 452,028 | 15 | 2009-01-16T21:11:46Z | [
"python",
"oop",
"inheritance"
] | Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :
```
class A:
def __init__(self):
#do something here
def method(self):
#some code here
class B(A):
def __init__(self):
... | Python is distributed as source. The very idea of a private method makes very little sense.
The programmer who wants to extend `B`, frustrated by a privacy issue, looks at the source for `B`, copies and pastes the source code for `method` into the subclass `C`.
What have you gained through "privacy"? The best you can... |
Making a method private in a python subclass | 451,963 | 24 | 2009-01-16T20:53:50Z | 452,049 | 7 | 2009-01-16T21:16:58Z | [
"python",
"oop",
"inheritance"
] | Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :
```
class A:
def __init__(self):
#do something here
def method(self):
#some code here
class B(A):
def __init__(self):
... | This may be a fair approximation. Lexical scoping to the "rescue":
```
#!/usr/bin/env python
class Foo(object):
def __init__(self, name):
self.name = name
self.bar()
def bar(self):
def baz():
print "I'm private"
print self.name
def quux():
... |
Making a method private in a python subclass | 451,963 | 24 | 2009-01-16T20:53:50Z | 452,240 | 11 | 2009-01-16T22:09:27Z | [
"python",
"oop",
"inheritance"
] | Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :
```
class A:
def __init__(self):
#do something here
def method(self):
#some code here
class B(A):
def __init__(self):
... | I am surprised that no one has mentioned this, but prefixing the method name with a single underscore is the correct way of labelling it as "private". It's not really *private* of course, (as explained in other answers), but there you go.
```
def _i_am_private(self):
"""If you call me from a subclass you are a nau... |
Making a method private in a python subclass | 451,963 | 24 | 2009-01-16T20:53:50Z | 452,316 | 12 | 2009-01-16T22:42:42Z | [
"python",
"oop",
"inheritance"
] | Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :
```
class A:
def __init__(self):
#do something here
def method(self):
#some code here
class B(A):
def __init__(self):
... | You can prefix methods and members with a single or double underscore. A single underscore implies "please don't use me, I'm supposed to be used only by this class", and a double underscore instructs the Python compiler to mangle the method/member name with the class name; as long as the class and its subclasses don't ... |
Making a method private in a python subclass | 451,963 | 24 | 2009-01-16T20:53:50Z | 458,101 | 7 | 2009-01-19T16:03:19Z | [
"python",
"oop",
"inheritance"
] | Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :
```
class A:
def __init__(self):
#do something here
def method(self):
#some code here
class B(A):
def __init__(self):
... | "Everything must be public" proponents think the author is trying to hide a useful API from the users. This guy doesn't want to violate an unquestionable law of Python. He wants to use some methods to define a useful API, and he wants to use other methods to organize the implementation of that API. If there's no separa... |
Making a method private in a python subclass | 451,963 | 24 | 2009-01-16T20:53:50Z | 5,851,875 | 27 | 2011-05-01T22:26:19Z | [
"python",
"oop",
"inheritance"
] | Is it possible to make a public method private in a subclass ? I don't want other classes extending this one to be able to call some of the methods . Here is an example :
```
class A:
def __init__(self):
#do something here
def method(self):
#some code here
class B(A):
def __init__(self):
... | Contrary to popular fashion on this subject, there **are** legitimate reasons to have a distinction between public, private, and protected members, whether you work in Python or a more traditional OOP environment. Many times, it comes to be that you develop auxiliary methods for a particularly long-winded task at some ... |
Is it worth using Python's re.compile? | 452,104 | 238 | 2009-01-16T21:31:57Z | 452,142 | 34 | 2009-01-16T21:42:37Z | [
"python",
"regex"
] | Is there any benefit in using compile for regular expressions in Python?
```
h = re.compile('hello')
h.match('hello world')
```
vs
```
re.match('hello', 'hello world')
``` | FWIW:
```
$ python -m timeit -s "import re" "re.match('hello', 'hello world')"
100000 loops, best of 3: 3.82 usec per loop
$ python -m timeit -s "import re; h=re.compile('hello')" "h.match('hello world')"
1000000 loops, best of 3: 1.26 usec per loop
```
so, if you're going to be using the *same* regex a lot, it may ... |
Is it worth using Python's re.compile? | 452,104 | 238 | 2009-01-16T21:31:57Z | 452,143 | 258 | 2009-01-16T21:42:57Z | [
"python",
"regex"
] | Is there any benefit in using compile for regular expressions in Python?
```
h = re.compile('hello')
h.match('hello world')
```
vs
```
re.match('hello', 'hello world')
``` | I've had a lot of experience running a compiled regex 1000s of times versus compiling on-the-fly, and have not noticed any perceivable difference. Obviously, this is anecdotal, and certainly not a great argument *against* compiling, but I've found the difference to be negligible.
EDIT:
After a quick glance at the actu... |
Is it worth using Python's re.compile? | 452,104 | 238 | 2009-01-16T21:31:57Z | 453,568 | 71 | 2009-01-17T16:49:07Z | [
"python",
"regex"
] | Is there any benefit in using compile for regular expressions in Python?
```
h = re.compile('hello')
h.match('hello world')
```
vs
```
re.match('hello', 'hello world')
``` | For me, the biggest benefit to `re.compile` isn't any kind of premature optimization (which is the [root of all evil](http://programmers.stackexchange.com/questions/39/whats-your-favourite-quote-about-programming/816#816), [anyway](http://en.wikipedia.org/wiki/Optimization_%28computer_science%29#When_to_optimize "read ... |
Is it worth using Python's re.compile? | 452,104 | 238 | 2009-01-16T21:31:57Z | 13,640,709 | 27 | 2012-11-30T07:24:30Z | [
"python",
"regex"
] | Is there any benefit in using compile for regular expressions in Python?
```
h = re.compile('hello')
h.match('hello world')
```
vs
```
re.match('hello', 'hello world')
``` | Here's a simple test case:
```
~$ for x in 1 10 100 1000 10000 100000 1000000; do python -m timeit -n $x -s 'import re' 're.match("[0-9]{3}-[0-9]{3}-[0-9]{4}", "123-123-1234")'; done
1 loops, best of 3: 3.1 usec per loop
10 loops, best of 3: 2.41 usec per loop
100 loops, best of 3: 2.24 usec per loop
1000 loops, best ... |
How can I install the Beautiful Soup module on the Mac? | 452,283 | 38 | 2009-01-16T22:26:45Z | 452,302 | 69 | 2009-01-16T22:37:30Z | [
"python",
"osx",
"module",
"installation"
] | I read this without finding the solution: <http://docs.python.org/install/index.html> | The "normal" way is to:
* Go to the Beautiful Soup web site, <http://www.crummy.com/software/BeautifulSoup/>
* Download the package
* Unpack it
* In a Terminal window, `cd` to the resulting directory
* Type `python setup.py install`
Another solution is to use `easy_install`. Go to <http://peak.telecommunity.com/DevCe... |
How can I install the Beautiful Soup module on the Mac? | 452,283 | 38 | 2009-01-16T22:26:45Z | 452,311 | 14 | 2009-01-16T22:41:46Z | [
"python",
"osx",
"module",
"installation"
] | I read this without finding the solution: <http://docs.python.org/install/index.html> | Brian beat me too it, but since I already have the transcript:
[easy\_install](http://peak.telecommunity.com/DevCenter/EasyInstall)
```
aaron@ares ~$ sudo easy_install BeautifulSoup
Searching for BeautifulSoup
Best match: BeautifulSoup 3.0.7a
Processing BeautifulSoup-3.0.7a-py2.5.egg
BeautifulSoup 3.0.7a is already t... |
How can I install the Beautiful Soup module on the Mac? | 452,283 | 38 | 2009-01-16T22:26:45Z | 24,178,431 | 12 | 2014-06-12T07:08:25Z | [
"python",
"osx",
"module",
"installation"
] | I read this without finding the solution: <http://docs.python.org/install/index.html> | I think the current right way to do this is by `pip` like Pramod comments
```
pip install beautifulsoup4
```
because of last changes in Python, see discussion [here](http://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install).
This was not so in the past. |
Python object.__repr__(self) should be an expression? | 452,300 | 51 | 2009-01-16T22:37:18Z | 452,310 | 54 | 2009-01-16T22:41:37Z | [
"python"
] | I was looking at the builtin object methods in the [Python documentation](http://docs.python.org/reference/datamodel.html#objects-values-and-types), and I was interested in the documentation for `object.__repr__(self)`. Here's what it says:
> Called by the repr() built-in function
> and by string conversions (reverse
... | ```
>>> from datetime import date
>>>
>>> repr(date.today()) # calls date.today().__repr__()
'datetime.date(2009, 1, 16)'
>>> eval(_) # _ is the output of the last command
datetime.date(2009, 1, 16)
```
The output is a string that can be parsed by the python interpreter and results in an equal... |
Python object.__repr__(self) should be an expression? | 452,300 | 51 | 2009-01-16T22:37:18Z | 452,312 | 24 | 2009-01-16T22:42:22Z | [
"python"
] | I was looking at the builtin object methods in the [Python documentation](http://docs.python.org/reference/datamodel.html#objects-values-and-types), and I was interested in the documentation for `object.__repr__(self)`. Here's what it says:
> Called by the repr() built-in function
> and by string conversions (reverse
... | It should be a Python expression that, when eval'd, creates an object with the exact same properties as this one. For example, if you have a `Fraction` class that contains two integers, a numerator and denominator, your `__repr__()` method would look like this:
```
# in the definition of Fraction class
def __repr__(se... |
Python object.__repr__(self) should be an expression? | 452,300 | 51 | 2009-01-16T22:37:18Z | 453,381 | 9 | 2009-01-17T14:42:03Z | [
"python"
] | I was looking at the builtin object methods in the [Python documentation](http://docs.python.org/reference/datamodel.html#objects-values-and-types), and I was interested in the documentation for `object.__repr__(self)`. Here's what it says:
> Called by the repr() built-in function
> and by string conversions (reverse
... | **Guideline:** If you can succinctly provide an *exact representation*, **format it as a Python expression** (which implies that it can be both eval'd and copied directly into source code, in the right context). If providing an *inexact representation*, **use `<...>` format**.
There are many possible representations f... |
What are the benefits of using Python for web programming? | 452,305 | 9 | 2009-01-16T22:38:56Z | 452,324 | 13 | 2009-01-16T22:45:56Z | [
"python",
"programming-languages"
] | What makes Python stand out for use in web development? What are some examples of highly successful uses of Python on the web? | [Django](http://www.djangoproject.com/) is, IMHO, one of the major benefits of using Python. Model your domain, code your classes, and voila, your ORM is done, and you can focus on the UI. Add in the ease of templating with the built-in templating language (or one of many others you can use as well), and it becomes *ve... |
How do I create a list of Python lambdas (in a list comprehension/for loop)? | 452,610 | 16 | 2009-01-17T01:19:13Z | 452,639 | 11 | 2009-01-17T01:37:51Z | [
"python",
"lambda",
"scope",
"closures",
"list-comprehension"
] | I want to create a list of lambda objects from a list of constants in Python; for instance:
```
listOfNumbers = [1,2,3,4,5]
square = lambda x: x * x
listOfLambdas = [lambda: square(i) for i in listOfNumbers]
```
This will create a list of lambda objects, however, when I run them:
```
for f in listOfLambdas:
prin... | I'm guessing that the lambda you're creating in the list comprehension is bound to the variable i which eventually ends up at 5. Thus, when you evaluate the lambdas after the fact, they're all bound to 5 and end up calculating 25. The same thing is happening with num in your second example. When you evaluate the lambda... |
How do I create a list of Python lambdas (in a list comprehension/for loop)? | 452,610 | 16 | 2009-01-17T01:19:13Z | 452,659 | 17 | 2009-01-17T01:51:59Z | [
"python",
"lambda",
"scope",
"closures",
"list-comprehension"
] | I want to create a list of lambda objects from a list of constants in Python; for instance:
```
listOfNumbers = [1,2,3,4,5]
square = lambda x: x * x
listOfLambdas = [lambda: square(i) for i in listOfNumbers]
```
This will create a list of lambda objects, however, when I run them:
```
for f in listOfLambdas:
prin... | You have:
```
listOfLambdas = [lambda: i*i for i in range(6)]
for f in listOfLambdas:
print f()
```
Output:
```
25
25
25
25
25
25
```
You need currying! Aside from being delicious, use this default value "hack".
```
listOfLambdas = [lambda i=i: i*i for i in range(6)]
for f in listOfLambdas:
print f()
```... |
Does python have an equivalent to Java Class.forName()? | 452,969 | 76 | 2009-01-17T08:10:48Z | 452,971 | 20 | 2009-01-17T08:13:05Z | [
"java",
"python",
"class",
"instantiation"
] | I have the need to take a string argument and create an object of the class named in that string in Python. In Java, I would use `Class.forName().newInstance()`. Is there an equivalent in Python?
---
Thanks for the responses. To answer those who want to know what I'm doing: I want to use a command line argument as th... | Assuming the class is in your scope:
```
globals()['classname'](args, to, constructor)
```
Otherwise:
```
getattr(someModule, 'classname')(args, to, constructor)
```
Edit: Note, you can't give a name like 'foo.bar' to getattr. You'll need to split it by . and call getattr() on each piece left-to-right. This will ha... |
Does python have an equivalent to Java Class.forName()? | 452,969 | 76 | 2009-01-17T08:10:48Z | 452,981 | 135 | 2009-01-17T08:25:39Z | [
"java",
"python",
"class",
"instantiation"
] | I have the need to take a string argument and create an object of the class named in that string in Python. In Java, I would use `Class.forName().newInstance()`. Is there an equivalent in Python?
---
Thanks for the responses. To answer those who want to know what I'm doing: I want to use a command line argument as th... | Reflection in python is a lot easier and far more flexible than it is in Java.
I recommend reading this [tutorial](http://www.diveintopython.net/power_of_introspection/index.html)
There's no direct function (that I know of) which takes a fully qualified class name and returns the class, however you have all the piece... |
What is the practical difference between xml, json, rss and atom when interfacing with Twitter? | 453,158 | 5 | 2009-01-17T11:19:36Z | 453,389 | 7 | 2009-01-17T14:45:23Z | [
"python",
"xml",
"json",
"twitter",
"twisted"
] | I'm new to web services and as an introduction I'm playing around with the Twitter API using the Twisted framework in python. I've read up on the different formats they offer, but it's still not clear to me which one I should use in my fairly simple project.
Specifically the practical difference between using JSON or X... | For me it boils down to convenience. Using XML, I have to parse the response in to a DOM (or more usually an ElementTree). Using JSON, one call to simplejson.loads(json\_string) and I have a native Python data structure (lists, dictionaries, strings etc) which I can start iterating over and processing. Anything that me... |
Advice regarding IPython + MacVim Workflow | 453,329 | 18 | 2009-01-17T13:46:27Z | 453,837 | 14 | 2009-01-17T19:13:43Z | [
"python",
"vim",
"ipython"
] | I've just found [IPython](http://ipython.scipy.org/) and I can report that I'm in deep love. And the affection was immediate. I think this affair will turn into something lasting, like [the one I have with screen](http://stackoverflow.com/questions/431521/run-a-command-in-a-shell-and-keep-running-the-command-when-you-c... | I use Linux, but I believe this tip can be used in OS X too. I use [GNU Screen](http://www.gnu.org/software/screen/) to send IPython commands from Vim as recommended by [this tip](http://vim.wikia.com/wiki/IPython_integration). This is how I do it:
First, you should open a terminal and start a screen session called 'i... |
Writing a simple "Rock Paper Scissors" game bot | 453,396 | 7 | 2009-01-17T14:50:12Z | 453,400 | 29 | 2009-01-17T14:53:03Z | [
"python"
] | I need help with a python game im working on (I just started learning Python about 3 days ago, so I'm still a nOob =)
This is what I came up with:
```
import random
from time import sleep
print "Please select: "
print "1 Rock"
print "2 Paper"
print "3 Scissors"
player = input ("Choose from 1-3: ")
if pl... | Well, you've already imported the random module, that's a start.
Try the random.choice function.
```
>>> from random import choice
>>> cpu_choice = choice(('rock', 'paper', 'scissors'))
``` |
Writing a simple "Rock Paper Scissors" game bot | 453,396 | 7 | 2009-01-17T14:50:12Z | 453,502 | 7 | 2009-01-17T16:05:47Z | [
"python"
] | I need help with a python game im working on (I just started learning Python about 3 days ago, so I'm still a nOob =)
This is what I came up with:
```
import random
from time import sleep
print "Please select: "
print "1 Rock"
print "2 Paper"
print "3 Scissors"
player = input ("Choose from 1-3: ")
if pl... | ```
import random
ROCK, PAPER, SCISSORS = 1, 2, 3
names = 'ROCK', 'PAPER', 'SCISSORS'
def beats(a, b):
if (a,b) in ((ROCK, PAPER), (PAPER, SCISSORS), (SCISSORS, ROCK)):
return False
return True
print "Please select: "
print "1 Rock"
print "2 Paper"
print "3 Scissors"
player = int(input ("C... |
Queryset API distinct() does not work? | 453,477 | 5 | 2009-01-17T15:49:11Z | 476,232 | 7 | 2009-01-24T16:16:07Z | [
"python",
"django"
] | ```
class Message(models.Model):
subject = models.CharField(max_length=100)
pub_date = models.DateTimeField(default=datetime.now())
class Topic(models.Model):
title = models.CharField(max_length=100)
message = models.ManyToManyField(Message, verbose_name='Discussion')
```
I want to get order all the t... | You don't need distinct() here, what you need is [aggregation](http://docs.djangoproject.com/en/dev/topics/db/aggregation/#topics-db-aggregation). This query will do what you want:
```
from django.db.models import Max
Topic.objects.annotate(Max('message__pub_date')).order_by('-message__pub_date__max')
```
Though if t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.