title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How to use django-compressor behind load balancer? | 7,246,865 | 10 | 2011-08-30T16:52:20Z | 7,309,624 | 10 | 2011-09-05T14:44:57Z | [
"python",
"django",
"django-compressor"
] | I have two servers behind a load balancer. Each server is running a memcached server and the settings file (which is identical on both servers) has them both defined (in short: shared cache).
I want the paths to the generated files to be identical on the servers so that the client does not have to download more than o... | In the develop branch there is a new option to change the css hashing method.
<https://github.com/jezdez/django_compressor>
See [line 61 in filters/css\_default.py](https://github.com/jezdez/django_compressor/blob/develop/compressor/filters/css_default.py#L61)
**The settings I'm using:**
```
COMPRESS_ENABLED = True
... |
Size of list in memory | 7,247,298 | 28 | 2011-08-30T17:29:01Z | 7,247,484 | 7 | 2011-08-30T17:44:32Z | [
"python",
"python-3.x"
] | I just experimented with the size of python datastructures in memory. I wrote the following snippet:
```
import sys
lst1=[]
lst1.append(1)
lst2=[1]
print(sys.getsizeof(lst1), sys.getsizeof(lst2))
```
I tested the code on the following configurations:
* Windows 7 64bit, Python3.1: the output is: `52 40` so lst1 has 5... | sorry, previous comment was a bit curt.
what's happening is that you're looking at how lists are allocated (and i think maybe you just wanted to see how big things were - in that case, use `sys.getsizeof()`)
when something is added to a list, one of two things can happen:
1. the extra item fits in spare space
2. ext... |
Size of list in memory | 7,247,298 | 28 | 2011-08-30T17:29:01Z | 7,247,542 | 59 | 2011-08-30T17:49:35Z | [
"python",
"python-3.x"
] | I just experimented with the size of python datastructures in memory. I wrote the following snippet:
```
import sys
lst1=[]
lst1.append(1)
lst2=[1]
print(sys.getsizeof(lst1), sys.getsizeof(lst2))
```
I tested the code on the following configurations:
* Windows 7 64bit, Python3.1: the output is: `52 40` so lst1 has 5... | Here's a fuller interactive session that will help me explain what's going on (Python 2.6 on Windows XP 32-bit, but it doesn't matter really):
```
>>> import sys
>>> sys.getsizeof([])
36
>>> sys.getsizeof([1])
40
>>> lst = []
>>> lst.append(1)
>>> sys.getsizeof(lst)
52
>>>
```
Note that the empty list is a bit smalle... |
Python and 16 Bit Tiff | 7,247,371 | 10 | 2011-08-30T17:35:38Z | 9,031,687 | 7 | 2012-01-27T10:09:41Z | [
"python",
"tiff",
"16-bit"
] | How can I convert and save a 16 bit single-channel TIF in Python?
I can load a 16 and 32 bit image without an issue, and see that the 32 bit image is mode `F` and the 16 bit image is mode `I;16S`:
```
import Image
i32 = Image.open('32.tif')
i16 = Image.open('16.tif')
i32
# <TiffImagePlugin.TiffImageFile image mode=F ... | Stumbled on this thread trying to save 16 bit TIFF images with PIL / numpy.
Versions: python 2.7.1 - numpy 1.6.1 - PIL 1.1.7
Here's a quick test I wrote. uint16 numpy array -> converted to string -> converted to a PIL image of type 'I;16' -> saved as a 16 bit TIFF.
Opening the image in ImageJ shows the right horizon... |
Using __getattribute__ or __getattr__ to call methods in Python | 7,247,868 | 8 | 2011-08-30T18:19:10Z | 7,247,937 | 7 | 2011-08-30T18:26:21Z | [
"python",
"getattr",
"getattribute"
] | I am trying to create a subclass which acts as a list of custom classes. However, I want the list to inherit the methods and attributes of the parent class and return a sum of the quantities of each item. I am attempting to do this using the `__getattribute__` method, but I cannot figure out how to pass arguments to ca... | You have a few points of confusion here:
1) `__getattribute__` intercepts all attribute access, which isn't what you want. You only want your code to step in if a real attribute doesn't exist, so you want `__getattr__`.
2) Your `__getattribute__` is calling the method on the list elements, but it shouldn't be doing r... |
Using __getattribute__ or __getattr__ to call methods in Python | 7,247,868 | 8 | 2011-08-30T18:19:10Z | 7,247,957 | 8 | 2011-08-30T18:28:08Z | [
"python",
"getattr",
"getattribute"
] | I am trying to create a subclass which acts as a list of custom classes. However, I want the list to inherit the methods and attributes of the parent class and return a sum of the quantities of each item. I am attempting to do this using the `__getattribute__` method, but I cannot figure out how to pass arguments to ca... | This code is awful and really not Pythonic at all. There's no way for you to pass extra argument in the `__getattribute__`, so you shouldn't try to do any implicit magic like this. It would be better written like this:
```
class Product(object):
def __init__(self, price, quantity):
self.price = price
... |
Python duck-typing for MVC event handling in pygame | 7,249,388 | 7 | 2011-08-30T20:28:25Z | 7,294,148 | 12 | 2011-09-03T15:56:13Z | [
"python",
"model-view-controller",
"pygame",
"duck-typing",
"isinstance"
] | A friend and I have been playing around with pygame some and came across [this tutorial for building games](http://ezide.com/games/writing-games.html) using pygame. We really liked how it broke out the game into a model-view-controller system with events as a go-between, but the code makes *heavy* use of `isinstance` c... | A cleaner way of handling events (and also a lot faster, but possibly consumes a bit more memory) is to have multiple event handler functions in your code. Something along these lines:
# The Desired Interface
```
class KeyboardEvent:
pass
class MouseEvent:
pass
class NotifyThisClass:
def __init__(self, ... |
How to build debian package with CPack to execute setup.py? | 7,249,440 | 13 | 2011-08-30T20:32:33Z | 7,918,913 | 11 | 2011-10-27T16:06:57Z | [
"python",
"cmake",
"packages",
"deb",
"cpack"
] | Until now, my project had only **.cpp** files that were compiled into different binaries and I managed to configure **CPack** to build a proper **debian package** without any problems.
Recently I wrote a couple of python applications and added them to the project, as well as some custom modules that I would also like ... | I figured out a way to do it but it's not very simple. I'll do my best to explain the procedure so please be patient.
## The idea of this approach is to use *postinst* and *prerm* to install and remove the python application from the system.
In the **CMakeLists.txt** that defines the project, you need to state that *... |
Permission Denied on httplib2 install | 7,249,773 | 3 | 2011-08-30T21:01:20Z | 7,249,820 | 11 | 2011-08-30T21:05:44Z | [
"python",
"terminal",
"httplib2"
] | I'm trying to install the httplib2 library for Python so I can use it to interact with the Twitter but I get the following error in the console when I try to install via 'python setup.py install'.
This is a new MBA and I am the only user (and Admin) so I shouldn't get denied so rudely!
```
error: could not create '/L... | Use [`sudo`](http://www.manpagez.com/man/8/sudo/) to run `setup.py` as root:
```
% sudo python setup.py install
``` |
Permission Denied on httplib2 install | 7,249,773 | 3 | 2011-08-30T21:01:20Z | 17,900,352 | 8 | 2013-07-27T17:03:33Z | [
"python",
"terminal",
"httplib2"
] | I'm trying to install the httplib2 library for Python so I can use it to interact with the Twitter but I get the following error in the console when I try to install via 'python setup.py install'.
This is a new MBA and I am the only user (and Admin) so I shouldn't get denied so rudely!
```
error: could not create '/L... | Some say that using `sudo` on `python setup.py install` can be dangerous. Instead, run `sudo chown -R $USER /Library/Python/2.7`.
TL;DR; Using [Virtualenv](http://www.pythonforbeginners.com/basics/how-to-use-python-virtualenv/) also happens to avoid this problem. |
getting ProcessId within Python code | 7,250,126 | 14 | 2011-08-30T21:37:10Z | 7,250,350 | 17 | 2011-08-30T22:05:05Z | [
"python"
] | I am in Windows and Suppose I have a main python code that calls python interpreter in command line to execute another python script ,say test.py .
So test.py is executed as a new process.How can I find the processId for this porcess in Python ?
**Update:**
To be more specific , we have os.getpid() in os module. It ... | If you used subprocess to spawn the shell, you can find the process ID in the [`pid`](http://docs.python.org/library/subprocess.html#subprocess.Popen.pid) property:
```
sp = subprocess.Popen(['python', 'script.py'])
print('PID is ' + str(sp.pid))
```
If you used multiprocessing, use *its* [pid](http://docs.python.org... |
Python code to generate part of sphinx documentation, is it possible? | 7,250,659 | 15 | 2011-08-30T22:46:33Z | 7,259,267 | 17 | 2011-08-31T15:17:44Z | [
"python",
"documentation",
"python-sphinx",
"restructuredtext"
] | I am using [sphinx](http://sphinx.pocoo.org/index.html) to generate the documentation for a project of mines.
In such project, I describe a list of available commands in a [yaml](http://yaml.org) file which, once loaded, results in a dictionary in the form `{command-name : command-description}` for example:
```
comma... | At the end I find a way to achieve what I wanted. Here's the how-to:
1. **Create a python script** (let's call it `generate-includes.py`) that will generate the *reStructuredText* and save it in the `myrst.inc` file. (In my example, this would be the script loading and parsing the YAML, but this is irrelevant). *Make ... |
Python code to generate part of sphinx documentation, is it possible? | 7,250,659 | 15 | 2011-08-30T22:46:33Z | 18,143,318 | 7 | 2013-08-09T09:14:48Z | [
"python",
"documentation",
"python-sphinx",
"restructuredtext"
] | I am using [sphinx](http://sphinx.pocoo.org/index.html) to generate the documentation for a project of mines.
In such project, I describe a list of available commands in a [yaml](http://yaml.org) file which, once loaded, results in a dictionary in the form `{command-name : command-description}` for example:
```
comma... | An improvement based on Michael's code and the built-in include directive:
```
import sys
from os.path import basename
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from sphinx.util.compat import Directive
from docutils import nodes, statemachine
class ExecDirective(Directiv... |
PYTHON-2.x Syntax error on line 1 but i don't see any? | 7,250,921 | 4 | 2011-08-30T23:26:09Z | 7,251,031 | 8 | 2011-08-30T23:45:51Z | [
"python",
"syntax-error",
"python-2.x"
] | the following file is located in this directory: `/Users/whiteglider/Documents`
name of file: `server.py`
this is my practice code which i just copied from <http://www.tutorialspoint.com/python/python_networking.htm>
```
import socket
s=socket.socket()
host=socket.gethostname()
port=12345
s.bind... | You've saved the file as a Rich Text Format file rather than a plain text file.
I don't know what editor you're using, but make sure to save the file as plain text / ASCII text, something like that, not RTF. |
Running maximum of numpy array values | 7,251,421 | 15 | 2011-08-31T00:44:47Z | 7,251,598 | 23 | 2011-08-31T01:16:33Z | [
"python",
"numpy"
] | I need a fast way to keep a running maximum of a numpy array. For example, if my array was:
```
x = numpy.array([11,12,13,20,19,18,17,18,23,21])
```
I'd want:
```
numpy.array([11,12,13,20,20,20,20,20,23,23])
```
Obviously I could do this with a little loop:
```
def running_max(x):
result = [x[0]]
for val i... | `numpy.maximum.accumulate` works for me.
```
>>> import numpy
>>> numpy.maximum.accumulate(numpy.array([11,12,13,20,19,18,17,18,23,21]))
array([11, 12, 13, 20, 20, 20, 20, 20, 23, 23])
``` |
What does 'while' with an integer mean in Python and how does this GCD code work? | 7,251,492 | 5 | 2011-08-31T00:55:54Z | 7,251,556 | 8 | 2011-08-31T01:09:01Z | [
"python",
"python-3.x"
] | I found this greatest common denominator code:
```
def gcd(x,y):
while y:
x, y = y, x % y
return x
```
I cannot understand what we mean by `while y` as `y` is an integer. How does it work? Furthermore, what does the line `x, y = y, x % y` add to the code? | For `while`, read this: <http://docs.python.org/reference/compound_stmts.html#the-while-statement>
It says "This repeatedly tests the expression and, if it is true, executes the first suite;"
Now the question is: What's True?
Read this: <http://docs.python.org/library/functions.html#bool>
Then read this: <http://do... |
Instantiate all functions in Python | 7,252,640 | 3 | 2011-08-31T04:45:13Z | 7,252,649 | 7 | 2011-08-31T04:46:56Z | [
"python"
] | Is there a way to do something like this:
```
util.py contains:
def add
def subtract
instantiate.py contains:
def instantiate
```
where instantiate does:
```
import util
def instantiate():
add = util.add
subtract = util.subtract
```
So I can skip typing `util` everytime I use a function and I can instantia... | You can import specific functions from a module :
```
from util import add, substract
``` |
How to add .xml extension to all files in a folder in Unix/Linux | 7,253,198 | 6 | 2011-08-31T06:11:25Z | 7,253,271 | 14 | 2011-08-31T06:19:56Z | [
"php",
"python",
"linux",
"shell",
"unix"
] | I want to rename all files in a folder and add a `.xml` extension. I am using Unix. How can I do that? | On the shell, you can do this:
```
for file in *; do
if [ -f ${file} ]; then
mv ${file} ${file}.xml
fi
done
```
**Edit**
To do this recursively on all subdirectories, you should use `find`:
```
for file in $(find -type f); do
mv ${file} ${file}.xml
done
```
On the other hand, if you're going to... |
How to embed a terminal in a Tkinter application? | 7,253,448 | 8 | 2011-08-31T06:41:55Z | 7,331,836 | 12 | 2011-09-07T09:47:26Z | [
"python",
"tkinter"
] | I want to embed a terminal in my main Tkinter window. I would like to have a sub window where a terminal (Bash based terminal) would run. I would like also to be able to let my program interact with the terminal, at least I would like to read the current working directory and/or set it.
I don't know if it is really im... | I am happy to say that it is in fact possible to do it, and you can do it with just a few lines of code (*I don't know if it is so easy with other toolkits*):
```
from Tkinter import *
import os
root = Tk()
termf = Frame(root, height=400, width=500)
termf.pack(fill=BOTH, expand=YES)
wid = termf.winfo_id()
os.system(... |
How to get everything after last slash in a URL? | 7,253,803 | 29 | 2011-08-31T07:23:22Z | 7,253,830 | 76 | 2011-08-31T07:28:00Z | [
"python",
"parsing",
"url"
] | How can I extract whatever follows the last slash in a URL in Python? For example, these URLs should return the following:
```
URL: http://www.test.com/TEST1
returns: TEST1
URL: http://www.test.com/page/TEST2
returns: TEST2
URL: http://www.test.com/page/page/12345
returns: 12345
```
I've tried urlparse, but that gi... | You don't need fancy things, just see [the string methods in the standard library](http://docs.python.org/py3k/library/stdtypes.html#str.rsplit) and you can easily split your url between 'filename' part and the rest:
```
url.rsplit('/', 1)
```
So you can get the part you're interested in simply with:
```
url.rsplit(... |
How to get everything after last slash in a URL? | 7,253,803 | 29 | 2011-08-31T07:23:22Z | 7,253,832 | 8 | 2011-08-31T07:28:17Z | [
"python",
"parsing",
"url"
] | How can I extract whatever follows the last slash in a URL in Python? For example, these URLs should return the following:
```
URL: http://www.test.com/TEST1
returns: TEST1
URL: http://www.test.com/page/TEST2
returns: TEST2
URL: http://www.test.com/page/page/12345
returns: 12345
```
I've tried urlparse, but that gi... | [`rsplit`](http://docs.python.org/library/stdtypes.html#str.rsplit) should be up to the task:
```
In [1]: 'http://www.test.com/page/TEST2'.rsplit('/', 1)[1]
Out[1]: 'TEST2'
``` |
How to get everything after last slash in a URL? | 7,253,803 | 29 | 2011-08-31T07:23:22Z | 7,253,858 | 30 | 2011-08-31T07:31:17Z | [
"python",
"parsing",
"url"
] | How can I extract whatever follows the last slash in a URL in Python? For example, these URLs should return the following:
```
URL: http://www.test.com/TEST1
returns: TEST1
URL: http://www.test.com/page/TEST2
returns: TEST2
URL: http://www.test.com/page/page/12345
returns: 12345
```
I've tried urlparse, but that gi... | One more (idio(ma)tic) way:
```
URL.split("/")[-1]
``` |
Python - how to convert int to string represent a 32bit Hex number | 7,253,907 | 10 | 2011-08-31T07:35:14Z | 7,253,918 | 20 | 2011-08-31T07:36:47Z | [
"python",
"integer",
"hex"
] | I want to get a python solution for this problem:
e.g.
```
integer 1 -> string "0x00000001"
integer 64 -> string "0x00000040"
integer 3652458 -> string "0x0037BB6A"
```
The string size will not be change if number is in `range(0, 2**32)`. | Try this:
```
'0x%08X' % 3652458
```
or (with Python 2.6 and newer)
```
'0x{0:08X}'.format(3652458)
```
both return:
```
'0x0037BB6A'
``` |
python : working with german umlaut | 7,254,047 | 11 | 2011-08-31T07:52:04Z | 7,254,078 | 25 | 2011-08-31T07:54:37Z | [
"python",
"unicode",
"diacritics"
] | ```
months = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]
print months[2].decode("utf-8")
```
Printing month[2] fails with
```
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-2: invalid data
```
help to get rid of this! | Did you add an encoding in the begining of your source file ?
```
# -*- coding: utf-8 -*-
``` |
Change Cherrypy Port and restart web server | 7,254,845 | 6 | 2011-08-31T09:08:59Z | 7,254,915 | 12 | 2011-08-31T09:16:25Z | [
"python",
"webserver",
"port",
"cherrypy"
] | Is there a way in python to change the port that `cherrypy` is using and force the web server (not apache, cherrypy) to restart? | Have a look at [cherrypy.process.servers](http://docs.cherrypy.org/dev/refman/process/servers.html). You can try something like this:
```
import cherrypy
cherrypy.config.update({'server.socket_port': 8099})
cherrypy.engine.restart()
``` |
Python list append behavior | 7,255,383 | 16 | 2011-08-31T10:00:40Z | 7,255,393 | 17 | 2011-08-31T10:01:30Z | [
"python",
"list"
] | Don't really know how to formulate the question...
Suppose I do the following:
```
>>> l = [[]]*2
>>> l
[[], []]
>>> l[0].append(1)
>>> l
[[1], [1]]
```
Why does 1 gets appended to both lists? | `[[]]*2` is a list of two references to **the same list**. You are appending to it and then seeing it twice. |
Python list append behavior | 7,255,383 | 16 | 2011-08-31T10:00:40Z | 7,255,405 | 11 | 2011-08-31T10:02:28Z | [
"python",
"list"
] | Don't really know how to formulate the question...
Suppose I do the following:
```
>>> l = [[]]*2
>>> l
[[], []]
>>> l[0].append(1)
>>> l
[[1], [1]]
```
Why does 1 gets appended to both lists? | Because there is really only one list. Consider this:
```
>>> l = [[]]
>>> l2 = l*2
>>> l2[0] is l[0]
True
>>> l2[1] is l[0]
True
```
`*2` performed on a list does not copy the list but return a list of length `2` filled with the same reference.
What you probably wanted was this:
```
>>> l = [[] for _ in xrange(2)]... |
Exit while loop by user hitting ENTER key | 7,255,463 | 7 | 2011-08-31T10:07:36Z | 17,862,622 | 9 | 2013-07-25T15:39:28Z | [
"python",
"while-loop"
] | I am a python newbie and have been asked to carry out some exercises using while and for loops. I have been asked to make a program loop until exit is requested by the user hitting `<Return>` only. So far I have:
```
User = raw_input('Enter <Carriage return> only to exit: ')
running = 1
while running == 1:
Run my ... | I ran into this page while (no pun) looking for something else. Here is what I use:
```
while True:
i = input("Enter text (or Enter to quit): ")
if not i:
break
print("Your input:", i)
print("While loop has exited")
``` |
Exit while loop by user hitting ENTER key | 7,255,463 | 7 | 2011-08-31T10:07:36Z | 22,519,365 | 9 | 2014-03-19T22:19:15Z | [
"python",
"while-loop"
] | I am a python newbie and have been asked to carry out some exercises using while and for loops. I have been asked to make a program loop until exit is requested by the user hitting `<Return>` only. So far I have:
```
User = raw_input('Enter <Carriage return> only to exit: ')
running = 1
while running == 1:
Run my ... | The exact thing you want ;)
<http://stackoverflow.com/a/22391379/3394391>
```
import sys, select, os
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print "I'm doing stuff. Press Enter to stop me!"
print i
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = raw... |
How to subclass str in Python | 7,255,655 | 14 | 2011-08-31T10:28:28Z | 7,255,782 | 21 | 2011-08-31T10:39:52Z | [
"python",
"fluent-interface"
] | I am trying to subclass str object, and add couple of methods to it. My main purpose is to learn how to do it. Where I am stuck is, am I supposed to subclass string in a metaclass, and create my class with that meta, or subclass str directly? And also, I guess I need to implement `__new__()` somehow, because, my custom... | Overwriting `__new__()` works if you want to modify the string on construction:
```
class caps(str):
def __new__(cls, content):
return str.__new__(cls, content.upper())
```
But if you just want to add new methods, you don't even have to touch the constructor:
```
class text(str):
def duplicate(self):
... |
How to subclass str in Python | 7,255,655 | 14 | 2011-08-31T10:28:28Z | 7,255,971 | 8 | 2011-08-31T10:58:42Z | [
"python",
"fluent-interface"
] | I am trying to subclass str object, and add couple of methods to it. My main purpose is to learn how to do it. Where I am stuck is, am I supposed to subclass string in a metaclass, and create my class with that meta, or subclass str directly? And also, I guess I need to implement `__new__()` somehow, because, my custom... | Here's a quick hack to do what you want: you basically intercept every function call, and, if you see that it's returning a string, you convert it back to your own class type.
While this works in this simple example, it has some limitations. Among other things, operators such as the subscript operator are apparently n... |
Can I efficiently swap two class instances by swapping __dict__? | 7,255,777 | 14 | 2011-08-31T10:38:45Z | 7,256,456 | 9 | 2011-08-31T11:44:46Z | [
"python"
] | I have a big class with lots of members, and quite a few references to instances of this class lying around. Unfortunately (for reasonable reasons) all these references are the wrong way around.
Instead of re-creating each (and finding and updating everywhere the objects are referenced), or adding an extra level of in... | ## Edit
What you're doing is possible, although it will make people cringe because it is hackish. If at all possible, I would suggest that you look at rewriting/refactoring your comparison operators. That will give you the best outcome by far. Of course, not knowing the scope or time-frame involved, it is very difficu... |
Save/dump a YAML file with comments in PyYAML | 7,255,885 | 22 | 2011-08-31T10:50:04Z | 7,255,983 | 7 | 2011-08-31T10:59:43Z | [
"python",
"yaml",
"pyyaml"
] | I have a yaml file that looks like this:
```
# The following key opens a door
key: value
```
Is there a way I can `load` and `dump` this data while maintaining the comment? | PyYAML throws away comments at a very low level (in `Scanner.scan_to_next_token`).
While you could adapt or extend it to handle comments in its whole stack, this would be a major modification. `Dump`ing (=emitting) comments seems to be easier and [is already being discussed](http://pyyaml.org/ticket/114). |
Save/dump a YAML file with comments in PyYAML | 7,255,885 | 22 | 2011-08-31T10:50:04Z | 27,103,244 | 20 | 2014-11-24T10:59:26Z | [
"python",
"yaml",
"pyyaml"
] | I have a yaml file that looks like this:
```
# The following key opens a door
key: value
```
Is there a way I can `load` and `dump` this data while maintaining the comment? | If you are using block structured YAML, you can use the python package¹ [ruamel.yaml](https://pypi.python.org/pypi/ruamel.yaml) which is a derivative of PyYAML and **supports round trip preservation of comments**:
```
import sys
import ruamel.yaml
yaml_str = """\
# example
name:
# details
family: Smith # very ... |
Differences in ctypes between Python 2 and 3 | 7,256,283 | 6 | 2011-08-31T11:28:09Z | 7,258,112 | 9 | 2011-08-31T14:04:16Z | [
"python",
"dll",
"numpy",
"python-3.x",
"ctypes"
] | I have a working python 2.7 program that calls a DLL. I am trying to port the script to python 3.2. The DLL call seems to work (i.e. there is no error upon calling) but the returned data does not make sense.
Just in case it could be useful:
- The call takes three arguments: two int (input) and a pointer to a ushort ar... | In Python 2.7, strings are byte-strings by default. In Python 3.x, they are unicode by default. Try explicitly making your string a byte string using `.encode('ascii')` before handing it to `DLL.prepare`.
**Edit:**
```
#another way of saying table=str(aNumber).encode('ascii')
table = bytes(str(aNumber), 'ascii')
DLL.... |
Adding REST behavior to a class with flask, case for blueprints? | 7,256,889 | 11 | 2011-08-31T12:27:28Z | 7,260,898 | 10 | 2011-08-31T17:23:18Z | [
"python",
"design-patterns",
"rest",
"amqp",
"flask"
] | I am dealing with a python application that consists of multiple distributed lightweight components that communicate using [RabbitMQ](http://www.rabbitmq.com/) & [Kombu](http://packages.python.org/kombu/).
A component listens on two queues and can receive multiple message types on each queue. Subclasses can override h... | Something else was quietly introduced in Flask 0.7 that might be of interest to you - [Pluggable Views](http://flask.pocoo.org/docs/views/). These are *class based* rather than function based endpoints - so you can use the [`dispatch_request`](http://flask.pocoo.org/docs/api/#flask.views.View.dispatch_request) method t... |
Why can't I use a list as a dict key in python? | 7,257,588 | 45 | 2011-08-31T13:28:03Z | 7,257,664 | 7 | 2011-08-31T13:32:58Z | [
"python",
"list",
"dictionary",
"tuples",
"hashable"
] | I'm a bit confused about what can/can't be used as a key for a python dict.
```
dicked = {}
dicked[None] = 'foo' # None ok
dicked[(1,3)] = 'baz' # tuple ok
import sys
dicked[sys] = 'bar' # wow, even a module is ok !
dicked[(1,[3])] = 'qux' # oops, not allowed
```
So a tuple is an immutable type but if I ... | The issue is that tuples are immutable, and lists are not. Consider the following
```
d = {}
li = [1,2,3]
d[li] = 5
li.append(4)
```
What should `d[li]` return? Is it the same list? How about `d[[1,2,3]]`? It has the same values, but is a different list?
Ultimately, there is no satisfactory answer. For example, if t... |
Why can't I use a list as a dict key in python? | 7,257,588 | 45 | 2011-08-31T13:28:03Z | 7,257,711 | 16 | 2011-08-31T13:36:23Z | [
"python",
"list",
"dictionary",
"tuples",
"hashable"
] | I'm a bit confused about what can/can't be used as a key for a python dict.
```
dicked = {}
dicked[None] = 'foo' # None ok
dicked[(1,3)] = 'baz' # tuple ok
import sys
dicked[sys] = 'bar' # wow, even a module is ok !
dicked[(1,[3])] = 'qux' # oops, not allowed
```
So a tuple is an immutable type but if I ... | There's a good article on the topic in the Python wiki: [Why Lists Can't Be Dictionary Keys](http://wiki.python.org/moin/DictionaryKeys). As explained there:
> What would go wrong if you tried to use lists as keys, with the hash as, say, their memory location?
It can be done without really breaking any of the require... |
Python strip() unicode string? | 7,258,411 | 2 | 2011-08-31T14:24:18Z | 7,258,480 | 7 | 2011-08-31T14:28:24Z | [
"python",
"string",
"unicode",
"strip"
] | How can you use string methods like strip() on a unicode string? and can't you access characters of a unicode string like with oridnary strings? (ex: mystring[0:4] ) | It's working as usual, as long as they are actually `unicode`, not `str` (note: every string literal *must* be preceded by `u`, like in this example):
```
>>> a = u"coÈofanÄ"
>>> a
u'co\u021bofan\u0103'
>>> a[-1]
u'\u0103'
>>> a[2]
u'\u021b'
>>> a[3]
u'o'
>>> a.strip(u'Ä')
u'co\u021bofan'
``` |
Manually calling a class based generic view | 7,258,912 | 12 | 2011-08-31T14:55:57Z | 7,260,361 | 22 | 2011-08-31T16:35:14Z | [
"python",
"django",
"django-generic-views"
] | I'm currently trying to call a class based Generic view from within another class based generic view and cant seem to do it correctly.
Ways I've tried:
```
result = CategoryTypes.as_view() # The same way you put it in the urlconf
print result
```
Prints: `<function CategoryTypes at 0x92bd924>`
```
CategoryTypes.as... | The first way -- `CategoryTypes.as_view()(self.request)` -- is right. The problem is that if your view returns a `TemplateResponse`, its `render` method isn't called automatically.
So if you need to access the content of the response, call `render()` on it first. |
Python's os.listdir behaviour on Windows | 7,258,993 | 5 | 2011-08-31T15:01:15Z | 7,259,040 | 16 | 2011-08-31T15:03:49Z | [
"python",
"windows",
"operating-system"
] | ```
>>> import os
>>> os.chdir('c:/python27')
>>> os.listdir('c:')
['Tools', 'include', 'python.exe', 'libs', 'DLLs', 'Lib', 'NEWS.txt',
'w9xpopen.exe', 'Doc', 'pythonw.exe', 'LICENSE.txt', 'README.txt', 'tcl']
>>> os.listdir('c:/')
['users', 'Program Files', 'Python27', 'windows']
```
Why is the "/" after "c:" affect... | I don't think this is specific to Python, it's a Windows question at heart.
In Windows `C:` and `C:\` (or, alternatively `C:/`) have quite different meanings:
* `C:` refers to the current directory on the drive `C:`
* `C:\` (and `C:/`) refers to the root directory of the drive `C:`
While UNIX-like operating systems ... |
How can I get methods to work as callbacks with python ctypes? | 7,259,794 | 10 | 2011-08-31T15:54:13Z | 7,261,524 | 7 | 2011-08-31T18:18:04Z | [
"python",
"ctypes"
] | I have an C api that i'm interfacing with the python ctypes package. Everything works well, except this little tidbit.
To register functions as callbacks to some notifications, i call this function :
```
void RegisterNotifyCallback( int loginId, int extraFlags, void *(*callbackFunc)(Notification *))
```
so in python... | You can't, so far as I know, call a bound method because it is missing the self parameter. I solve this problem using a closure, like this:
```
CALLBACK = ctypes.CFUNCTYPE(None, ctypes.POINTER(Notification))
class MyClass(object):
def getCallbackFunc(self):
def func(Notification):
self.doSome... |
Django substr / substring in templates | 7,260,399 | 14 | 2011-08-31T16:38:08Z | 7,260,472 | 21 | 2011-08-31T16:44:41Z | [
"python",
"django",
"templates",
"substr"
] | Could someone tell me, does the method like substr in PHP (<http://pl2.php.net/manual/en/function.substr.php>) exist in Django templates? | You can use the [`slice` filter](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#slice), though I don't think there's an equivalent to the `$length` argument. |
How to create a Mac OS X app with Python? | 7,261,795 | 29 | 2011-08-31T18:39:33Z | 14,926,118 | 7 | 2013-02-17T21:14:07Z | [
"python",
"wxpython",
"osx",
"py2app"
] | I want to create a GUI application which should work on Windows and Mac. For this I've chosen Python.
The problem is on Mac OS X.
**There are 2 tools to generate an ".app" for Mac: py2app and pyinstaller.**
1. py2app is pretty good, but it adds the source code in the package. I
don't want to share the code with t... | > How to configure py2app to include the source code in the executable,
> so the final users will not have access to my program?
Unless you very seriously hack the python interpreter (and include the mangled version) there is no really good way to hide the source from a moderately skilled and determined user. I strong... |
Convert an excel or spreadsheet column letter to its number in Pythonic fashion | 7,261,936 | 5 | 2011-08-31T18:51:42Z | 12,640,614 | 13 | 2012-09-28T13:05:10Z | [
"python",
"excel",
"google-spreadsheet",
"python-2.x"
] | Is there a more pythonic way of converting excel-style columns to numbers (starting with 1)?
Working code up to two letters:
```
def column_to_number(c):
"""Return number corresponding to excel-style column."""
number=-25
for l in c:
if not l in string.ascii_letters:
return False
... | There is a way to make it more pythonic (works with three or more letters and uses less magic numbers):
```
def col2num(col):
num = 0
for c in col:
if c in string.ascii_letters:
num = num * 26 + (ord(c.upper()) - ord('A')) + 1
return num
```
And as a one-liner using reduce (does not ch... |
python : how to convert string literal to raw string literal? | 7,262,828 | 17 | 2011-08-31T20:12:30Z | 7,262,918 | 20 | 2011-08-31T20:23:22Z | [
"python",
"string",
"text"
] | I read in a string from a GUI textbox entered by the user and process it through [pandoc](http://johnmacfarlane.net/pandoc/). The string contains latex directives for math which have backslash characters. I want to send in the string as a raw string to pandoc for processing. But something like '\theta' becomes a tab an... | Pythonâs raw strings are just a way to tell the Python interpreter that it should interpret backslashes as literal slashes. If you read strings entered by the user, they are already past the point where they could have been raw. Also, user input is most likely read in literally, i.e. ârawâ.
This means the interp... |
Try/except for specific error of type Exception | 7,263,701 | 3 | 2011-08-31T21:32:19Z | 7,263,737 | 9 | 2011-08-31T21:35:21Z | [
"python",
"try-catch"
] | I have a certain function which does the following in certain cases:
raise Exception, 'someError'
and may raise other exceptions in other cases.
I want to treat differently the cases when the function raises Exception, 'someError' and the cases where the function raises other exceptions.
For example, I tried the fo... | You can look at the message property of the exception
```
>>> try:
... raise Exception, 'someError'
... except Exception as e:
... if e.message == 'someError':
... print 'first case'
... else:
... print 'second case'
...
first case
```
but it's pretty hacky. It'd be better to just... |
Get HTML Source of WebElement in Selenium WebDriver using Python | 7,263,824 | 173 | 2011-08-31T21:44:11Z | 7,290,968 | 61 | 2011-09-03T03:29:14Z | [
"python",
"selenium",
"selenium-webdriver",
"webdriver"
] | I'm using the Python bindings to run Selenium WebDriver.
```
from selenium import webdriver
wd = webdriver.Firefox()
```
I know I can grab a webelement like so...
```
elem = wd.find_element_by_css_selector('#my-id')
```
And I know I can get the full page source with...
```
wd.page_source
```
But is there anyway t... | There is not really a straight-forward way of getting the html source code of a webelement. You will have to use JS. I am not too sure about python bindings but you can easily do like this in Java. I am sure there must be something similar to `JavascriptExecutor` class in Python.
```
WebElement element = driver.findE... |
Get HTML Source of WebElement in Selenium WebDriver using Python | 7,263,824 | 173 | 2011-08-31T21:44:11Z | 8,575,709 | 269 | 2011-12-20T12:49:48Z | [
"python",
"selenium",
"selenium-webdriver",
"webdriver"
] | I'm using the Python bindings to run Selenium WebDriver.
```
from selenium import webdriver
wd = webdriver.Firefox()
```
I know I can grab a webelement like so...
```
elem = wd.find_element_by_css_selector('#my-id')
```
And I know I can get the full page source with...
```
wd.page_source
```
But is there anyway t... | You can read `innerHTML` attribute to get source of the *content* of the element or `outerHTML` for source *with* the current element.
Python:
```
element.get_attribute('innerHTML')
```
Java:
```
elem.getAttribute("innerHTML");
```
C#:
```
element.GetAttribute("innerHTML");
```
Ruby:
```
element.attribute("inne... |
Get HTML Source of WebElement in Selenium WebDriver using Python | 7,263,824 | 173 | 2011-08-31T21:44:11Z | 15,531,471 | 35 | 2013-03-20T18:08:52Z | [
"python",
"selenium",
"selenium-webdriver",
"webdriver"
] | I'm using the Python bindings to run Selenium WebDriver.
```
from selenium import webdriver
wd = webdriver.Firefox()
```
I know I can grab a webelement like so...
```
elem = wd.find_element_by_css_selector('#my-id')
```
And I know I can get the full page source with...
```
wd.page_source
```
But is there anyway t... | Sure we can get all HTML source code with this script below in Selenium Python:
```
elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")
```
If you you want to save it to file:
```
f = open('c:/html_source_code.html', 'w')
f.write(source_code.encode('utf-8'))
f.close()
```
I sugg... |
Syntax error iterating over tuple in python | 7,264,073 | 3 | 2011-08-31T22:07:54Z | 7,264,090 | 32 | 2011-08-31T22:09:12Z | [
"python",
"tuples",
"python-2.7"
] | I am new to Python and am unsure of the best way to iterate over a tuple.
The syntax
```
for i in tuple
print i
```
causes an error. Any help will be much appreciated! I am a ruby programmer new to python. | That is an error because the syntax is invalid, add a colon:
```
for i in tup:
print i
```
Also, you should not use `tuple` as the name for a variable, as it is the name of a [built-in function](http://docs.python.org/library/functions.html#tuple). |
Convert int to ascii [chr()] in django template | 7,264,634 | 2 | 2011-08-31T23:30:07Z | 7,264,766 | 7 | 2011-08-31T23:48:43Z | [
"python",
"django",
"django-templates",
"ascii",
"chr"
] | I am writing a django application, and in a loop,
```
{% for item in list %}
{{ forloop.counter0 }}
{% endfor %}
```
this will printout the number in the loop starting from 0. But I want to printout alphabet starting from 'A', so the python way to do it is chr(forloop.counter0+65), but this is inside the ... | You can write a simple [custom template tag](https://docs.djangoproject.com/en/dev/howto/custom-template-tags/), for example a filter:
```
@register.filter(name='chr')
def chr_(value):
return chr(value + 65)
```
Then load it in your template and you can do:
```
{{ forloop.counter0|chr }}
``` |
Coffeescript equivalent to Python's getattr | 7,264,676 | 3 | 2011-08-31T23:36:11Z | 7,264,933 | 11 | 2011-09-01T00:19:14Z | [
"javascript",
"python",
"coffeescript"
] | In python I can put a function into a variable at runtime, then call it using the getattr function
```
method = getattr(self,self.name)
method()
```
Is there a similar way to do this in Coffeescript?
Thanks!
---
Using zeekay suggestion but using classes would be:
```
class Test
foo: -> alert 'foo'
foo2: meth... | In Javascript objects are associative arrays, and you can access property/methods using the name of the property as the key:
```
obj =
method: -> 'xxx'
method = obj['method']
method() # 'xxx'
```
Your updated example doesn't work because `foo2` is merely returning `foo`. You might want to try this:
```
class Test
... |
range() for floats | 7,267,226 | 55 | 2011-09-01T07:30:04Z | 7,267,280 | 59 | 2011-09-01T07:36:01Z | [
"python",
"range",
"fractions",
"decimal"
] | Is there a `range()` equivalent for floats in Python?
```
>>> range(0.5,5,1.5)
[0, 1, 2, 3, 4]
>>> range(0.5,5,0.5)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
range(0.5,5,0.5)
ValueError: range() step argument must not be zero
``` | I don't know a built-in function, but writing one like [this](http://stackoverflow.com/a/477610/623735) shouldn't be too complicated.
```
def frange(x, y, jump):
while x < y:
yield x
x += jump
```
---
As the comments mention, this could produce unpredictable results like:
```
>>> list(frange(0, 100, 0.1))... |
range() for floats | 7,267,226 | 55 | 2011-09-01T07:30:04Z | 7,267,287 | 50 | 2011-09-01T07:36:25Z | [
"python",
"range",
"fractions",
"decimal"
] | Is there a `range()` equivalent for floats in Python?
```
>>> range(0.5,5,1.5)
[0, 1, 2, 3, 4]
>>> range(0.5,5,0.5)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
range(0.5,5,0.5)
ValueError: range() step argument must not be zero
``` | You can either use:
```
[x / 10.0 for x in range(5, 50, 15)]
```
or use lambda / map:
```
map(lambda x: x/10.0, range(5, 50, 15))
```
or `arange` from NumPy:
```
>>> from numpy import arange
>>> arange(0.5, 5, 1.5)
array([0.5, 2.0, 3.5])
```
**EDIT**:
Disclaimer: using `arange` leads to floating point errors, nu... |
range() for floats | 7,267,226 | 55 | 2011-09-01T07:30:04Z | 7,267,806 | 23 | 2011-09-01T08:30:55Z | [
"python",
"range",
"fractions",
"decimal"
] | Is there a `range()` equivalent for floats in Python?
```
>>> range(0.5,5,1.5)
[0, 1, 2, 3, 4]
>>> range(0.5,5,0.5)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
range(0.5,5,0.5)
ValueError: range() step argument must not be zero
``` | I used to use `numpy.arange` but had some complications controlling the number of elements it returns, due to floating point errors. So now I use `linspace`, e.g.:
```
>>> import numpy
>>> numpy.linspace(0, 10, num=4)
array([ 0. , 3.33333333, 6.66666667, 10. ])
``` |
range() for floats | 7,267,226 | 55 | 2011-09-01T07:30:04Z | 14,653,331 | 15 | 2013-02-01T19:07:07Z | [
"python",
"range",
"fractions",
"decimal"
] | Is there a `range()` equivalent for floats in Python?
```
>>> range(0.5,5,1.5)
[0, 1, 2, 3, 4]
>>> range(0.5,5,0.5)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
range(0.5,5,0.5)
ValueError: range() step argument must not be zero
``` | Pylab has `frange` (a wrapper, actually, for `matplotlib.mlab.frange`):
```
>>> import pylab as pl
>>> pl.frange(0.5,5,0.5)
array([ 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ])
``` |
(Python) What is the proper nomenclature for this so I can search for and learn about it? | 7,267,687 | 2 | 2011-09-01T08:20:19Z | 7,267,749 | 8 | 2011-09-01T08:25:36Z | [
"python",
"class",
"parameters",
"python-2.x"
] | Sorry for the poor title. I really have no idea how to describe this to a search engine to find out how it works.
```
class MyClass(object):
def __init__(self, contents=None):
self.contents = contents
```
Specifically, the `contents=None` parameter.
I've been studying Python for about 2 months now, and t... | That's a [Default Argument Value](http://docs.python.org/tutorial/controlflow.html#default-argument-values) for a [Keyword Argument](http://docs.python.org/tutorial/controlflow.html#keyword-arguments).
They're pretty straightforward, as long as they're not a [mutable object](http://stackoverflow.com/questions/1132941/... |
Is the Global Request variable in Python/Django available? | 7,267,977 | 6 | 2011-09-01T08:46:18Z | 7,270,133 | 9 | 2011-09-01T12:16:38Z | [
"python",
"django"
] | I have written a plugin that sends a signal to activate my code. However, it doesn't send the user-request object to my code. I am looking for a way to retrieve the current request without modifying the main application. I cannot find any documentation related to global request (like `$_SERVER['REMOTE_ADDR']` in PHP).
... | Django doesn't provide a global request object (it would actually be a thread local, not a global). But there are a few techniques you can use to get the same effect yourself: <http://nedbatchelder.com/blog/201008/global_django_requests.html> |
Python, MySQL and SELECT output to dictionary with column names for keys | 7,268,178 | 2 | 2011-09-01T09:04:41Z | 7,268,211 | 14 | 2011-09-01T09:08:40Z | [
"python",
"mysql",
"dictionary"
] | I have a MySQL table on which I'm executing SELECT statements within Python.
Is there anything out of the Python MySQLdb API that will, via the cursor, output an array of dictionaries whose keys are the column names (and values are those in the returned rows)? | Please use dictionary cursor:
```
cursor = conn.cursor (MySQLdb.cursors.DictCursor)
``` |
(Python) Issues with directories that have special characters | 7,268,618 | 6 | 2011-09-01T09:45:11Z | 7,268,662 | 8 | 2011-09-01T09:50:14Z | [
"python",
"windows",
"directory"
] | * OS: Windows server 03
* Python ver: 2.7
For the code below, its runs fine when I substitute "fuchida@domain.com" with "fuchida". If I use the email format for directory name I get the following error "**WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:**" . Please let me kn... | I suspect problems with your `\` as escape characters. Try this:
```
import os
def dirListing():
dirList = os.listdir(r"C:\\Program Files\home\Server\Logs\fuchida@domain.com")
for fname in dirList:
print fname
return
def main():
dirListing()
if __name__ == '__main__':main()
``` |
Python, mechanize - problem with finding form by name | 7,268,886 | 3 | 2011-09-01T10:12:38Z | 7,269,248 | 7 | 2011-09-01T10:49:23Z | [
"python",
"forms",
"mechanize"
] | ```
import urllib
import cookielib
import mechanize
url = "http://hattrick.org/World/Transfers/"
cookie = cookielib.CookieJar()
browser = mechanize.Browser()
browser.set_cookiejar(cookie)
browser.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
browser.open(url)
browser.select_form(name="aspne... | You can check what forms are available by using the browser.forms() iterator.
To find out what forms are available in a Python interpreter, just do:
```
>>> print [form for form in browser.forms()][0]
``` |
Finding the index of elements based on a condition using python list comprehension | 7,270,321 | 32 | 2011-09-01T12:31:59Z | 7,270,355 | 14 | 2011-09-01T12:35:27Z | [
"python"
] | The following Python code appears to be very long winded when coming from a Matlab background
```
>>> a = [1, 2, 3, 1, 2, 3]
>>> [index for index,value in enumerate(a) if value > 2]
[2, 5]
```
When in Matlab I can write:
```
>> a = [1, 2, 3, 1, 2, 3];
>> find(a>2)
ans =
3 6
```
Is there a short hand method... | Another way:
```
>>> [i for i in range(len(a)) if a[i] > 2]
[2, 5]
```
In general, remember that **while `find` is a ready-cooked function, list comprehensions are a general, and thus very powerful solution**. Nothing prevents you from writing a `find` function in Python and use it later as you wish. I.e.:
```
>>> d... |
Finding the index of elements based on a condition using python list comprehension | 7,270,321 | 32 | 2011-09-01T12:31:59Z | 7,270,932 | 27 | 2011-09-01T13:20:16Z | [
"python"
] | The following Python code appears to be very long winded when coming from a Matlab background
```
>>> a = [1, 2, 3, 1, 2, 3]
>>> [index for index,value in enumerate(a) if value > 2]
[2, 5]
```
When in Matlab I can write:
```
>> a = [1, 2, 3, 1, 2, 3];
>> find(a>2)
ans =
3 6
```
Is there a short hand method... | * In Python, you wouldn't use indexes for this at all, but just deal with the valuesâ`[value for value in a if value > 2]`. Usually dealing with indexes means you're not doing something the best way.
* If you *do* need an API similar to Matlab's, you would use [numpy](http://numpy.scipy.org/), a package for multidime... |
How to reload a module's function in Python? | 7,271,082 | 10 | 2011-09-01T13:34:03Z | 7,271,215 | 7 | 2011-09-01T13:43:46Z | [
"python",
"methods",
"import",
"reload"
] | Following up on [this question regarding reloading a module](http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module), how do I reload a specific function from a changed module?
pseudo-code:
```
from foo import bar
if foo.py has changed:
reload bar
``` | Hot reloading is not something you can do in Python reliably without blowing up your head. You literally cannot support reloading without writing code special ways, and trying to write and maintain code that supports reloading with any sanity requires extreme discipline and is too confusing to be worth the effort. Test... |
Python clean way to wrap individual statements in a try except block | 7,271,245 | 7 | 2011-09-01T13:45:49Z | 7,271,328 | 9 | 2011-09-01T13:52:31Z | [
"python",
"excel",
"vba",
"com",
"try-catch"
] | I'm currently doing some Python automation of Excel with com. It's fully functional, and does what I want, but I've discovered something surprising. Sometimes, some of the Excel commands I use will fail with an exception for no apparent reason. Other times, they will work.
In the VB equivalent code for what I'm doing,... | Exceptions never happen "for no apparent reason". There is always a reason and that reason needs to be fixed. Otherwise, your program will start to produce "random" data where "random" is at the mercy of the bug that you're hiding.
But of course, you need a solution for your problem. Here is my suggestion:
1. Create ... |
Python clean way to wrap individual statements in a try except block | 7,271,245 | 7 | 2011-09-01T13:45:49Z | 7,271,877 | 10 | 2011-09-01T14:34:03Z | [
"python",
"excel",
"vba",
"com",
"try-catch"
] | I'm currently doing some Python automation of Excel with com. It's fully functional, and does what I want, but I've discovered something surprising. Sometimes, some of the Excel commands I use will fail with an exception for no apparent reason. Other times, they will work.
In the VB equivalent code for what I'm doing,... | Consider abstracting away the suppression. And to Aaron's point, do not swallow exceptions generally.
```
class Suppressor:
def __init__(self, exception_type):
self._exception_type = exception_type
def __call__(self, expression):
try:
exec expression
except self._exception_... |
Introspect calling object | 7,272,326 | 6 | 2011-09-01T15:06:53Z | 7,272,464 | 14 | 2011-09-01T15:17:05Z | [
"python",
"introspection"
] | How do I introspect `A`'s instance from within `b.func()` (i.e. `A`'s instance's *`self`*):
```
class A():
def go(self):
b=B()
b.func()
class B():
def func(self):
# Introspect to find the calling A instance here
``` | In general we don't want that `func` to have access back to the calling instance of `A` because this breaks [encapsulation](http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29). Inside of `b.func` you should have access to any args and kwargs passed, the state/attributes of the instance `b` (vi... |
python string replace is deleting whitespace incorrectly | 7,272,758 | 3 | 2011-09-01T15:38:19Z | 7,272,892 | 10 | 2011-09-01T15:48:06Z | [
"python",
"string",
"replace",
"whitespace"
] | I have a method
```
def strip_searchname(self, original_name):
taboo = {" and ", " of ", " at ", " in ", ":", "-", ",", " the ", " "}
searchname = original_name
for word in taboo:
print(searchname)
searchname = searchname.replace(word, "")
searchname = re.sub('[^a-zA-Z]', "", searchname... | > What I DON'T understand is why it seems to be executing the " "
> replace BEFORE the " of " replace, for example, when the " of "
> replace comes before the space in the list.
It's not a list.
```
taboo = {" and ", " of ", " at ", " in ", ":", "-", ",", " the ", " "}
```
is a set literal. Try replacing { and } by ... |
How to map a function to a triple nested list and keep the triple nested list intact? | 7,273,164 | 2 | 2011-09-01T16:11:56Z | 7,273,261 | 11 | 2011-09-01T16:19:27Z | [
"list",
"nested",
"python"
] | I've have been building an analysis workflow for my PhD and have been using a triple nested list to represent my data structure because I want it to be able to expand to an arbitrary amount of data in its second and third levels. The first level is the whole dataset, the second level is each subject in the dataset and ... | Rather than doing it in place, make a new list
```
dataset = [[[float(value) for value in measure]
for measure in subject]
for subject in dataset]
``` |
python read-only class properties | 7,273,293 | 6 | 2011-09-01T16:22:19Z | 7,273,347 | 10 | 2011-09-01T16:26:22Z | [
"python",
"properties"
] | Is there a way to make read-only class properties in Python? Ex. in Unity3d you can do this:
```
transform.position = Vector3.zero
```
Vector3.zero returns an instance of the Vector3 class where x, y, and z are 0. This is basically the same as:
```
transform.position = Vector3(0, 0, 0)
```
I've tried doing somethin... | The most obvious way might be to alter the class object after the fact:
```
class Vector3(object):
# ...
Vector3.zero = Vector3(0, 0, 0)
```
The main problem with this is that there's then only one zero object, and if it's mutable you can cause accidental damage all over the place. It may be easier (and feel less... |
python read-only class properties | 7,273,293 | 6 | 2011-09-01T16:22:19Z | 7,273,483 | 9 | 2011-09-01T16:38:33Z | [
"python",
"properties"
] | Is there a way to make read-only class properties in Python? Ex. in Unity3d you can do this:
```
transform.position = Vector3.zero
```
Vector3.zero returns an instance of the Vector3 class where x, y, and z are 0. This is basically the same as:
```
transform.position = Vector3(0, 0, 0)
```
I've tried doing somethin... | Use a metaclass
```
class MetaVector3(type):
@property
def zero(cls):
return cls(0,0,0)
class Vector3(object):
__metaclass__ = MetaVector3
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
>>> v = Vector3.zero
>>> v.x, v.y, v.z
(0, 0, 0)
``` |
Behavior of Python's time.sleep(0) under linux - Does it cause a context switch? | 7,273,474 | 20 | 2011-09-01T16:38:05Z | 7,273,727 | 19 | 2011-09-01T16:56:55Z | [
"python",
"multithreading"
] | This pattern comes up a lot but I can't find a straight answer.
An non-critical, un-friendly program might do
```
while(True):
# do some work
```
Using other technologies and platforms, if you want to allow this program to run hot (use as much CPU cycles as possible) but be polite - allow other programs who are ... | I'd never thought about this, so I wrote this script:
```
import time
while True:
print "loop"
time.sleep(0.5)
```
Just as a test. Running this with `strace -o isacontextswitch.strace -s512 python test.py` gives you this output on the loop:
```
write(1, "loop\n", 5) = 5
select(0, NULL, NUL... |
Behavior of Python's time.sleep(0) under linux - Does it cause a context switch? | 7,273,474 | 20 | 2011-09-01T16:38:05Z | 7,274,203 | 8 | 2011-09-01T17:38:48Z | [
"python",
"multithreading"
] | This pattern comes up a lot but I can't find a straight answer.
An non-critical, un-friendly program might do
```
while(True):
# do some work
```
Using other technologies and platforms, if you want to allow this program to run hot (use as much CPU cycles as possible) but be polite - allow other programs who are ... | I think you have already the answer from @Ninefingers, but in this answer we will try to dive into python source code.
First the python `time` module is implemented in C and to see the `time.sleep` function implementation you can take a look at [Modules/timemodule.c](http://hg.python.org/cpython/file/4d584ebbfa77/Modu... |
Behavior of Python's time.sleep(0) under linux - Does it cause a context switch? | 7,273,474 | 20 | 2011-09-01T16:38:05Z | 7,275,029 | 7 | 2011-09-01T18:53:12Z | [
"python",
"multithreading"
] | This pattern comes up a lot but I can't find a straight answer.
An non-critical, un-friendly program might do
```
while(True):
# do some work
```
Using other technologies and platforms, if you want to allow this program to run hot (use as much CPU cycles as possible) but be polite - allow other programs who are ... | You are basically attempting to usurp the job of the OS CPU scheduler. It would likely be much better to simply call `os.nice(100)` to inform the scheduler that you're very low priority so it can do its job properly. |
Testing for reference equality in Python | 7,274,097 | 17 | 2011-09-01T17:29:10Z | 7,274,122 | 29 | 2011-09-01T17:31:00Z | [
"python",
"reference",
"equality"
] | Say I have a class in Python that has an eq method defined for comparing attributes for equality:
```
class Foo(object):
# init code...
def __eq__(self, other):
# usual eq code here....
```
How can I then compare two instances of Foo for reference equality (that is test if they are the same instance)... | Thats the `is` operator
```
print f1 is f2
``` |
How to request pages from website that uses OpenID? | 7,274,141 | 16 | 2011-09-01T17:32:16Z | 8,445,371 | 11 | 2011-12-09T12:17:09Z | [
"python",
"authentication",
"openid",
"urllib2"
] | *[This question has been asked here before](http://stackoverflow.com/questions/6330335/python-how-to-request-pages-from-website-that-uses-openid). The accepted answer was probably obvious to both questioner and answerer---but not to me. I have commented on the above question to get more precisions, but there was no res... | Well I myself don't know much about OpenID but your post (and the bounty!!) got me interested.
[This link](http://blogs.oracle.com/bblfish/entry/the_openid_sequence_diagram) tells the exact flow of OpenID authentication sequence (Atleast for v1.0. The new version is 2.0). From what I could make out, the steps would be... |
Changing image hue with Python PIL | 7,274,221 | 16 | 2011-09-01T17:40:30Z | 7,274,986 | 9 | 2011-09-01T18:48:48Z | [
"python",
"image",
"python-imaging-library",
"hue"
] | Using Python PIL, I'm trying to adjust the hue of a given image.
I'm not very comfortable with the jargon of graphics, so what I mean by âadjusting hueâ is doing the Photoshop operation called [âHue/saturationâ](http://www.guidebookgallery.org/pics/apps/photoshop/usage/colours/huesaturation/900.png): this is t... | There is Python code to convert RGB to HSV (and vice versa) in the [colorsys module in the standard library](http://svn.python.org/view/python/trunk/Lib/colorsys.py?view=markup). My first attempt used
```
rgb_to_hsv=np.vectorize(colorsys.rgb_to_hsv)
hsv_to_rgb=np.vectorize(colorsys.hsv_to_rgb)
```
to vectorize those ... |
Python using exceptions for control flow considered bad? | 7,274,310 | 9 | 2011-09-01T17:47:42Z | 7,274,420 | 10 | 2011-09-01T17:56:56Z | [
"python",
"try-catch",
"generator"
] | All right,
I've seen this multiple times in the past, but most recently with [my question here](http://stackoverflow.com/questions/7271245/python-clean-way-to-wrap-individual-statements-in-a-try-except-block). So, I'm curious why this is the case, *in python* because generators use exceptions to indicate the end of th... | Because ending the generator is not a common event (I know it will always happen, but it only happens *once*). Throwing the exception is considered expensive. If an event is going to succeed 99% of the time and fail 1%, using try/except can be much faster than checking if it's okay to access that data (it's easier to a... |
Why do Python unicode strings require special treatment for UTF-8 BOM? | 7,274,478 | 14 | 2011-09-01T18:02:10Z | 7,274,594 | 26 | 2011-09-01T18:13:38Z | [
"python",
"unicode",
"utf-8",
"io",
"character-encoding"
] | For some reason, Python seems to be having issues with **BOM** when reading unicode strings from a **UTF-8** file. Consider the following:
```
with open('test.py') as f:
for line in f:
print unicode(line, 'utf-8')
```
Seems straightforward, doesn't it?
That's what I thought until I ran it from command line ... | The `'utf-8-sig'` encoding will consume the BOM signature on your behalf. |
Why do Python unicode strings require special treatment for UTF-8 BOM? | 7,274,478 | 14 | 2011-09-01T18:02:10Z | 7,274,750 | 13 | 2011-09-01T18:27:47Z | [
"python",
"unicode",
"utf-8",
"io",
"character-encoding"
] | For some reason, Python seems to be having issues with **BOM** when reading unicode strings from a **UTF-8** file. Consider the following:
```
with open('test.py') as f:
for line in f:
print unicode(line, 'utf-8')
```
Seems straightforward, doesn't it?
That's what I thought until I ran it from command line ... | You wrote:
> ```
> UnicodeEncodeError: 'charmap' codec can't encode character u'\ufeff' in position 0: character maps to <undefined>
> ```
When you specify the `"utf-8"` encoding in Python, it takes you at your word. UTF-8 files *arenât supposed* to contain a BOM in them. They are neither required nor recommended.... |
How do I write a setup.py for a twistd/twisted plugin that works with setuptools, distribute, etc? | 7,275,295 | 26 | 2011-09-01T19:14:25Z | 7,525,163 | 16 | 2011-09-23T06:34:42Z | [
"python",
"twisted",
"setuptools",
"distutils",
"distribute"
] | The [Twisted Plugin System](http://twistedmatrix.com/documents/current/core/howto/plugin.html) is the preferred way to write extensible twisted applications.
However, due to the way the plugin system is structured (plugins go into a twisted/plugins directory which should *not* be a Python package), writing a proper se... | By preventing pip from writing the line "`twisted`" to `.egg-info/top_level.txt`, you can keep using `packages=[..., 'twisted.plugins']` and have a working `pip uninstall` that doesn't remove all of `twisted/`. This involves monkeypatching setuptools/distribute near the top of your `setup.py`. Here is a sample `setup.p... |
Are there dictionary comprehensions in Python? (Problem with function returning dict) | 7,276,511 | 18 | 2011-09-01T21:03:40Z | 7,276,556 | 26 | 2011-09-01T21:07:34Z | [
"python",
"dictionary",
"python-2.x"
] | I know about list comprehensions, what about dictionary comprehensions?
Expected Output:
```
>>> countChar('google')
{'e': 1, 'g': 2, 'l': 1, 'o': 2}
>>> countLetters('apple')
{'a': 1, 'e': 1, 'l': 1, 'p': 2}
>>> countLetters('')
{}
```
Code (I'm a beginner):
```
def countChar(word):
l = []
... | **edit**: As agf pointed out in comments and the other answer, there is a dictionary comprehension for Python 2.7 or newer.
```
def countChar(word):
return dict((item, word.count(item)) for item in set(word))
>>> countChar('google')
{'e': 1, 'g': 2, 'o': 2, 'l': 1}
>>> countChar('apple')
{'a': 1, 'p': 2, 'e': 1, ... |
Are there dictionary comprehensions in Python? (Problem with function returning dict) | 7,276,511 | 18 | 2011-09-01T21:03:40Z | 7,276,625 | 55 | 2011-09-01T21:14:59Z | [
"python",
"dictionary",
"python-2.x"
] | I know about list comprehensions, what about dictionary comprehensions?
Expected Output:
```
>>> countChar('google')
{'e': 1, 'g': 2, 'l': 1, 'o': 2}
>>> countLetters('apple')
{'a': 1, 'e': 1, 'l': 1, 'p': 2}
>>> countLetters('')
{}
```
Code (I'm a beginner):
```
def countChar(word):
l = []
... | If you're on Python 2.7 or newer:
```
{item: word.count(item) for item in set(word)}
```
works fine. You don't need to sort the list before you set it. You also don't need to turn the word into a list. Also, you're on a new enough Python to use `collections.Counter(word)` instead.
If you're on an older version of Py... |
smartest way to join two lists into a formatted string | 7,277,072 | 5 | 2011-09-01T22:02:43Z | 7,277,102 | 20 | 2011-09-01T22:06:29Z | [
"python",
"list",
"join",
"format"
] | Lets say I have two lists of same length:
```
a = ['a1', 'a2', 'a3']
b = ['b1', 'b2', 'b3']
```
and I want to produce the following string:
```
c = 'a1=b1, a2=b2, a3=b3'
```
What is the best way to achieve this?
I have following implementations:
```
import timeit
a = [str(f) for f in range(500)]
b = [str(f) for ... | This implementation is, on my system, faster than either of your two functions and still more compact.
```
c = ', '.join('%s=%s' % t for t in zip(a, b))
```
Thanks to @JBernardo for the suggested improvement.
In more recent syntax, `str.format` is more appropriate:
```
c = ', '.join('{}={}'.format(*t) for t in zip(... |
smartest way to join two lists into a formatted string | 7,277,072 | 5 | 2011-09-01T22:02:43Z | 7,277,115 | 7 | 2011-09-01T22:08:05Z | [
"python",
"list",
"join",
"format"
] | Lets say I have two lists of same length:
```
a = ['a1', 'a2', 'a3']
b = ['b1', 'b2', 'b3']
```
and I want to produce the following string:
```
c = 'a1=b1, a2=b2, a3=b3'
```
What is the best way to achieve this?
I have following implementations:
```
import timeit
a = [str(f) for f in range(500)]
b = [str(f) for ... | Those two solutions do *very* different things. The first loops in a *nested* way, then computes indexes with `list.index`, effectively making this a doubly-nested for loop and requiring what you could think of as 125,000,000 operations. The second iterates in lockstep, making 500 pairs without doing 250000 operations.... |
smartest way to join two lists into a formatted string | 7,277,072 | 5 | 2011-09-01T22:02:43Z | 19,202,870 | 7 | 2013-10-05T21:21:35Z | [
"python",
"list",
"join",
"format"
] | Lets say I have two lists of same length:
```
a = ['a1', 'a2', 'a3']
b = ['b1', 'b2', 'b3']
```
and I want to produce the following string:
```
c = 'a1=b1, a2=b2, a3=b3'
```
What is the best way to achieve this?
I have following implementations:
```
import timeit
a = [str(f) for f in range(500)]
b = [str(f) for ... | ```
a = ['a1', 'a2', 'a3']
b = ['b1', 'b2', 'b3']
pat = '%s=%%s, %s=%%s, %s=%%s'
print pat % tuple(a) % tuple(b)
```
gives `a1=b1, a2=b2, a3=b3`
.
Then:
```
from timeit import Timer
from itertools import izip
n = 300
a = [str(f) for f in range(n)]
b = [str(f) for f in range(n)]
def func1():
return ', '.joi... |
Python equivalent to echo -e? | 7,277,225 | 3 | 2011-09-01T22:18:22Z | 7,277,306 | 10 | 2011-09-01T22:26:16Z | [
"python"
] | Is there a python equivalent to `echo -e`?
In other words, is there a built-in function to convert `r"\x50\x79\x74\x68\x6f\x6e"` to `"Python"` in Python?
*Edit*
I added the 'r' prefix, to make sure everyone understands that I do not want the python interpreter to convert this. Rather, I want to convert that 24-charac... | The correct way to do this, which I just found is
```
>>> a = r"\x50\x79\x74\x68\x6f\x6e"
>>> print a
\x50\x79\x74\x68\x6f\x6e
>>> a.decode('string_escape')
'Python'
```
Make sure you are escaping the backslashes (or using the raw 'r' prefix) when testing this!
References:
* <http://docs.python.org/library/stdtypes... |
bit-wise operation unary ~ (invert) | 7,278,779 | 23 | 2011-09-02T02:44:23Z | 7,278,791 | 28 | 2011-09-02T02:46:31Z | [
"python",
"bit-manipulation"
] | I'm a little confused by the `~` operator. Code goes below:
```
a = 1
~a #-2
b = 15
~b #-16
```
How does `~` do work?
I thought, `~a` would be something like:
```
0001 = a
1110 = ~a
```
why not? | You are exactly right. It's an artifact of [two's complement](http://en.wikipedia.org/wiki/Two%27s_complement) integer representation.
In 16 bits, 1 is represented as `0000 0000 0000 0001`. Inverted, you get `1111 1111 1111 1110`, which is -2. Similarly, 15 is `0000 0000 0000 1111`. Inverted, you get `1111 1111 1111 0... |
bit-wise operation unary ~ (invert) | 7,278,779 | 23 | 2011-09-02T02:44:23Z | 12,790,495 | 14 | 2012-10-08T22:41:52Z | [
"python",
"bit-manipulation"
] | I'm a little confused by the `~` operator. Code goes below:
```
a = 1
~a #-2
b = 15
~b #-16
```
How does `~` do work?
I thought, `~a` would be something like:
```
0001 = a
1110 = ~a
```
why not? | The '~' operator is defined as:
"The bit-wise inversion of x is defined as -(x+1). It only applies to integral numbers."[Python Doc - 5.5](http://docs.python.org/reference/expressions.html#unary-arithmetic-and-bitwise-operations)
The important part of this sentence is that this is related to 'integral numbers' (also c... |
What does a . in an import statement in Python mean? | 7,279,810 | 34 | 2011-09-02T06:12:36Z | 7,279,834 | 27 | 2011-09-02T06:17:01Z | [
"python",
"module"
] | I'm looking over the code for Python's `multiprocessing` module, and it contains this line:
```
from ._multiprocessing import win32, Connection, PipeConnection
```
instead of
```
from _multiprocessing import win32, Connection, PipeConnection
```
the subtle difference being the period before `_multiprocessing`. What... | That's the new syntax for explicit [relative imports](http://www.python.org/dev/peps/pep-0328/). It means import from the current package. |
Is it possible, in python, to update or initialize a dictionary key with a single command? | 7,280,644 | 3 | 2011-09-02T07:57:39Z | 7,280,661 | 13 | 2011-09-02T07:59:36Z | [
"python",
"dictionary"
] | For instance, say I want to build an histogram, I would go like that:
```
hist = {}
for entry in data:
if entry["location"] in hist:
hist[entry["location"]] += 1
else:
hist[entry["location"]] = 1
```
Is there a way to avoid the existence check and initialize or update the key depending on its ... | What you want here is a `defaultdict`:
```
from collections import defaultdict
hist = defaultdict(int)
for entry in data:
hist[entry["location"]] += 1
```
`defaultdict` default-constructs any entry that doesn't already exist in the dict, so for ints they start out at 0 and you just add one for every item. |
Is it possible, in python, to update or initialize a dictionary key with a single command? | 7,280,644 | 3 | 2011-09-02T07:57:39Z | 7,280,666 | 8 | 2011-09-02T08:00:04Z | [
"python",
"dictionary"
] | For instance, say I want to build an histogram, I would go like that:
```
hist = {}
for entry in data:
if entry["location"] in hist:
hist[entry["location"]] += 1
else:
hist[entry["location"]] = 1
```
Is there a way to avoid the existence check and initialize or update the key depending on its ... | Yes, you can do:
```
hist[entry["location"]] = hist.get(entry["location"], 0) + 1
```
With reference types, you can often use `setdefault` for this purpose, but this isn't appropriate when the right hand side of your `dict` is just an integer.
```
Update( hist.setdefault( entry["location"], MakeNewEntry() ) )
``` |
How to group items in an iterable object based on the first character of the item? | 7,280,969 | 4 | 2011-09-02T08:31:13Z | 7,281,048 | 9 | 2011-09-02T08:38:59Z | [
"python"
] | Starting with a sorted iterable object I need to group the items by their first character (say a group for every letter from a to z and a group for numbers and symbols).
For a more concrete example, let's say I have this list:
L = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', '10', '%a', ' b', ...]
And I ne... | ```
import itertools as it
L = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', '10', '%a', ' b']
sorter = lambda x: x[0].lower() if x and x[0].isalpha() else '}'
GL = [list(v) for k, v in it.groupby(sorted(L, key=sorter), key=sorter)]
```
returns:
```
[['aa', 'ab', 'ac'],
['ba', 'bb', 'bc'],
['ca', 'cb', '... |
Python: are objects more memory-hungry than dictionaries? | 7,281,305 | 4 | 2011-09-02T09:04:53Z | 7,281,404 | 10 | 2011-09-02T09:14:07Z | [
"python"
] | ```
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
# RAM usage: 2100
>>> class Test:
... def __init__(self, i):
... self.one = i
... self.hundred = 100*i
...
# RAM usage: 2108
>>> li... | If you define a class in Python (as opposed to writing it as C extension) then by default it will use a dictionary to store all of its attributes. This is why it's impossible for it to be smaller than a dictionary, and why you can assign arbitrary attributes to most Python objects.
If you know know in advance which at... |
In Python, how do you find the index of the first value greater than a threshold in a sorted list? | 7,281,760 | 21 | 2011-09-02T09:49:38Z | 7,281,797 | 39 | 2011-09-02T09:52:58Z | [
"python",
"algorithm",
"search",
"bisection"
] | In Python, how do you find the index of the first value greater than a threshold in a sorted list?
I can think of several ways of doing this (linear search, hand-written dichotomy,..), but I'm looking for a clean an reasonably efficient way of doing it. Since it's probably a pretty common problem, I'm sure experienced... | Have a look at [bisect](http://docs.python.org/library/bisect.html).
```
import bisect
l = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
bisect.bisect(l, 55) # returns 7
```
Compare it with linear search:
```
timeit bisect.bisect(l, 55)
# 375ns
timeit next((i for i,n in enumerate(l) if n > 55), len(l))
# 2.24us
timei... |
What's the difference between assertEqual and assertIs (assertIs was introduced in Python 2.7)? | 7,281,774 | 5 | 2011-09-02T09:51:08Z | 7,281,925 | 11 | 2011-09-02T10:05:54Z | [
"python",
"unit-testing"
] | Reference - <http://docs.python.org/library/unittest.html#assert-methods>
```
assertEqual(a, b) # checks that a == b
assertIs(a, b) # checks that a is b <---- whatever that means????
``` | Using `assertEqual` the two objects need not be of the same type, they merely need to be the same value. In comparison, using `assertIs` the two objects need to be the same object.
`assertEqual` tests for equality like the `==` operator:
> The operators <, >, ==, >=, <=, and != compare the values of two objects. The ... |
Using beaker sessions for checking if user is authenticated in Pyramid | 7,281,884 | 11 | 2011-09-02T10:02:38Z | 7,290,323 | 11 | 2011-09-03T00:11:20Z | [
"python",
"session",
"authentication",
"pyramid"
] | I'm creating a webapp using Pyramid with Beaker sessions.
I would like to store user id in `request.session['user_id']` and some other info after successful signing in and then use it for checking if user already signed in:
```
if 'user_id' in request.session:
# user signed in
else:
# user not signed in or s... | Use pyramid\_beaker and the [SessionAuthenticationPolicy](http://docs.pylonsproject.org/projects/pyramid/en/latest/api/authentication.html#pyramid.authentication.SessionAuthenticationPolicy), then use `pyramid.authentication.authenticated_userid()` to check if they're logged in or not. If it returns `None`, they're not... |
Split three-digit integer to three-item list of each digit in Python | 7,282,054 | 7 | 2011-09-02T10:17:12Z | 7,282,099 | 19 | 2011-09-02T10:20:50Z | [
"python"
] | I'm new to Python. What I want to do is take a three-digit integer like `634`, and split it so it becomes a three-item list, i.e.
`digits = [ 6, 3, 4 ]`
Any help in this would be much appreciated. | You can convert the number to a string, then iterate over the string and convert each character back to an integer:
```
>>> [int(char) for char in str(634)]
[6, 3, 4]
```
Or, as @eph rightfully points out below, use [map()](http://docs.python.org/library/functions.html#map):
```
>>> map(int, str(634)) # Pytho... |
Split three-digit integer to three-item list of each digit in Python | 7,282,054 | 7 | 2011-09-02T10:17:12Z | 7,282,578 | 7 | 2011-09-02T11:10:01Z | [
"python"
] | I'm new to Python. What I want to do is take a three-digit integer like `634`, and split it so it becomes a three-item list, i.e.
`digits = [ 6, 3, 4 ]`
Any help in this would be much appreciated. | Using `str()` is a bit lazy. Quite a lot slower than using math. Using a `while` loop would be faster still
```
In [1]: n = 634
In [2]: timeit [int(i) for i in str(n)]
100000 loops, best of 3: 5.3 us per loop
In [3]: timeit map(int, str(n))
100000 loops, best of 3: 5.32 us per loop
In [4]: import math
In [5]: time... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.