title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
Python: How to make a cross-module variable? | 142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| 82 | 2008-09-26T23:59:47Z | 142,669 | <p>Global variables are usually a bad idea, but you can do this by assigning to <code>__builtins__</code>:</p>
<pre><code>__builtins__.foo = 'something'
print foo
</code></pre>
<p>Also, modules themselves are variables that you can access from any module. So if you define a module called <code>my_globals.py</code>:</p>
<pre><code># my_globals.py
foo = 'something'
</code></pre>
<p>Then you can use that from anywhere as well:</p>
<pre><code>import my_globals
print my_globals.foo
</code></pre>
<p>Using modules rather than modifying <code>__builtins__</code> is generally a cleaner way to do globals of this sort.</p>
| 6 | 2008-09-27T01:03:43Z | [
"python",
"module",
"global"
] |
Python: How to make a cross-module variable? | 142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| 82 | 2008-09-26T23:59:47Z | 3,269,974 | <p>You can pass the globals of one module to onother:</p>
<p>In Module A:</p>
<pre><code>import module_b
my_var=2
module_b.do_something_with_my_globals(globals())
print my_var
</code></pre>
<p>In Module B:</p>
<pre><code>def do_something_with_my_globals(glob): # glob is simply a dict.
glob["my_var"]=3
</code></pre>
| 8 | 2010-07-17T02:22:22Z | [
"python",
"module",
"global"
] |
Python: How to make a cross-module variable? | 142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| 82 | 2008-09-26T23:59:47Z | 3,911,089 | <p>You can already do this with module-level variables. Modules are the same no matter what module they're being imported from. So you can make the variable a module-level variable in whatever module it makes sense to put it in, and access it or assign to it from other modules. It would be better to call a function to set the variable's value, or to make it a property of some singleton object. That way if you end up needing to run some code when the variable's changed, you can do so without breaking your module's external interface.</p>
<p>It's not usually a great way to do things â using globals seldom is â but I think this is the cleanest way to do it. </p>
| 5 | 2010-10-12T01:26:37Z | [
"python",
"module",
"global"
] |
Python: How to make a cross-module variable? | 142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| 82 | 2008-09-26T23:59:47Z | 10,158,462 | <p>I use this for a couple built-in primitive functions that I felt were really missing. One example is a find function that has the same usage semantics as filter, map, reduce.</p>
<pre><code>def builtin_find(f, x, d=None):
for i in x:
if f(i):
return i
return d
import __builtin__
__builtin__.find = builtin_find
</code></pre>
<p>Once this is run (for instance, by importing near your entry point) all your modules can use find() as though, obviously, it was built in.</p>
<pre><code>find(lambda i: i < 0, [1, 3, 0, -5, -10]) # Yields -5, the first negative.
</code></pre>
<p><strong>Note:</strong> You can do this, of course, with filter and another line to test for zero length, or with reduce in one sort of weird line, but I always felt it was weird.</p>
| 0 | 2012-04-15T00:10:57Z | [
"python",
"module",
"global"
] |
Python: How to make a cross-module variable? | 142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| 82 | 2008-09-26T23:59:47Z | 15,035,172 | <p>I believe that there are plenty of circumstances in which it does make sense and it simplifies programming to have some globals that are known across several (tightly coupled) modules. In this spirit, I would like to elaborate a bit on the idea of having a module of globals which is imported by those modules which need to reference them.</p>
<p>When there is only one such module, I name it "g". In it, I assign default values for every variable I intend to treat as global. In each module that uses any of them, I do not use "from g import var", as this only results in a local variable which is initialized from g only at the time of the import. I make most references in the form g.var, and the "g." serves as a constant reminder that I am dealing with a variable that is potentially accessible to other modules. </p>
<p>If the value of such a global variable is to be used frequently in some function in a module, then that function can make a local copy: var = g.var. However, it is important to realize that assignments to var are local, and global g.var cannot be updated without referencing g.var explicitly in an assignment.</p>
<p>Note that you can also have multiple such globals modules shared by different subsets of your modules to keep things a little more tightly controlled. The reason I use short names for my globals modules is to avoid cluttering up the code too much with occurrences of them. With only a little experience, they become mnemonic enough with only 1 or 2 characters. </p>
<p>It is still possible to make an assignment to, say, g.x when x was not already defined in g, and a different module can then access g.x. However, even though the interpreter permits it, this approach is not so transparent, and I do avoid it. There is still the possibility of accidentally creating a new variable in g as a result of a typo in the variable name for an assignment. Sometimes an examination of dir(g) is useful to discover any surprise names that may have arisen by such accident.</p>
| 13 | 2013-02-22T23:48:03Z | [
"python",
"module",
"global"
] |
Python: How to make a cross-module variable? | 142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| 82 | 2008-09-26T23:59:47Z | 20,331,768 | <p>I could achieve cross-module modifiable (or <strong>mutable</strong>) variables by using a dictionary:</p>
<pre><code># in myapp.__init__
Timeouts = {} # cross-modules global mutable variables for testing purpose
Timeouts['WAIT_APP_UP_IN_SECONDS'] = 60
# in myapp.mod1
from myapp import Timeouts
def wait_app_up(project_name, port):
# wait for app until Timeouts['WAIT_APP_UP_IN_SECONDS']
# ...
# in myapp.test.test_mod1
from myapp import Timeouts
def test_wait_app_up_fail(self):
timeout_bak = Timeouts['WAIT_APP_UP_IN_SECONDS']
Timeouts['WAIT_APP_UP_IN_SECONDS'] = 3
with self.assertRaises(hlp.TimeoutException) as cm:
wait_app_up(PROJECT_NAME, PROJECT_PORT)
self.assertEqual("Timeout while waiting for App to start", str(cm.exception))
Timeouts['WAIT_JENKINS_UP_TIMEOUT_IN_SECONDS'] = timeout_bak
</code></pre>
<p>When launching <code>test_wait_app_up_fail</code>, the actual timeout duration is 3 seconds.</p>
| 0 | 2013-12-02T15:24:38Z | [
"python",
"module",
"global"
] |
Python: How to make a cross-module variable? | 142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| 82 | 2008-09-26T23:59:47Z | 31,737,507 | <p>I wanted to post an answer that there is a case where the variable won't be found.</p>
<p>Cyclical imports may break the module behavior.</p>
<p>For example:</p>
<p>first.py</p>
<pre><code>import second
var = 1
</code></pre>
<p>second.py</p>
<pre><code>import first
print(first.var) # will throw an error because the order of execution happens before var gets declared.
</code></pre>
<p>main.py</p>
<pre><code>import first
</code></pre>
<p>On this is example it should be obvious, but in a large code-base, this can be really confusing.</p>
| 0 | 2015-07-31T03:14:05Z | [
"python",
"module",
"global"
] |
How do I upgrade python 2.5.2 to python 2.6rc2 on ubuntu linux 8.04? | 142,764 | <p>I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this.</p>
<p>Thanks
Dirk</p>
| 8 | 2008-09-27T02:15:03Z | 142,770 | <p>With the warning that I think it's a tremendously bad idea to replace the default Python with an unreleased beta version:</p>
<p>First, install 2.6rc2. You can download the source from the <a href="http://www.python.org/download/releases/2.6/">Python website</a>. Standard <code>./configure && make && sudo make install</code> installation style.</p>
<p>Next, remove the <code>/usr/bin/python</code> symlink. Do <em>not</em> remove <code>/usr/bin/python2.5</code>. Add a symlink to 2.6 with <code>ln -s /usr/local/bin/python2.6 /usr/bin/python</code>.</p>
<p>Once again, I think this is a terrible idea. There is almost certainly a better way to do whatever you're trying to accomplish.</p>
<p><hr /></p>
<p>Migrating installed libraries is a much longer process. Look in the <code> /usr/lib/python2.5/site-packages/</code> and <code> /usr/local/lib/python2.5/site-packages/</code> directories. Any libraries installed to them will need to be re-installed with 2.6. Since you're not using a packaged Python version, you cannot use Ubuntu's packages -- you'll have to manually upgrade all the libraries yourself. Most of them can probably be installed with <code>sudo easy_install <name></code>, but some like PyGTK+ are not so easy. You'll have to follow custom installation procedures for each such library.</p>
| 15 | 2008-09-27T02:19:38Z | [
"python",
"linux",
"ubuntu",
"installation"
] |
How do I upgrade python 2.5.2 to python 2.6rc2 on ubuntu linux 8.04? | 142,764 | <p>I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this.</p>
<p>Thanks
Dirk</p>
| 8 | 2008-09-27T02:15:03Z | 142,777 | <p>Is there any need to?</p>
<p>Ubuntu in general doesn't package RC releases. 2.6 will not be available in Ubuntu until Jaunty Jackalope.</p>
<p>However,, if you insist that you need to install it, then, you'll have to do so without a package manager.</p>
<p>Download the package, and unzip it to a directory</p>
<p>run the following commands (waiting for each to finish as you do so)</p>
<pre><code>./configure
make
sudo make install
</code></pre>
<p>There, you have it installed.</p>
<p>It's better to wait for it to be packaged first, espescially as Python is used in a lot of ubuntu internals, so may break your system horribly</p>
| 1 | 2008-09-27T02:25:18Z | [
"python",
"linux",
"ubuntu",
"installation"
] |
How do I upgrade python 2.5.2 to python 2.6rc2 on ubuntu linux 8.04? | 142,764 | <p>I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this.</p>
<p>Thanks
Dirk</p>
| 8 | 2008-09-27T02:15:03Z | 152,185 | <p>It would not be wise to change the default version of Python, i.e. what you get when you type "python" into a shell. However, you can have multiple versions of python installed. The trick is to make sure that the program named "python" on the path is the system supplied version. If you want to run your install of Python 2.6 you'd then type python2.6 into a shell to start it.</p>
<p>Download the package and unzip it, then run:</p>
<pre><code>./configure
make
sudo make install
ls -l /usr/local/bin
</code></pre>
<p>You should see a python and a python2.6 file, both created on the day you ran make install; delete the python file. Then when <code>python</code> is launched the standard system Python version from <code>/usr/bin</code> will be run, and when <code>python2.6</code> is run you get your shiny new python 2.6rc2. Python displays the version when it starts an interactive interpreter.</p>
| 1 | 2008-09-30T08:10:39Z | [
"python",
"linux",
"ubuntu",
"installation"
] |
How do I upgrade python 2.5.2 to python 2.6rc2 on ubuntu linux 8.04? | 142,764 | <p>I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this.</p>
<p>Thanks
Dirk</p>
| 8 | 2008-09-27T02:15:03Z | 633,753 | <p>I have the same issue, and apparently pre-built binaries can be found here:</p>
<pre><code># Python 2.6
deb http://ppa.launchpad.net/doko/ubuntu intrepid main
deb-src http://ppa.launchpad.net/doko/ubuntu intrepid main
</code></pre>
| 6 | 2009-03-11T08:41:01Z | [
"python",
"linux",
"ubuntu",
"installation"
] |
Does Python have a bitfield type? | 142,812 | <p>I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?</p>
| 34 | 2008-09-27T02:47:40Z | 142,821 | <p>NumPy has a <a href="http://numpy.scipy.org/array_interface.shtml" rel="nofollow">array interface</a> module that you can use to make a bitfield.</p>
| 4 | 2008-09-27T02:52:13Z | [
"python",
"bit-fields",
"bitarray"
] |
Does Python have a bitfield type? | 142,812 | <p>I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?</p>
| 34 | 2008-09-27T02:47:40Z | 142,846 | <p>The BitVector package may be what you need. It's not built in to my python installation, but easy to track down on the python site.</p>
<p><a href="https://pypi.python.org/pypi/BitVector" rel="nofollow">https://pypi.python.org/pypi/BitVector</a> for the current version.</p>
| 5 | 2008-09-27T03:03:16Z | [
"python",
"bit-fields",
"bitarray"
] |
Does Python have a bitfield type? | 142,812 | <p>I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?</p>
| 34 | 2008-09-27T02:47:40Z | 143,221 | <p><a href="http://pypi.python.org/pypi/bitarray/">Bitarray</a> was the best answer I found, when I recently had a similar need. It's a C extension (so much faster than BitVector, which is pure python) and stores its data in an actual bitfield (so it's eight times more memory efficient than a numpy boolean array, which appears to use a byte per element.)</p>
| 22 | 2008-09-27T08:20:43Z | [
"python",
"bit-fields",
"bitarray"
] |
Does Python have a bitfield type? | 142,812 | <p>I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?</p>
| 34 | 2008-09-27T02:47:40Z | 143,247 | <p>If your bitfield is short, you can probably use <a href="http://docs.python.org/lib/module-struct.html" rel="nofollow">the struct module</a>. Otherwise I'd recommend some sort of a wrapper around <a href="http://docs.python.org/lib/module-array.html" rel="nofollow">the array module</a>.</p>
<p>Also, the ctypes module does contain <a href="http://docs.python.org/lib/ctypes-bit-fields-in-structures-unions.html" rel="nofollow">bitfields</a>, but I've never used it myself. <em>Caveat emptor</em>.</p>
| 2 | 2008-09-27T08:41:05Z | [
"python",
"bit-fields",
"bitarray"
] |
Does Python have a bitfield type? | 142,812 | <p>I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?</p>
| 34 | 2008-09-27T02:47:40Z | 143,643 | <p>I use the binary bit-wise operators !, &, |, ^, >>, and <<. They work really well and are implemented directly in the underlying C, which is usually directly on the underlying hardware.</p>
| 4 | 2008-09-27T13:26:06Z | [
"python",
"bit-fields",
"bitarray"
] |
Does Python have a bitfield type? | 142,812 | <p>I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?</p>
| 34 | 2008-09-27T02:47:40Z | 265,491 | <p>Represent each of your values as a power of two:</p>
<pre><code>testA = 2**0
testB = 2**1
testC = 2**3
</code></pre>
<p>Then to set a value true:</p>
<pre><code>table = table | testB
</code></pre>
<p>To set a value false:</p>
<pre><code>table = table & (~testC)
</code></pre>
<p>To test for a value:</p>
<pre><code>bitfield_length = 0xff
if ((table & testB & bitfield_length) != 0):
print "Field B set"
</code></pre>
<p>Dig a little deeper into hexadecimal representation if this doesn't make sense to you. This is basically how you keep track of your boolean flags in an embedded C application as well (if you have limitted memory).</p>
| 5 | 2008-11-05T15:30:33Z | [
"python",
"bit-fields",
"bitarray"
] |
Does Python have a bitfield type? | 142,812 | <p>I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?</p>
| 34 | 2008-09-27T02:47:40Z | 1,574,928 | <p>You should take a look at the <a href="http://python-bitstring.googlecode.com">bitstring</a> module, which has recently reached version 2.0.
The binary data is compactly stored as a byte array and can be easily created, modified and analysed.</p>
<p>You can create <code>BitString</code> objects from binary, octal, hex, integers (big or little endian), strings, bytes, floats, files and more.</p>
<pre><code>a = BitString('0xed44')
b = BitString('0b11010010')
c = BitString(int=100, length=14)
d = BitString('uintle:16=55, 0b110, 0o34')
e = BitString(bytes='hello')
f = pack('<2H, bin:3', 5, 17, '001')
</code></pre>
<p>You can then analyse and modify them with simple functions or slice notation - no need to worry about bit masks etc.</p>
<pre><code>a.prepend('0b110')
if '0b11' in b:
c.reverse()
g = a.join([b, d, e])
g.replace('0b101', '0x3400ee1')
if g[14]:
del g[14:17]
else:
g[55:58] = 'uint:11=33, int:9=-1'
</code></pre>
<p>There is also a concept of a bit position, so that you can treat it like a file or stream if that's useful to you. Properties are used to give different interpretations of the bit data.</p>
<pre><code>w = g.read(10).uint
x, y, z = g.readlist('int:4, int:4, hex:32')
if g.peek(8) == '0x00':
g.pos += 10
</code></pre>
<p>Plus there's support for the standard bit-wise binary operators, packing, unpacking, endianness and more. The latest version is for Python 2.6 to 3.1, and although it's pure Python it is reasonably well optimised in terms of memory and speed.</p>
| 10 | 2009-10-15T20:43:54Z | [
"python",
"bit-fields",
"bitarray"
] |
Does Python have a bitfield type? | 142,812 | <p>I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?</p>
| 34 | 2008-09-27T02:47:40Z | 3,730,785 | <p>If you want to use ints (or long ints) to represent as arrays of bools (or as sets of integers), take a look at <a href="http://sourceforge.net/projects/pybitop/files/" rel="nofollow">http://sourceforge.net/projects/pybitop/files/</a></p>
<p>It provides insert/extract of bitfields into long ints; finding the most-significant, or least-significant '1' bit; counting all the 1's; bit-reversal; stuff like that which is all possible in pure python but much faster in C.</p>
| 1 | 2010-09-16T21:01:07Z | [
"python",
"bit-fields",
"bitarray"
] |
Does Python have a bitfield type? | 142,812 | <p>I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?</p>
| 34 | 2008-09-27T02:47:40Z | 11,481,471 | <p>If you mainly want to be able to name your bit fields and easily manipulate them, e.g. to work with flags represented as single bits in a communications protocol, then you can use the standard Structure and Union features of <a href="http://docs.python.org/library/ctypes.html">ctypes</a>, as described at <a href="http://stackoverflow.com/questions/10346375/how-do-i-properly-declare-a-ctype-structure-union-in-python">How Do I Properly Declare a ctype Structure + Union in Python? - Stack Overflow</a></p>
<p>For example, to work with the 4 least-significant bits of a byte individually, just name them from least to most significant in a LittleEndianStructure. You use a union to provide access to the same data as a byte or int so you can move the data in or out of the communication protocol. In this case that is done via the <code>flags.asbyte</code> field:</p>
<pre><code>import ctypes
c_uint8 = ctypes.c_uint8
class Flags_bits(ctypes.LittleEndianStructure):
_fields_ = [
("logout", c_uint8, 1),
("userswitch", c_uint8, 1),
("suspend", c_uint8, 1),
("idle", c_uint8, 1),
]
class Flags(ctypes.Union):
_fields_ = [("b", Flags_bits),
("asbyte", c_uint8)]
flags = Flags()
flags.asbyte = 0xc
print(flags.b.idle)
print(flags.b.suspend)
print(flags.b.userswitch)
print(flags.b.logout)
</code></pre>
<p>The four bits (which I've printed here starting with the most significant, which seems more natural when printing) are 1, 1, 0, 0, i.e. 0xc in binary.</p>
| 24 | 2012-07-14T06:02:45Z | [
"python",
"bit-fields",
"bitarray"
] |
Drag and drop onto Python script in Windows Explorer | 142,844 | <p>I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.</p>
<p>Is there some kind of configuration that needs to be done somewhere for this work?</p>
| 37 | 2008-09-27T03:02:30Z | 142,854 | <p>Sure. From a <a href="http://mindlesstechnology.wordpress.com/2008/03/29/make-python-scripts-droppable-in-windows/">mindless technology article called "Make Python Scripts Droppable in Windows"</a>, you can add a drop handler by adding a registry key:</p>
<blockquote>
<p>Hereâs a registry import file that you can use to do this. Copy the
following into a .reg file and run it
(Make sure that your .py extensions
are mapped to Python.File).</p>
<pre><code>Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler]
@="{60254CA5-953B-11CF-8C96-00AA00B8708C}"
</code></pre>
</blockquote>
<p>This makes Python scripts use the WSH drop handler, which is compatible with long filenames. To use the short filename handler, replace the GUID with <code>86C86720-42A0-1069-A2E8-08002B30309D</code>.</p>
<p>A comment in that post indicates that one can enable dropping on "no console Python files (<code>.pyw</code>)" or "compiled Python files (<code>.pyc</code>)" by using the <code>Python.NoConFile</code> and <code>Python.CompiledFile</code> classes.</p>
| 46 | 2008-09-27T03:06:25Z | [
"python",
"windows",
"drag-and-drop",
"windows-explorer"
] |
Drag and drop onto Python script in Windows Explorer | 142,844 | <p>I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.</p>
<p>Is there some kind of configuration that needs to be done somewhere for this work?</p>
| 37 | 2008-09-27T03:02:30Z | 4,486,506 | <p>Try using py2exe. Use py2exe to convert your python script into a windows executable. You should then be able to drag and drop input files to your script in Windows Explorer. You should also be able to create a shortcut on your desktop and drop input files onto it. And if your python script can take a file list you should be able to drag and drop multiple files on your script (or shortcut).</p>
| 5 | 2010-12-20T02:47:21Z | [
"python",
"windows",
"drag-and-drop",
"windows-explorer"
] |
Drag and drop onto Python script in Windows Explorer | 142,844 | <p>I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.</p>
<p>Is there some kind of configuration that needs to be done somewhere for this work?</p>
| 37 | 2008-09-27T03:02:30Z | 10,246,159 | <p>write a simple shell script (file.bat)</p>
<pre><code>"c:\Python27\python.exe" yourprogram.py %1
</code></pre>
<p>where %1 stands for the firs argument you pass to the script.</p>
<p>Now drag%drop your target files on the file.bat icon.</p>
| 18 | 2012-04-20T12:21:36Z | [
"python",
"windows",
"drag-and-drop",
"windows-explorer"
] |
Drag and drop onto Python script in Windows Explorer | 142,844 | <p>I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.</p>
<p>Is there some kind of configuration that needs to be done somewhere for this work?</p>
| 37 | 2008-09-27T03:02:30Z | 21,840,490 | <p>Create a shortcut of the file. In case you don't have python open .py files by default, go into the properties of the shortcut and edit the target of the shortcut to include the python version you're using. For example:</p>
<p>Target: C:\Python26\python.exe < shortcut target path></p>
<p>I'm posting this because I didn't want to edit the Registry and the .bat workaround didn't work for me.</p>
| 0 | 2014-02-17T22:23:58Z | [
"python",
"windows",
"drag-and-drop",
"windows-explorer"
] |
Drag and drop onto Python script in Windows Explorer | 142,844 | <p>I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.</p>
<p>Is there some kind of configuration that needs to be done somewhere for this work?</p>
| 37 | 2008-09-27T03:02:30Z | 35,284,322 | <p>The working directory may be in Window/System32 when get error: IOError: [Errno 2] No such file or directory: .... So you need to change to the script or input file directory firstly. Such as: </p>
<p><code>os.chdir(os.path.split(sys.argv[0])[0])</code></p>
| -1 | 2016-02-09T05:09:05Z | [
"python",
"windows",
"drag-and-drop",
"windows-explorer"
] |
OCSP libraries for python / java / c? | 143,515 | <p>Going back to my previous question on OCSP, does anybody know of "reliable" OCSP libraries for Python, Java and C?</p>
<p>I need "client" OCSP functionality, as I'll be checking the status of Certs against an OCSP responder, so responder functionality is not that important.</p>
<p>Thanks</p>
| 3 | 2008-09-27T12:12:32Z | 143,996 | <p>Have you check pyOpenSSL.. am sure openssl supports ocsp and python binding may support it</p>
| 1 | 2008-09-27T16:57:12Z | [
"java",
"python",
"c",
"ocsp"
] |
OCSP libraries for python / java / c? | 143,515 | <p>Going back to my previous question on OCSP, does anybody know of "reliable" OCSP libraries for Python, Java and C?</p>
<p>I need "client" OCSP functionality, as I'll be checking the status of Certs against an OCSP responder, so responder functionality is not that important.</p>
<p>Thanks</p>
| 3 | 2008-09-27T12:12:32Z | 144,139 | <p>Java 5 has support of revocation checking via <a href="http://java.sun.com/j2se/1.5.0/docs/guide/security/pki-tiger.html#OCSP" rel="nofollow">OCSP built in</a>. If you want to build an OCSP responder, or have finer control over revocation checking, check out <a href="http://www.bouncycastle.org/docs/docs1.5/overview-summary.html" rel="nofollow">Bouncy Castle</a>. You can use this to implement your own <a href="http://java.sun.com/javase/6/docs/api/java/security/cert/PKIXCertPathChecker.html" rel="nofollow">CertPathChecker</a> that, for example, uses non-blocking I/O in its status checks.</p>
| 3 | 2008-09-27T17:53:57Z | [
"java",
"python",
"c",
"ocsp"
] |
OCSP libraries for python / java / c? | 143,515 | <p>Going back to my previous question on OCSP, does anybody know of "reliable" OCSP libraries for Python, Java and C?</p>
<p>I need "client" OCSP functionality, as I'll be checking the status of Certs against an OCSP responder, so responder functionality is not that important.</p>
<p>Thanks</p>
| 3 | 2008-09-27T12:12:32Z | 189,046 | <p><a href="http://www.openssl.org/" rel="nofollow">OpenSSL</a> is the most widely used product for OCSP in C. It's quite reliable, although incredibly obtuse. I'd recommend looking at apps/ocsp.c for a pretty good example of how to make OCSP requests and validate responses.</p>
<p>Vista and Server 2008 have built-in OCSP support in CAPI; check out <a href="http://msdn.microsoft.com/en-us/library/aa377167.aspx" rel="nofollow">CertVerifyRevocation</a>.</p>
| 1 | 2008-10-09T20:20:57Z | [
"java",
"python",
"c",
"ocsp"
] |
Crypto/X509 certificate parsing libraries for Python | 143,632 | <p>Any recommended crypto libraries for Python. I know I've asked something similar in <a href="http://stackoverflow.com/questions/143523/">x509 certificate parsing libraries for Java</a>, but I should've split the question in two.</p>
<p>What I need is the ability to parse X.509 Certificates to extract the information contained in them.</p>
<p>Looking around, I've found two options:</p>
<ul>
<li>Python OpenSSL Wrappers (<a href="http://sourceforge.net/projects/pow" rel="nofollow" title="Python OpenSSL Wrappers">http://sourceforge.net/projects/pow</a>)</li>
<li><a href="https://github.com/pyca/pyopenssl" rel="nofollow">pyOpenSSL</a></li>
</ul>
<p>Of the two, pyOpenSSL seems to be the most "maintained", but I'd like some feedback on anybody who might have experience with them?</p>
| 5 | 2008-09-27T13:15:33Z | 144,087 | <p>You might want to try <a href="http://www.keyczar.org/" rel="nofollow">keyczar</a> as mentioned by me in your other post, since that library actually has implementations for both python and java. That would make it easier to use it in both contexts.</p>
<p>A word of warning: I have not actually used this library 8(, so please take this with a grain of salt.</p>
| 3 | 2008-09-27T17:28:36Z | [
"python",
"cryptography",
"openssl",
"x509"
] |
Crypto/X509 certificate parsing libraries for Python | 143,632 | <p>Any recommended crypto libraries for Python. I know I've asked something similar in <a href="http://stackoverflow.com/questions/143523/">x509 certificate parsing libraries for Java</a>, but I should've split the question in two.</p>
<p>What I need is the ability to parse X.509 Certificates to extract the information contained in them.</p>
<p>Looking around, I've found two options:</p>
<ul>
<li>Python OpenSSL Wrappers (<a href="http://sourceforge.net/projects/pow" rel="nofollow" title="Python OpenSSL Wrappers">http://sourceforge.net/projects/pow</a>)</li>
<li><a href="https://github.com/pyca/pyopenssl" rel="nofollow">pyOpenSSL</a></li>
</ul>
<p>Of the two, pyOpenSSL seems to be the most "maintained", but I'd like some feedback on anybody who might have experience with them?</p>
| 5 | 2008-09-27T13:15:33Z | 349,462 | <p>Use M2Crypto, it is the most complete tool IMHO</p>
| 5 | 2008-12-08T12:58:51Z | [
"python",
"cryptography",
"openssl",
"x509"
] |
Crypto/X509 certificate parsing libraries for Python | 143,632 | <p>Any recommended crypto libraries for Python. I know I've asked something similar in <a href="http://stackoverflow.com/questions/143523/">x509 certificate parsing libraries for Java</a>, but I should've split the question in two.</p>
<p>What I need is the ability to parse X.509 Certificates to extract the information contained in them.</p>
<p>Looking around, I've found two options:</p>
<ul>
<li>Python OpenSSL Wrappers (<a href="http://sourceforge.net/projects/pow" rel="nofollow" title="Python OpenSSL Wrappers">http://sourceforge.net/projects/pow</a>)</li>
<li><a href="https://github.com/pyca/pyopenssl" rel="nofollow">pyOpenSSL</a></li>
</ul>
<p>Of the two, pyOpenSSL seems to be the most "maintained", but I'd like some feedback on anybody who might have experience with them?</p>
| 5 | 2008-09-27T13:15:33Z | 2,038,330 | <p>My experience is that most crypto libraries are focused on a particular workflow - making a certain set of tasks easier and others hard or perhaps impossible. The exception to this would be ones that have really been around a long time and have matured (e.g. openssl, bounceycastle, but none of the python libraries in my experience). So, you really need to evaluate libraries in the context of what you are trying to do.</p>
<p>More specifically, I've used pyOpenSSL for simple generation of private keys and certificates requests (i.e. being a client to a CA) and am quite happy with it.</p>
| 1 | 2010-01-10T19:48:35Z | [
"python",
"cryptography",
"openssl",
"x509"
] |
Has anyone found a good set of python plugins for vim -- specifically module completion? | 144,201 | <p>I'm looking for a suite of plugins that can help me finally switch over to vim full-time.</p>
<p>Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it.</p>
<p>What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance).</p>
<ul>
<li>Code completion, meaning: the ability to code complete modules/functions/etc. in <em>any</em> module that's on the pythonpath, <strong>not just system modules</strong>. Bonus points for showing docstrings when completing.</li>
<li>Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files?</li>
<li>Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open.</li>
<li>Bzr integration. Not super important, since most of it I can just drop to the shell to do.</li>
</ul>
| 22 | 2008-09-27T18:28:42Z | 144,212 | <p><a href="http://www.sontek.net/python-with-a-modular-ide-vim" rel="nofollow">Here you can find some info</a> about this.</p>
<p>It covers code completion, having a list of classes and functions in open files. I haven't got around to do a full configuration for vim, since I don't use Python primarily, but I have the same interests in transforming vim in a better Python IDE.</p>
<p><strong>Edit:</strong> The original site is down, so found it <a href="https://web.archive.org/web/20110106042207/http://sontek.net/python-with-a-modular-ide-vim" rel="nofollow">saved on the web archive</a>.</p>
| 17 | 2008-09-27T18:42:39Z | [
"python",
"vim",
"code-completion"
] |
Has anyone found a good set of python plugins for vim -- specifically module completion? | 144,201 | <p>I'm looking for a suite of plugins that can help me finally switch over to vim full-time.</p>
<p>Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it.</p>
<p>What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance).</p>
<ul>
<li>Code completion, meaning: the ability to code complete modules/functions/etc. in <em>any</em> module that's on the pythonpath, <strong>not just system modules</strong>. Bonus points for showing docstrings when completing.</li>
<li>Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files?</li>
<li>Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open.</li>
<li>Bzr integration. Not super important, since most of it I can just drop to the shell to do.</li>
</ul>
| 22 | 2008-09-27T18:28:42Z | 144,278 | <p>Here is some info on Bazaar integration if you're interested:</p>
<p>https://launchpad.net/bzr-vim-commands</p>
| 1 | 2008-09-27T19:29:39Z | [
"python",
"vim",
"code-completion"
] |
Has anyone found a good set of python plugins for vim -- specifically module completion? | 144,201 | <p>I'm looking for a suite of plugins that can help me finally switch over to vim full-time.</p>
<p>Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it.</p>
<p>What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance).</p>
<ul>
<li>Code completion, meaning: the ability to code complete modules/functions/etc. in <em>any</em> module that's on the pythonpath, <strong>not just system modules</strong>. Bonus points for showing docstrings when completing.</li>
<li>Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files?</li>
<li>Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open.</li>
<li>Bzr integration. Not super important, since most of it I can just drop to the shell to do.</li>
</ul>
| 22 | 2008-09-27T18:28:42Z | 144,646 | <p>For refactoring: <a href="http://rope.sourceforge.net/ropevim.html" rel="nofollow">ropevim</a></p>
| 2 | 2008-09-27T22:38:49Z | [
"python",
"vim",
"code-completion"
] |
Has anyone found a good set of python plugins for vim -- specifically module completion? | 144,201 | <p>I'm looking for a suite of plugins that can help me finally switch over to vim full-time.</p>
<p>Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it.</p>
<p>What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance).</p>
<ul>
<li>Code completion, meaning: the ability to code complete modules/functions/etc. in <em>any</em> module that's on the pythonpath, <strong>not just system modules</strong>. Bonus points for showing docstrings when completing.</li>
<li>Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files?</li>
<li>Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open.</li>
<li>Bzr integration. Not super important, since most of it I can just drop to the shell to do.</li>
</ul>
| 22 | 2008-09-27T18:28:42Z | 149,921 | <p><strong>Code completion:</strong> <a href="http://github.com/orestis/pysmell/tree/master" rel="nofollow">PySmell</a> looks promising. It's work-in-progress, but alredy useful.</p>
| 0 | 2008-09-29T18:04:00Z | [
"python",
"vim",
"code-completion"
] |
Has anyone found a good set of python plugins for vim -- specifically module completion? | 144,201 | <p>I'm looking for a suite of plugins that can help me finally switch over to vim full-time.</p>
<p>Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it.</p>
<p>What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance).</p>
<ul>
<li>Code completion, meaning: the ability to code complete modules/functions/etc. in <em>any</em> module that's on the pythonpath, <strong>not just system modules</strong>. Bonus points for showing docstrings when completing.</li>
<li>Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files?</li>
<li>Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open.</li>
<li>Bzr integration. Not super important, since most of it I can just drop to the shell to do.</li>
</ul>
| 22 | 2008-09-27T18:28:42Z | 150,378 | <p>I use <a href="http://www.vim.org/scripts/script.php?script_id=910" rel="nofollow">pydoc.vim</a> (I actually wrote it) a lot, try it and tell me what you think. Another one that I think is quite useful is the updated syntax file with all it's extensions that you can enable, which you can find <a href="http://www.vim.org/scripts/script.php?script_id=790" rel="nofollow">here</a>.</p>
| 1 | 2008-09-29T19:55:24Z | [
"python",
"vim",
"code-completion"
] |
Has anyone found a good set of python plugins for vim -- specifically module completion? | 144,201 | <p>I'm looking for a suite of plugins that can help me finally switch over to vim full-time.</p>
<p>Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it.</p>
<p>What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance).</p>
<ul>
<li>Code completion, meaning: the ability to code complete modules/functions/etc. in <em>any</em> module that's on the pythonpath, <strong>not just system modules</strong>. Bonus points for showing docstrings when completing.</li>
<li>Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files?</li>
<li>Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open.</li>
<li>Bzr integration. Not super important, since most of it I can just drop to the shell to do.</li>
</ul>
| 22 | 2008-09-27T18:28:42Z | 1,148,862 | <p>I use Pydiction (<a href="http://www.vim.org/scripts/script.php?script_id=850" rel="nofollow">http://www.vim.org/scripts/script.php?script_id=850</a>) it's a plugin for vim that lets you Tab-complete python modules/methods/attributes/keywords, including 3rd party stuff like Pygame, wxPython, Twisted, and literally everything. It works more accurately than other things i've tried and it doesn't even require that python support be compiled into your Vim.</p>
| 1 | 2009-07-18T23:24:25Z | [
"python",
"vim",
"code-completion"
] |
Has anyone found a good set of python plugins for vim -- specifically module completion? | 144,201 | <p>I'm looking for a suite of plugins that can help me finally switch over to vim full-time.</p>
<p>Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it.</p>
<p>What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance).</p>
<ul>
<li>Code completion, meaning: the ability to code complete modules/functions/etc. in <em>any</em> module that's on the pythonpath, <strong>not just system modules</strong>. Bonus points for showing docstrings when completing.</li>
<li>Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files?</li>
<li>Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open.</li>
<li>Bzr integration. Not super important, since most of it I can just drop to the shell to do.</li>
</ul>
| 22 | 2008-09-27T18:28:42Z | 3,113,907 | <p>Old question, but I typed all this up for a misread question...</p>
<p><strong>General plugin recommendations</strong>: <a href="http://www.vim.org/scripts/script.php?script_id=1581" rel="nofollow">LookupFile</a> and a plugin for your source control system (I like <a href="http://git-scm.com/" rel="nofollow">Git</a> and <a href="http://github.com/motemen/git-vim" rel="nofollow">Git-Vim</a>).</p>
<p><strong>Python plugin recommendations</strong>: If you're using Linux, I'd recommend ipython and <a href="http://ipython.scipy.org/moin/Cookbook/IPythonGVim" rel="nofollow">ipy.py</a> (a better interactive interpreter). <a href="http://www.vim.org/scripts/script.php?script_id=790" rel="nofollow">Improved syntax highlighting</a>, <a href="http://www.vim.org/scripts/script.php?script_id=1318" rel="nofollow">snippets</a>, <a href="http://www.vim.org/scripts/script.php?script_id=910" rel="nofollow">pydoc</a>, and for refactoring support <a href="http://bicyclerepair.sourceforge.net/" rel="nofollow">bicyclerepairman</a>. I got started with <a href="http://www.sontek.net/post/Python-with-a-modular-IDE-%28Vim%29.aspx" rel="nofollow">this post</a>.</p>
<p>You may want to try looking through someone's vimfiles. <a href="http://github.com/pydave/daveconfig/tree/master/multi/vim/" rel="nofollow">Mine are on github</a>.</p>
| 3 | 2010-06-24T21:12:36Z | [
"python",
"vim",
"code-completion"
] |
Has anyone found a good set of python plugins for vim -- specifically module completion? | 144,201 | <p>I'm looking for a suite of plugins that can help me finally switch over to vim full-time.</p>
<p>Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it.</p>
<p>What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance).</p>
<ul>
<li>Code completion, meaning: the ability to code complete modules/functions/etc. in <em>any</em> module that's on the pythonpath, <strong>not just system modules</strong>. Bonus points for showing docstrings when completing.</li>
<li>Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files?</li>
<li>Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open.</li>
<li>Bzr integration. Not super important, since most of it I can just drop to the shell to do.</li>
</ul>
| 22 | 2008-09-27T18:28:42Z | 7,780,004 | <p>And I write another plugin: <a href="https://github.com/klen/python-mode" rel="nofollow">https://github.com/klen/python-mode</a></p>
<p>Old (now its more powerful) screencast here: <a href="https://www.youtube.com/watch?v=67OZNp9Z0CQ" rel="nofollow">https://www.youtube.com/watch?v=67OZNp9Z0CQ</a></p>
| 4 | 2011-10-15T19:09:27Z | [
"python",
"vim",
"code-completion"
] |
Has anyone found a good set of python plugins for vim -- specifically module completion? | 144,201 | <p>I'm looking for a suite of plugins that can help me finally switch over to vim full-time.</p>
<p>Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it.</p>
<p>What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance).</p>
<ul>
<li>Code completion, meaning: the ability to code complete modules/functions/etc. in <em>any</em> module that's on the pythonpath, <strong>not just system modules</strong>. Bonus points for showing docstrings when completing.</li>
<li>Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files?</li>
<li>Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open.</li>
<li>Bzr integration. Not super important, since most of it I can just drop to the shell to do.</li>
</ul>
| 22 | 2008-09-27T18:28:42Z | 18,787,006 | <p>I personally think<a href="https://github.com/davidhalter/jedi-vim" rel="nofollow">Jedi Vim</a> is the best, but it is incompatible with python-mode.</p>
| 0 | 2013-09-13T13:02:44Z | [
"python",
"vim",
"code-completion"
] |
Significant figures in the decimal module | 144,218 | <p>So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:</p>
<pre><code>from decimal import Decimal
>>> Decimal('1.0') + Decimal('2.0')
Decimal("3.0")
</code></pre>
<p>But this doesn't:</p>
<pre><code>>>> Decimal('1.00') / Decimal('3.00')
Decimal("0.3333333333333333333333333333")
</code></pre>
<p>So two questions:</p>
<ol>
<li>Am I right that this isn't the expected amount of significant digits, or do I need to brush up on significant digit math?</li>
<li>Is there any way to do this without having to set the decimal precision manually? Granted, I'm sure I can use numpy to do this, but I just want to know if there's a way to do this with the decimal module out of curiosity.</li>
</ol>
| 4 | 2008-09-27T18:47:54Z | 144,225 | <p>Decimal defaults to 28 places of precision.<br/>
The only way to limit the number of digits it returns is by altering the precision.</p>
| 0 | 2008-09-27T18:53:49Z | [
"python",
"floating-point",
"decimal",
"physics",
"significance"
] |
Significant figures in the decimal module | 144,218 | <p>So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:</p>
<pre><code>from decimal import Decimal
>>> Decimal('1.0') + Decimal('2.0')
Decimal("3.0")
</code></pre>
<p>But this doesn't:</p>
<pre><code>>>> Decimal('1.00') / Decimal('3.00')
Decimal("0.3333333333333333333333333333")
</code></pre>
<p>So two questions:</p>
<ol>
<li>Am I right that this isn't the expected amount of significant digits, or do I need to brush up on significant digit math?</li>
<li>Is there any way to do this without having to set the decimal precision manually? Granted, I'm sure I can use numpy to do this, but I just want to know if there's a way to do this with the decimal module out of curiosity.</li>
</ol>
| 4 | 2008-09-27T18:47:54Z | 144,231 | <p>Decimals won't throw away decimal places like that. If you really want to limit precision to 2 d.p. then try</p>
<pre><code>decimal.getcontext().prec=2
</code></pre>
<p>EDIT: You can alternatively call quantize() every time you multiply or divide (addition and subtraction will preserve the 2 dps).</p>
| 2 | 2008-09-27T18:58:37Z | [
"python",
"floating-point",
"decimal",
"physics",
"significance"
] |
Significant figures in the decimal module | 144,218 | <p>So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:</p>
<pre><code>from decimal import Decimal
>>> Decimal('1.0') + Decimal('2.0')
Decimal("3.0")
</code></pre>
<p>But this doesn't:</p>
<pre><code>>>> Decimal('1.00') / Decimal('3.00')
Decimal("0.3333333333333333333333333333")
</code></pre>
<p>So two questions:</p>
<ol>
<li>Am I right that this isn't the expected amount of significant digits, or do I need to brush up on significant digit math?</li>
<li>Is there any way to do this without having to set the decimal precision manually? Granted, I'm sure I can use numpy to do this, but I just want to know if there's a way to do this with the decimal module out of curiosity.</li>
</ol>
| 4 | 2008-09-27T18:47:54Z | 144,253 | <p>If I undertand Decimal correctly, the "precision" is the number of digits after the decimal point in <em>decimal notation</em>.</p>
<p>You seem to want something else: the number of significant digits. That is one more than the number of digits after the decimal point in <em>scientific notation</em>.</p>
<p>I would be interested in learning about a Python module that does significant-digits-aware floating point point computations.</p>
| 0 | 2008-09-27T19:11:46Z | [
"python",
"floating-point",
"decimal",
"physics",
"significance"
] |
Significant figures in the decimal module | 144,218 | <p>So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:</p>
<pre><code>from decimal import Decimal
>>> Decimal('1.0') + Decimal('2.0')
Decimal("3.0")
</code></pre>
<p>But this doesn't:</p>
<pre><code>>>> Decimal('1.00') / Decimal('3.00')
Decimal("0.3333333333333333333333333333")
</code></pre>
<p>So two questions:</p>
<ol>
<li>Am I right that this isn't the expected amount of significant digits, or do I need to brush up on significant digit math?</li>
<li>Is there any way to do this without having to set the decimal precision manually? Granted, I'm sure I can use numpy to do this, but I just want to know if there's a way to do this with the decimal module out of curiosity.</li>
</ol>
| 4 | 2008-09-27T18:47:54Z | 144,263 | <p>What's wrong with floating point? </p>
<pre><code>>>> "%8.2e"% ( 1.0/3.0 )
'3.33e-01'
</code></pre>
<p>It was designed for scientific-style calculations with a limited number of significant digits.</p>
| 0 | 2008-09-27T19:17:57Z | [
"python",
"floating-point",
"decimal",
"physics",
"significance"
] |
Significant figures in the decimal module | 144,218 | <p>So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:</p>
<pre><code>from decimal import Decimal
>>> Decimal('1.0') + Decimal('2.0')
Decimal("3.0")
</code></pre>
<p>But this doesn't:</p>
<pre><code>>>> Decimal('1.00') / Decimal('3.00')
Decimal("0.3333333333333333333333333333")
</code></pre>
<p>So two questions:</p>
<ol>
<li>Am I right that this isn't the expected amount of significant digits, or do I need to brush up on significant digit math?</li>
<li>Is there any way to do this without having to set the decimal precision manually? Granted, I'm sure I can use numpy to do this, but I just want to know if there's a way to do this with the decimal module out of curiosity.</li>
</ol>
| 4 | 2008-09-27T18:47:54Z | 144,573 | <p>Changing the decimal working precision to 2 digits is <em>not</em> a good idea, unless you absolutely only are going to perform a single operation.</p>
<p>You should always perform calculations at higher precision than the level of significance, and only round the final result. If you perform a long sequence of calculations and round to the number of significant digits at each step, errors will accumulate. The decimal module doesn't know whether any particular operation is one in a long sequence, or the final result, so it assumes that it shouldn't round more than necessary. Ideally it would use infinite precision, but that is too expensive so the Python developers settled for 28 digits.</p>
<p>Once you've arrived at the final result, what you probably want is quantize:</p>
<pre>
>>> (Decimal('1.00') / Decimal('3.00')).quantize(Decimal("0.001"))
Decimal("0.333")
</pre>
<p>You have to keep track of significance manually. If you want automatic significance tracking, you should use interval arithmetic. There are some libraries available for Python, including <a href="http://pyinterval.googlecode.com/">pyinterval</a> and <a href="http://code.google.com/p/mpmath/">mpmath</a> (which supports arbitrary precision). It is also straightforward to implement interval arithmetic with the decimal library, since it supports directed rounding.</p>
<p>You may also want to read the <a href="http://speleotrove.com/decimal/decifaq4.html#signif">Decimal Arithmetic FAQ: Is the decimal arithmetic âsignificanceâ arithmetic?</a></p>
| 6 | 2008-09-27T22:00:35Z | [
"python",
"floating-point",
"decimal",
"physics",
"significance"
] |
Significant figures in the decimal module | 144,218 | <p>So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:</p>
<pre><code>from decimal import Decimal
>>> Decimal('1.0') + Decimal('2.0')
Decimal("3.0")
</code></pre>
<p>But this doesn't:</p>
<pre><code>>>> Decimal('1.00') / Decimal('3.00')
Decimal("0.3333333333333333333333333333")
</code></pre>
<p>So two questions:</p>
<ol>
<li>Am I right that this isn't the expected amount of significant digits, or do I need to brush up on significant digit math?</li>
<li>Is there any way to do this without having to set the decimal precision manually? Granted, I'm sure I can use numpy to do this, but I just want to know if there's a way to do this with the decimal module out of curiosity.</li>
</ol>
| 4 | 2008-09-27T18:47:54Z | 719,519 | <p>Just out of curiosity...is it necessary to use the decimal module? Why not floating point with a significant-figures rounding of numbers when you are ready to see them? Or are you trying to keep track of the significant figures of the computation (like when you have to do an error analysis of a result, calculating the computed error as a function of the uncertainties that went into the calculation)? If you want a rounding function that rounds from the left of the number instead of the right, try:</p>
<pre><code>def lround(x,leadingDigits=0):
"""Return x either as 'print' would show it (the default)
or rounded to the specified digit as counted from the leftmost
non-zero digit of the number, e.g. lround(0.00326,2) --> 0.0033
"""
assert leadingDigits>=0
if leadingDigits==0:
return float(str(x)) #just give it back like 'print' would give it
return float('%.*e' % (int(leadingDigits),x)) #give it back as rounded by the %e format
</code></pre>
<p>The numbers will look right when you print them or convert them to strings, but if you are working at the prompt and don't explicitly print them they may look a bit strange:</p>
<pre><code>>>> lround(1./3.,2),str(lround(1./3.,2)),str(lround(1./3.,4))
(0.33000000000000002, '0.33', '0.3333')
</code></pre>
| 1 | 2009-04-05T19:23:02Z | [
"python",
"floating-point",
"decimal",
"physics",
"significance"
] |
Python PostgreSQL modules. Which is best? | 144,448 | <p>I've seen a number of postgresql modules for python like pygresql, pypgsql, psyco. Most of them are Python DB API 2.0 compliant, some are not being actively developed anymore.
Which module do you recommend? Why?</p>
| 20 | 2008-09-27T20:55:04Z | 144,462 | <p>psycopg2 seems to be the most popular. I've never had any trouble with it. There's actually a pure Python interface for PostgreSQL too, called <a href="http://barryp.org/software/bpgsql/">bpgsql</a>. I wouldn't recommend it over psycopg2, but it's recently become capable enough to support Django and is useful if you can't compile C modules.</p>
| 15 | 2008-09-27T21:00:21Z | [
"python",
"postgresql",
"module"
] |
Python PostgreSQL modules. Which is best? | 144,448 | <p>I've seen a number of postgresql modules for python like pygresql, pypgsql, psyco. Most of them are Python DB API 2.0 compliant, some are not being actively developed anymore.
Which module do you recommend? Why?</p>
| 20 | 2008-09-27T20:55:04Z | 145,801 | <p>Psycopg1 is known for better performance in heavilyy threaded environments (like web applications) than Psycopg2, although not maintained. Both are well written and rock solid, I'd choose one of these two depending on use case.</p>
| 1 | 2008-09-28T13:04:17Z | [
"python",
"postgresql",
"module"
] |
Python PostgreSQL modules. Which is best? | 144,448 | <p>I've seen a number of postgresql modules for python like pygresql, pypgsql, psyco. Most of them are Python DB API 2.0 compliant, some are not being actively developed anymore.
Which module do you recommend? Why?</p>
| 20 | 2008-09-27T20:55:04Z | 1,550,328 | <p>I suggest Psycopg over Psycopg2 since the first one seems a bit more sable. At least in my experience. I have an application running 24/7 and sometimes I was getting random memory crashes (double free or corruption errors) from Psycopg2. Nothing I could have debug fast or easily since it's not a Python error but a C error. I just switched over to Pyscopg and I did not get any crashes after that.</p>
<p>Also, as said in an other post, <a href="http://barryp.org/software/bpgsql/" rel="nofollow">bpgsql</a> seems a very good alternative. It's stable and easy to use since you don't need to compile it. The only bad side is that library is not threadsafe.</p>
<p>Pygresql seems nice, there's a more direct way to query the database with this library. But I don't know how stable this one is though.</p>
| 2 | 2009-10-11T10:06:27Z | [
"python",
"postgresql",
"module"
] |
Python PostgreSQL modules. Which is best? | 144,448 | <p>I've seen a number of postgresql modules for python like pygresql, pypgsql, psyco. Most of them are Python DB API 2.0 compliant, some are not being actively developed anymore.
Which module do you recommend? Why?</p>
| 20 | 2008-09-27T20:55:04Z | 1,579,851 | <p>I uses only psycopg2 and had no problems with that. </p>
| 0 | 2009-10-16T19:10:43Z | [
"python",
"postgresql",
"module"
] |
Python PostgreSQL modules. Which is best? | 144,448 | <p>I've seen a number of postgresql modules for python like pygresql, pypgsql, psyco. Most of them are Python DB API 2.0 compliant, some are not being actively developed anymore.
Which module do you recommend? Why?</p>
| 20 | 2008-09-27T20:55:04Z | 36,021,904 | <p>I've used pg8000 without any problems in the past 3 years. It's uptodate and available on pypi and works on both python2 and python3. You can use "pip install pg8000" to quickly get it (don't forget to use --proxy=yourproxy:yourport if you're behind a firewall).</p>
<p>If you're worried about thread safety, it also provides a score for thread safety (see: <a href="http://pybrary.net/pg8000/dbapi.html" rel="nofollow">http://pybrary.net/pg8000/dbapi.html</a> and <a href="https://www.python.org/dev/peps/pep-0249/" rel="nofollow">https://www.python.org/dev/peps/pep-0249/</a> for definitions of the different levels of thread safety) (although I have no yet used threads with psql).</p>
| 0 | 2016-03-15T20:54:06Z | [
"python",
"postgresql",
"module"
] |
Something like Explorer's icon grid view in a Python GUI | 145,155 | <p>I am making a Python gui project that needs to duplicate the look of a Windows gui environment (ie Explorer). I have my own custom icons to draw but they should be selectable by the same methods as usual; click, ctrl-click, drag box etc. Are any of the gui toolkits going to help with this or will I have to implement it all myself. If there aren't any tools to help with this advice would be greatly appreciated.</p>
<p><em>edit</em> I am not trying to recreate explorer, that would be madness. I simply want to be able to take icons and lay them out in a scrollable window. Any number of them may be selected at once. It would be great if there was something that could select/deselect them in the same (appearing at least) way that Windows does. Then all I would need is a list of all the selected icons.</p>
| 2 | 2008-09-28T03:39:35Z | 145,161 | <p>I'll assume you're serious and suggest that you check out the many wonderful <a href="http://wiki.python.org/moin/GuiProgramming" rel="nofollow">GUI libraries</a> available for Python.</p>
| 1 | 2008-09-28T03:44:07Z | [
"python",
"user-interface"
] |
Something like Explorer's icon grid view in a Python GUI | 145,155 | <p>I am making a Python gui project that needs to duplicate the look of a Windows gui environment (ie Explorer). I have my own custom icons to draw but they should be selectable by the same methods as usual; click, ctrl-click, drag box etc. Are any of the gui toolkits going to help with this or will I have to implement it all myself. If there aren't any tools to help with this advice would be greatly appreciated.</p>
<p><em>edit</em> I am not trying to recreate explorer, that would be madness. I simply want to be able to take icons and lay them out in a scrollable window. Any number of them may be selected at once. It would be great if there was something that could select/deselect them in the same (appearing at least) way that Windows does. Then all I would need is a list of all the selected icons.</p>
| 2 | 2008-09-28T03:39:35Z | 145,162 | <p>Python has extensions for accessing the Win32 API, but good luck trying to re-write explorer in <em>that</em> by yourself. Your best bet is to use a toolkit like <a href="http://doc.trolltech.com/4.4/gallery-windowsxp.html" rel="nofollow">Qt</a>, but you'll still have to write the vast majority of the application from scratch.</p>
<p>Is there any way you can re-use explorer itself in your project?</p>
<p><hr /></p>
<p>Updated for edited question:</p>
<p><a href="http://www.gtk.org/" rel="nofollow">GTK+</a> has an <a href="http://library.gnome.org/devel/gtk/unstable/GtkIconView.html" rel="nofollow">icon grid widget</a> that you could use. See a reference for <a href="http://www.pygtk.org/" rel="nofollow">PyGTK+</a>: <a href="http://www.pygtk.org/docs/pygtk/class-gtkiconview.html" rel="nofollow"><code>gtk.IconView</code></a></p>
| 3 | 2008-09-28T03:45:09Z | [
"python",
"user-interface"
] |
Something like Explorer's icon grid view in a Python GUI | 145,155 | <p>I am making a Python gui project that needs to duplicate the look of a Windows gui environment (ie Explorer). I have my own custom icons to draw but they should be selectable by the same methods as usual; click, ctrl-click, drag box etc. Are any of the gui toolkits going to help with this or will I have to implement it all myself. If there aren't any tools to help with this advice would be greatly appreciated.</p>
<p><em>edit</em> I am not trying to recreate explorer, that would be madness. I simply want to be able to take icons and lay them out in a scrollable window. Any number of them may be selected at once. It would be great if there was something that could select/deselect them in the same (appearing at least) way that Windows does. Then all I would need is a list of all the selected icons.</p>
| 2 | 2008-09-28T03:39:35Z | 145,174 | <p>In wxPython there's a plethora of ready-made list and tree controls (CustomTreeCtrl, TreeListCtrl, and others), a mixture of which you can use to create a simple explorer in minutes. The wxPython demo even has a few relevant examples (see the demo of MVCTree).</p>
| 2 | 2008-09-28T03:56:32Z | [
"python",
"user-interface"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 145,283 | <p>The quickest way to do this is using <a href="http://www.swig.org/">SWIG</a>.</p>
<p>Example from SWIG <a href="http://www.swig.org/tutorial.html">tutorial</a>:</p>
<pre><code>/* File : example.c */
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
</code></pre>
<p>Interface file:</p>
<pre><code>/* example.i */
%module example
%{
/* Put header files here or function declarations like below */
extern int fact(int n);
%}
extern int fact(int n);
</code></pre>
<p>Building a Python module on Unix:</p>
<pre><code>swig -python example.i
gcc -fPIC -c example.c example_wrap.c -I/usr/local/include/python2.7
gcc -shared example.o example_wrap.o -o _example.so
</code></pre>
<p>Usage:</p>
<pre><code>>>> import example
>>> example.fact(5)
120
</code></pre>
<p>Note that you have to have python-dev. Also in some systems python header files will be in /usr/include/python2.7 based on the way you have installed it.</p>
<p>From the tutorial:</p>
<blockquote>
<p>SWIG is a fairly complete C++ compiler with support for nearly every language feature. This includes preprocessing, pointers, classes, inheritance, and even C++ templates. SWIG can also be used to package structures and classes into proxy classes in the target language â exposing the underlying functionality in a very natural manner.</p>
</blockquote>
| 23 | 2008-09-28T05:44:11Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 145,287 | <p>Iâve never used it but Iâve heard good things about <a href="https://docs.python.org/3.6/library/ctypes.html">ctypes</a>. If youâre trying to use it with C++, be sure to evade name mangling via <a href="http://stackoverflow.com/q/1041866/2157640"><code>extern "C"</code></a>. <em>Thanks for the comment, Florian Bösch.</em></p>
| 12 | 2008-09-28T05:48:59Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 145,305 | <p><a href="http://openwetware.org/wiki/Julius_B._Lucks/Projects/Python_All_A_Scientist_Needs">This paper, claiming python to be all a scientist needs,</a> basically says: first prototype everything in Python. Then when you need to speed a part up, use SWIG and translate this part to C.</p>
| 9 | 2008-09-28T06:00:56Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 145,347 | <p>One of the official Python documents contains details on <a href="https://docs.python.org/3.6/extending/" rel="nofollow">extending Python using C/C++</a>.
Even without the use of <a href="http://www.swig.org/" rel="nofollow">SWIG</a>, itâs quite straightforward and works perfectly well on Windows.</p>
| 2 | 2008-09-28T06:28:08Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 145,384 | <p>Check out <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/">pyrex</a> or <a href="http://cython.org/">cython</a>. They're python-like languages for interfacing between C/C++ and python.</p>
| 16 | 2008-09-28T06:53:18Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 145,436 | <p>You should have a look at <a href="http://www.boost.org/doc/libs/1_49_0/libs/python/doc/">Boost.Python</a>, here is the short introdution taken from their website:</p>
<blockquote>
<p>The Boost Python Library is a framework for interfacing Python and
C++. It allows you to quickly and seamlessly expose C++ classes
functions and objects to Python, and vice-versa, using no special
tools -- just your C++ compiler. It is designed to wrap C++ interfaces
non-intrusively, so that you should not have to change the C++ code at
all in order to wrap it, making Boost.Python ideal for exposing
3rd-party libraries to Python. The library's use of advanced
metaprogramming techniques simplifies its syntax for users, so that
wrapping code takes on the look of a kind of declarative interface
definition language (IDL).</p>
</blockquote>
| 69 | 2008-09-28T07:51:37Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 145,649 | <p>I like <a href="http://docs.python.org/2/library/ctypes.html">ctypes</a> a lot, <a href="http://www.swig.org/">swig</a> always tended to give me <a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/d94badd9847fe43a?pli=1">problems</a>. Also ctypes has the advantage that you don't need to satisfy any compile time dependency on python, and your binding will work on any python that has ctypes, not just the one it was compiled against.</p>
<p>Suppose you have a simple C++ example class you want to talk to in a file called foo.cpp:</p>
<pre><code>#include <iostream>
class Foo{
public:
void bar(){
std::cout << "Hello" << std::endl;
}
};
</code></pre>
<p>Since ctypes can only talk to C functions, you need to provide those declaring them as extern "C"</p>
<pre><code>extern "C" {
Foo* Foo_new(){ return new Foo(); }
void Foo_bar(Foo* foo){ foo->bar(); }
}
</code></pre>
<p>Next you have to compile this to a shared library</p>
<pre><code>g++ -c -fPIC foo.cpp -o foo.o
g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o
</code></pre>
<p>And finally you have to write your python wrapper (e.g. in fooWrapper.py)</p>
<pre><code>from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')
class Foo(object):
def __init__(self):
self.obj = lib.Foo_new()
def bar(self):
lib.Foo_bar(self.obj)
</code></pre>
<p>Once you have that you can call it like</p>
<pre><code>f = Foo()
f.bar() #and you will see "Hello" on the screen
</code></pre>
| 339 | 2008-09-28T10:53:31Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 19,786,993 | <p>I think cffi for python can be an option.</p>
<blockquote>
<p>The goal is to call C code from Python. You should be able to do so
without learning a 3rd language: every alternative requires you to
learn their own language (Cython, SWIG) or API (ctypes). So we tried
to assume that you know Python and C and minimize the extra bits of
API that you need to learn.</p>
</blockquote>
<p><a href="http://cffi.readthedocs.org/en/release-0.7/">http://cffi.readthedocs.org/en/release-0.7/</a></p>
| 5 | 2013-11-05T10:39:23Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 23,865,947 | <p>I started my journey in the python <-> C++ binding from this page, with the objective of linking high level data types (multidimensional STL vectors with python lists) :-)</p>
<p>Having tried the solutions based on both <a href="https://docs.python.org/2/library/ctypes.html">ctypes</a> and <a href="http://www.boost.org/doc/libs/1_55_0/libs/python/doc/tutorial/doc/html/index.html">boost.python</a> (and not being a software engineer) I have found them complex when high level datatypes binding is required, while I have found <a href="http://swig.org">swig</a> much more simple for such cases.
This example uses therefore SWIG and it has been tested in Linux (but swig is available and is widely used in Windows too).</p>
<p>The objective is to make available to python a C++ function that takes a matrix in form of a 2D STL vector and returns an average of each row (as a 1D STL vector).</p>
<p>The code in C++ ("code.cpp") is as follow:</p>
<pre><code>#include <vector>
#include "code.h"
using namespace std;
vector<double> average (vector< vector<double> > i_matrix) {
// compute average of each row..
vector <double> averages;
for (int r = 0; r < i_matrix.size(); r++){
double rsum = 0.0;
double ncols= i_matrix[r].size();
for (int c = 0; c< i_matrix[r].size(); c++){
rsum += i_matrix[r][c];
}
averages.push_back(rsum/ncols);
}
return averages;
}
</code></pre>
<p>The equivalent header ("code.h") is:</p>
<pre><code>#ifndef _code
#define _code
#include <vector>
std::vector<double> average (std::vector< std::vector<double> > i_matrix);
#endif
</code></pre>
<p>We first compile the C++ code to create an object file:</p>
<pre><code>g++ -c -fPIC code.cpp
</code></pre>
<p>We then define a <a href="http://swig.org/Doc3.0/SWIG.html">swig interface definition file</a> ("code.i") for our C++ functions.</p>
<pre><code>%module code
%{
#include "code.h"
%}
%include "std_vector.i"
namespace std {
/* On a side note, the names VecDouble and VecVecdouble can be changed, but the order of first the inner vector matters !*/
%template(VecDouble) vector<double>;
%template(VecVecdouble) vector< vector<double> >;
}
%include "code.h"
</code></pre>
<p>Using swig, we generate a C++ interface source code from the swig interface definition file..</p>
<pre><code>swig -c++ -python code.i
</code></pre>
<p>We finally compile the generated C++ interface source file and link everything together to generate a shared library that is directly importable by python (the "_" matters):</p>
<pre><code>g++ -c -fPIC code_wrap.cxx -I/usr/include/python2.7 -I/usr/lib/python2.7
g++ -shared -Wl,-soname,_code.so -o _code.so code.o code_wrap.o
</code></pre>
<p>We can now use the function in python scripts:</p>
<pre><code>#!/usr/bin/env python
import code
a= [[3,5,7],[8,10,12]]
print a
b = code.average(a)
print "Assignment done"
print a
print b
</code></pre>
| 18 | 2014-05-26T08:30:54Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 29,853,756 | <p>First you should decide what is your particular purpose. The official Python documentation on <a href="https://docs.python.org/2/extending/" rel="nofollow">extending and embedding the Python interpreter</a> was mentioned above, I can add a good <a href="https://python-packaging-user-guide.readthedocs.org/en/latest/extensions.html" rel="nofollow">overview of binary extensions</a>. The use cases can be divided into 3 categories:</p>
<ul>
<li><strong>accelerator modules</strong>: to run faster than the equivalent pure Python code runs in CPython.</li>
<li><strong>wrapper modules</strong>: to expose existing C interfaces to Python code.</li>
<li><strong>low level system access</strong>: to access lower level features of the CPython runtime, the operating system, or the underlying hardware.</li>
</ul>
<p>In order to give some broader perspective for other interested and since your initial question is a bit vague ("to a C or C++ library") I think this information might be interesting to you. On the link above you can read on disadvantages of using binary extensions and its alternatives. </p>
<p>Apart from the other answers suggested, if you want an accelerator module, you can try <a href="http://numba.pydata.org/" rel="nofollow">Numba</a>. It works "by generating optimized machine code using the LLVM compiler infrastructure at import time, runtime, or statically (using the included pycc tool)". </p>
| 2 | 2015-04-24T17:23:23Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 32,264,764 | <p>The question is how to call a C function from Python, if I understood correctly. Then the best bet are Ctypes (BTW portable across all variants of Python).</p>
<pre><code>>>> from ctypes import *
>>> libc = cdll.msvcrt
>>> print libc.time(None)
1438069008
>>> printf = libc.printf
>>> printf("Hello, %s\n", "World!")
Hello, World!
14
>>> printf("%d bottles of beer\n", 42)
42 bottles of beer
19
</code></pre>
<p>For a detailed guide you may want to refer to <a href="http://myunixworld.blogspot.in/2015/07/how-python-can-talk-to-other-language.html" rel="nofollow">my blog article</a>.</p>
| 2 | 2015-08-28T06:38:12Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 34,515,909 | <p>Cython is definitely the way to go, unless you anticipate writing Java wrappers, in which case SWIG may be preferable. </p>
<p>I recommend using the <code>runcython</code> command line utility, it makes the process of using Cython extremely easy. If you need to pass structured data to C++, take a look at Google's protobuf library, it's very convenient. </p>
<p>Here is a minimal examples I made that uses both tools: </p>
<p><a href="https://github.com/nicodjimenez/python2cpp" rel="nofollow">https://github.com/nicodjimenez/python2cpp</a></p>
<p>Hope it can be a useful starting point. </p>
| 1 | 2015-12-29T17:27:16Z | [
"c++",
"python",
"c"
] |
Calling C/C++ from python? | 145,270 | <p>What would be the quickest way to construct a python binding to a C or C++ library?</p>
<p>(using windows if this matters)</p>
| 270 | 2008-09-28T05:34:20Z | 38,542,539 | <p>There is also <code>pybind11</code>, which is like a lightweight version of <code>Boost</code> and compatible with all modern C++ compilers : </p>
<p><a href="https://pybind11.readthedocs.io/en/latest/" rel="nofollow">https://pybind11.readthedocs.io/en/latest/</a> </p>
| 1 | 2016-07-23T13:53:34Z | [
"c++",
"python",
"c"
] |
Text difference algorithm | 145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| 42 | 2008-09-28T10:12:25Z | 145,609 | <p>Look at <a href="http://docs.python.org/lib/module-difflib.html" rel="nofollow">difflib</a>. (Python)</p>
<p>That will calculate the diffs in various formats. You could then use the size of the context diff as a measure of how different two documents are?</p>
| 23 | 2008-09-28T10:14:43Z | [
"c#",
"python",
"diff"
] |
Text difference algorithm | 145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| 42 | 2008-09-28T10:12:25Z | 145,623 | <p>If you need a finer granularity than lines, you can use Levenshtein distance. Levenshtein distance is a straight-forward measure on how to similar two texts are.<br />
You can also use it to extract the edit logs and can a very fine-grained diff, similar to that on the edit history pages of SO.
Be warned though that Levenshtein distance can be quite CPU- and memory-intensive to calculate, so using difflib,as Douglas Leder suggested, is most likely going to be faster.</p>
<p>Cf. also <a href="http://stackoverflow.com/questions/132478/how-to-perform-string-diffs-in-java#132547">this answer</a>.</p>
| 5 | 2008-09-28T10:27:49Z | [
"c#",
"python",
"diff"
] |
Text difference algorithm | 145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| 42 | 2008-09-28T10:12:25Z | 145,632 | <p>As stated, use difflib. Once you have the diffed output, you may find the <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow">Levenshtein distance</a> of the different strings as to give a "value" of how different they are.</p>
| 2 | 2008-09-28T10:33:09Z | [
"c#",
"python",
"diff"
] |
Text difference algorithm | 145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| 42 | 2008-09-28T10:12:25Z | 145,634 | <p><a href="http://bazaar-vcs.org/" rel="nofollow">Bazaar</a> contains an alternative difference algorithm, called <a href="http://bramcohen.livejournal.com/37690.html" rel="nofollow">patience diff</a> (there's more info in the comments on that page) which is claimed to be better than the traditional diff algorithm. The file 'patiencediff.py' in the bazaar distribution is a simple command line front end.</p>
| 10 | 2008-09-28T10:35:02Z | [
"c#",
"python",
"diff"
] |
Text difference algorithm | 145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| 42 | 2008-09-28T10:12:25Z | 145,659 | <p>I can recommend to take a look at Neil Fraser's code and articles:</p>
<p><a href="http://code.google.com/p/google-diff-match-patch/">google-diff-match-patch</a></p>
<blockquote>
<p>Currently available in Java,
JavaScript, C++ and Python. Regardless
of language, each library features the
same API and the same functionality.
All versions also have comprehensive
test harnesses.</p>
</blockquote>
<p><a href="http://neil.fraser.name/writing/diff/">Neil Fraser: Diff Strategies</a> - for theory and implementation notes</p>
| 30 | 2008-09-28T11:04:31Z | [
"c#",
"python",
"diff"
] |
Text difference algorithm | 145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| 42 | 2008-09-28T10:12:25Z | 146,530 | <p>There are a number of distance metrics, as paradoja mentioned there is the Levenshtein distance, but there is also <a href="http://en.wikipedia.org/wiki/New_York_State_Identification_and_Intelligence_System" rel="nofollow">NYSIIS</a> and <a href="http://en.wikipedia.org/wiki/Soundex" rel="nofollow">Soundex</a>. In terms of Python implementations, I have used <a href="http://www.mindrot.org/projects/py-editdist/" rel="nofollow">py-editdist</a> and <a href="http://advas.sourceforge.net/" rel="nofollow">ADVAS</a> before. Both are nice in the sense that you get a single number back as a score. Check out ADVAS first, it implements a bunch of algorithms.</p>
| 3 | 2008-09-28T19:21:45Z | [
"c#",
"python",
"diff"
] |
Text difference algorithm | 145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| 42 | 2008-09-28T10:12:25Z | 146,957 | <p>In Python, there is <a href="http://docs.python.org/lib/module-difflib.html">difflib</a>, as also others have suggested.</p>
<p><code>difflib</code> offers the <a href="http://docs.python.org/lib/sequence-matcher.html">SequenceMatcher</a> class, which can be used to give you a similarity ratio. Example function:</p>
<pre><code>def text_compare(text1, text2, isjunk=None):
return difflib.SequenceMatcher(isjunk, text1, text2).ratio()
</code></pre>
| 25 | 2008-09-28T23:02:33Z | [
"c#",
"python",
"diff"
] |
Text difference algorithm | 145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| 42 | 2008-09-28T10:12:25Z | 478,615 | <p>My current understanding is that the best solution to the Shortest Edit Script (SES) problem is Myers "middle-snake" method with the Hirschberg linear space refinement.</p>
<p>The Myers algorithm is described in:</p>
<blockquote>
<p>E. Myers, ``An O(ND) Difference
Algorithm and Its Variations,''<br>
Algorithmica 1, 2 (1986), 251-266.</p>
</blockquote>
<p>The GNU diff utility uses the Myers algorithm.</p>
<p>The "similarity score" you speak of is called the "edit distance" in the literature which is the number of inserts or deletes necessary to transform one sequence into the other.</p>
<p>Note that a number of people have cited the Levenshtein distance algorithm but that is, albeit easy to implement, not the optimal solution as it is inefficient (requires the use of a possibly huge n*m matrix) and does not provide the "edit script" which is the sequence of edits that could be used to transform one sequence into the other and vice versa.</p>
<p>For a good Myers / Hirschberg implementation look at:</p>
<p><a href="http://www.ioplex.com/~miallen/libmba/dl/src/diff.c" rel="nofollow">http://www.ioplex.com/~miallen/libmba/dl/src/diff.c</a></p>
<p>The particular library that it is contained within is no longer maintained but to my knowledge the diff.c module itself is still correct.</p>
<p>Mike</p>
| 8 | 2009-01-26T00:44:40Z | [
"c#",
"python",
"diff"
] |
Text difference algorithm | 145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| 42 | 2008-09-28T10:12:25Z | 1,937,762 | <p>You could use the <a href="http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution" rel="nofollow">solution to the Longest Common Subsequence (LCS) problem</a>. See also the discussion about possible ways to optimize this solution.</p>
| 1 | 2009-12-21T01:31:09Z | [
"c#",
"python",
"diff"
] |
Text difference algorithm | 145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| 42 | 2008-09-28T10:12:25Z | 1,937,776 | <p>One method I've employed for a different functionality, to calculate how much data was new in a modified file, could perhaps work for you as well.</p>
<p>I have a diff/patch implementation C# that allows me to take two files, presumably old and new version of the same file, and calculate the "difference", but not in the usual sense of the word. Basically I calculate a set of operations that I can perform on the old version to update it to have the same contents as the new version.</p>
<p>To use this for the functionality initially described, to see how much data was new, I simple ran through the operations, and for every operation that copied from the old file verbatim, that had a 0-factor, and every operation that inserted new text (distributed as part of the patch, since it didn't occur in the old file) had a 1-factor. All characters was given this factory, which gave me basically a long list of 0's and 1's.</p>
<p>All I then had to do was to tally up the 0's and 1's. In your case, with my implementation, a low number of 1's compared to 0's would mean the files are very similar.</p>
<p>This implementation would also handle cases where the modified file had inserted copies from the old file out of order, or even duplicates (ie. you copy a part from the start of the file and paste it near the bottom), since they would both be copies of the same original part from the old file.</p>
<p>I experimented with weighing copies, so that the first copy counted as 0, and subsequent copies of the same characters had progressively higher factors, in order to give a copy/paste operation some "new-factor", but I never finished it as the project was scrapped.</p>
<p>If you're interested, my diff/patch code is available from my Subversion repository.</p>
| 0 | 2009-12-21T01:39:30Z | [
"c#",
"python",
"diff"
] |
Text difference algorithm | 145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| 42 | 2008-09-28T10:12:25Z | 9,992,986 | <p>Take a look at the <a href="http://pypi.python.org/pypi/Fuzzy" rel="nofollow">Fuzzy</a> module. It has fast (written in C) based algorithms for soundex, NYSIIS and double-metaphone.</p>
<p>A good introduction can be found at: <a href="http://www.informit.com/articles/article.aspx?p=1848528" rel="nofollow">http://www.informit.com/articles/article.aspx?p=1848528</a></p>
| 0 | 2012-04-03T12:11:29Z | [
"c#",
"python",
"diff"
] |
How do I successfully pass a function reference to Djangoâs reverse() function? | 146,522 | <p>Iâve got a brand new Django project. Iâve added one minimal view function to <code>views.py</code>, and one URL pattern to <code>urls.py</code>, passing the view by function reference instead of a string:</p>
<pre><code># urls.py
# -------
# coding=utf-8
from django.conf.urls.defaults import *
from myapp import views
urlpatterns = patterns('',
url(r'^myview/$', views.myview),
)
# views.py
----------
# coding=utf-8
from django.http import HttpResponse
def myview(request):
return HttpResponse('MYVIEW LOL', content_type="text/plain")
</code></pre>
<p>Iâm trying to use <code>reverse()</code> to get the URL, by passing it a function reference. But Iâm not getting a match, despite confirming that the view function Iâm passing to reverse is the exact same view function I put in the URL pattern:</p>
<pre><code>>>> from django.core.urlresolvers import reverse
>>> import urls
>>> from myapp import views
>>> urls.urlpatterns[0].callback is views.myview
True
>>> reverse(views.myview)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 254, in reverse
*args, **kwargs)))
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 243, in reverse
"arguments '%s' not found." % (lookup_view, args, kwargs))
NoReverseMatch: Reverse for '<function myview at 0x6fe6b0>' with arguments '()' and keyword arguments '{}' not found.
</code></pre>
<p>As far as I can tell from the documentation, function references should be fine in both the URL pattern and <code>reverse()</code>.</p>
<ul>
<li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#passing-callable-objects-instead-of-strings">URL patterns with function references</a></li>
<li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse"><code>reverse</code> with function references</a></li>
</ul>
<p>Iâm using the Django trunk, revision 9092.</p>
| 8 | 2008-09-28T19:15:15Z | 146,524 | <p>Got it!! The problem is that some of the imports are of <code>myproject.myapp.views</code>, and some are just of <code>myapp.views</code>. This is confusing the Python module system enough that it no longer detects the functions as the same object. This is because your main <code>settings.py</code> probably has a line like:</p>
<pre><code>ROOT_URLCONF = `myproject.urls`
</code></pre>
<p>To solve this, try using the full import in your shell session:</p>
<pre><code>>>> from django.core.urlresolvers import reverse
>>> from myproject.myapp import views
>>> reverse(views.myview)
'/myview/'
</code></pre>
<p>Here's a log of the debugging session, for any interested future readers:</p>
<pre><code>>>> from django.core import urlresolvers
>>> from myapp import myview
>>> urlresolvers.get_resolver (None).reverse_dict
{None: ([(u'myview/', [])], 'myview/$'), <function myview at 0x845d17c>: ([(u'myview/', [])], 'myview/$')}
>>> v1 = urlresolvers.get_resolver (None).reverse_dict.items ()[1][0]
>>> reverse(v1)
'/myview/'
>>> v1 is myview
False
>>> v1.__module__
'testproject.myapp.views'
>>> myview.__module__
'myapp.views'
</code></pre>
<p>What happens if you change the URL match to be <code>r'^myview/$'</code>?</p>
<p><hr /></p>
<p>Have you tried it with the view name? Something like <code>reverse ('myapp.myview')</code>?</p>
<p>Is <code>urls.py</code> the root URLconf, or in the <code>myapp</code> application? There needs to be a full path from the root to a view for it to be resolved. If that's <code>myproject/myapp/urls.py</code>, then in <code>myproject/urls.py</code> you'll need code like this:</p>
<pre><code>from django.conf.urls.defaults import patterns
urlpatterns = patterns ('',
(r'^/', 'myapp.urls'),
)
</code></pre>
| 8 | 2008-09-28T19:17:44Z | [
"python",
"django"
] |
How do I successfully pass a function reference to Djangoâs reverse() function? | 146,522 | <p>Iâve got a brand new Django project. Iâve added one minimal view function to <code>views.py</code>, and one URL pattern to <code>urls.py</code>, passing the view by function reference instead of a string:</p>
<pre><code># urls.py
# -------
# coding=utf-8
from django.conf.urls.defaults import *
from myapp import views
urlpatterns = patterns('',
url(r'^myview/$', views.myview),
)
# views.py
----------
# coding=utf-8
from django.http import HttpResponse
def myview(request):
return HttpResponse('MYVIEW LOL', content_type="text/plain")
</code></pre>
<p>Iâm trying to use <code>reverse()</code> to get the URL, by passing it a function reference. But Iâm not getting a match, despite confirming that the view function Iâm passing to reverse is the exact same view function I put in the URL pattern:</p>
<pre><code>>>> from django.core.urlresolvers import reverse
>>> import urls
>>> from myapp import views
>>> urls.urlpatterns[0].callback is views.myview
True
>>> reverse(views.myview)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 254, in reverse
*args, **kwargs)))
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 243, in reverse
"arguments '%s' not found." % (lookup_view, args, kwargs))
NoReverseMatch: Reverse for '<function myview at 0x6fe6b0>' with arguments '()' and keyword arguments '{}' not found.
</code></pre>
<p>As far as I can tell from the documentation, function references should be fine in both the URL pattern and <code>reverse()</code>.</p>
<ul>
<li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#passing-callable-objects-instead-of-strings">URL patterns with function references</a></li>
<li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse"><code>reverse</code> with function references</a></li>
</ul>
<p>Iâm using the Django trunk, revision 9092.</p>
| 8 | 2008-09-28T19:15:15Z | 146,538 | <p>If your two code pastes are complete, then it doesn't look like the second, which makes the actual call to reverse(), ever imports the urls module and therefor if the url mapping is ever actually achieved.</p>
| 1 | 2008-09-28T19:25:49Z | [
"python",
"django"
] |
I'm using Python regexes in a criminally inefficient manner | 146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
<p><%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%></p>
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| 7 | 2008-09-28T20:03:14Z | 146,637 | <p>Never create your own programming language. Ever. (I used to have an exception to this rule, but not any more.)</p>
<p>There is always an existing language you can use which suits your needs better. If you elaborated on your use-case, people may help you select a suitable language.</p>
| 2 | 2008-09-28T20:19:40Z | [
"regex",
"algorithm",
"optimization",
"python"
] |
I'm using Python regexes in a criminally inefficient manner | 146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
<p><%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%></p>
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| 7 | 2008-09-28T20:03:14Z | 146,639 | <p>You can match both kind of quotes in one go with <code>r"(\"|')(.*?)\1"</code> - the <code>\1</code> refers to the first group, so it will only match matching quotes.</p>
| 1 | 2008-09-28T20:20:03Z | [
"regex",
"algorithm",
"optimization",
"python"
] |
I'm using Python regexes in a criminally inefficient manner | 146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
<p><%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%></p>
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| 7 | 2008-09-28T20:03:14Z | 146,646 | <p>Don't call search twice in a row (in the loop conditional, and the first statement in the loop). Call (and cache the result) once before the loop, and then in the final statement of the loop.</p>
| 0 | 2008-09-28T20:22:31Z | [
"regex",
"algorithm",
"optimization",
"python"
] |
I'm using Python regexes in a criminally inefficient manner | 146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
<p><%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%></p>
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| 7 | 2008-09-28T20:03:14Z | 146,649 | <p>You're calling re.compile quite a bit. A global variable for these wouldn't hurt here.</p>
| 1 | 2008-09-28T20:23:40Z | [
"regex",
"algorithm",
"optimization",
"python"
] |
I'm using Python regexes in a criminally inefficient manner | 146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
<p><%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%></p>
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| 7 | 2008-09-28T20:03:14Z | 146,671 | <p>The first thing that may improve things is to move the re.compile outside the function. The compilation is cached, but there is a speed hit in checking this to see if its compiled.</p>
<p>Another possibility is to use a single regex as below:</p>
<pre><code>MatchedQuotes = re.compile(r"(['\"])(.*)\1", re.LOCALE)
item = MatchedQuotes.sub(r'\2', item, 1)
</code></pre>
<p>Finally, you can combine this into the regex in processVariables. Taking <a href="http://stackoverflow.com/questions/146607/im-using-python-regexes-in-a-criminally-inefficient-manner#146683">Torsten Marek's</a> suggestion to use a function for re.sub, this improves and simplifies things dramatically.</p>
<pre><code>VariableDefinition = re.compile(r'<%(["\']?)(.*?)\1=(["\']?)(.*?)\3%>', re.LOCALE)
VarRepl = re.compile(r'<%(["\']?)(.*?)\1%>', re.LOCALE)
def processVariables(item):
vars = {}
def findVars(m):
vars[m.group(2).upper()] = m.group(4)
return ""
item = VariableDefinition.sub(findVars, item)
return VarRepl.sub(lambda m: vars[m.group(2).upper()], item)
print processVariables('<%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%>')
</code></pre>
<p>Here are my timings for 100000 runs:</p>
<pre><code>Original : 13.637
Global regexes : 12.771
Single regex : 9.095
Final version : 1.846
</code></pre>
<p>[Edit] Add missing non-greedy specifier</p>
<p>[Edit2] Added .upper() calls so case insensitive like original version</p>
| 10 | 2008-09-28T20:31:44Z | [
"regex",
"algorithm",
"optimization",
"python"
] |
I'm using Python regexes in a criminally inefficient manner | 146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
<p><%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%></p>
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| 7 | 2008-09-28T20:03:14Z | 146,683 | <p><a href="http://docs.python.org/lib/node46.html" rel="nofollow"><code>sub</code></a> can take a callable as it's argument rather than a simple string. Using that, you can replace all variables with one function call:</p>
<pre><code>>>> import re
>>> var_matcher = re.compile(r'<%(.*?)%>', re.LOCALE)
>>> string = '<%"TITLE"%> <%"SHMITLE"%>'
>>> values = {'"TITLE"': "I am a title.", '"SHMITLE"': "And I am a shmitle."}
>>> var_matcher.sub(lambda m: vars[m.group(1)], string)
'I am a title. And I am a shmitle.
</code></pre>
<p>Follow <a href="#146646" rel="nofollow">eduffy.myopenid.com</a>'s advice and keep the compiled regexes around. </p>
<p>The same recipe can be applied to the first loop, only there you need to store the value of the variable first, and always return <code>""</code> as replacement.</p>
| 3 | 2008-09-28T20:36:43Z | [
"regex",
"algorithm",
"optimization",
"python"
] |
I'm using Python regexes in a criminally inefficient manner | 146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
<p><%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%></p>
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| 7 | 2008-09-28T20:03:14Z | 146,710 | <p>If a regexp only contains one .* wildcard and literals, then you can use find and rfind to locate the opening and closing delimiters.</p>
<p>If it contains only a series of .*? wildcards, and literals, then you can just use a series of find's to do the work.</p>
<p>If the code is time-critical, this switch away from regexp's altogether might give a little more speed.</p>
<p>Also, it looks to me like this is an <a href="http://en.wikipedia.org/wiki/LL_parser" rel="nofollow">LL-parsable language</a>. You could look for a library that can already parse such things for you. You could also use recursive calls to do a one-pass parse -- for example, you could implement your processVariables function to only consume up the first quote, and then call a quote-matching function to consume up to the next quote, etc.</p>
| 1 | 2008-09-28T20:47:53Z | [
"regex",
"algorithm",
"optimization",
"python"
] |
I'm using Python regexes in a criminally inefficient manner | 146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
<p><%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%></p>
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| 7 | 2008-09-28T20:03:14Z | 146,734 | <p>Creating a templating language is all well and good, but shouldn't one of the goals of the templating language be easy readability and efficient parsing? The example you gave seems to be neither.</p>
<p>As Jamie Zawinsky famously said:</p>
<blockquote>
<p>Some people, when confronted with a
problem, think "I know, I'll use
regular expressions!" Now they have
two problems.</p>
</blockquote>
<p>If regular expressions are a solution to a problem you have created, the best bet is not to write a better regular expression, but to redesign your approach to eliminate their use entirely. Regular expressions are complicated, expensive, hugely difficult to maintain, and (ideally) should only be used for working around a problem someone else created.</p>
| 2 | 2008-09-28T21:05:37Z | [
"regex",
"algorithm",
"optimization",
"python"
] |
I'm using Python regexes in a criminally inefficient manner | 146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
<p><%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%></p>
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| 7 | 2008-09-28T20:03:14Z | 146,784 | <p>Why not use XML and XSLT instead of creating your own template language? What you want to do is pretty easy in XSLT.</p>
| -3 | 2008-09-28T21:27:53Z | [
"regex",
"algorithm",
"optimization",
"python"
] |
I'm using Python regexes in a criminally inefficient manner | 146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
<p><%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%></p>
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| 7 | 2008-09-28T20:03:14Z | 146,862 | <p>Why not use <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a>? Seriously. What feature do you require that Mako doesn't have? Perhaps you can adapt or extend something that already works.</p>
| 1 | 2008-09-28T22:07:43Z | [
"regex",
"algorithm",
"optimization",
"python"
] |
In Django, where is the best place to put short snippets of HTML-formatted data? | 146,789 | <p>This question is related to (but perhaps not quite the same as):</p>
<p><a href="http://stackoverflow.com/questions/61451/does-django-have-html-helpers">http://stackoverflow.com/questions/61451/does-django-have-html-helpers</a></p>
<p>My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example:</p>
<p>I have two classes, Person and Address. There are multiple Addresses for each Person, setup likeso (in their respective <strong>models.py</strong>)</p>
<pre><code>class Person(models.Model):
...
class Address(models.Model):
contact = models.ForeignKey(Person)
</code></pre>
<p>Now, whenever I look at a Person, I want to see all their Addresses. So suppose <strong>Persons/views.py</strong> has something likeso:</p>
<pre><code>def detail(request, person_id):
person = get_object_or_404( Person, pk=person_id )
return render_to_response('persons/details.html',
{ 'title' : unicode(person), 'addresses': person.address_set.all() } )
</code></pre>
<p>And, I have a template, <strong>persons/details.html</strong>, with code, for example, like-so:</p>
<pre><code>{% extends "base.html" %}
{% for address in addresses %}
<b>{{ address.name }}</b>
{{ address.type }} <br>
{{ address.street_1 }}<br>
{{ address.street_2 }}<br>
{{ address.city }} {{ address.stateprov }} {{ address.postalcode }}<br>
{{ address.country }}
<hr>
{{ endfor }}
</code></pre>
<p>I am repeating this code quite a bit, often with minor variations, such when it's in a table, and then < br > must be substituted by < /td >< td >. Other times, I don't want a street_2 to display (or the < br > after it). All to say, there is fundamental logic that I want to express, that I am even more loath to tote around with block-and-copy!</p>
<p>What I want is a <strong>persons/details.html</strong> with, for example, the following: </p>
<pre><code>{% extends "base.html" %}
{% for address in addresses %}
{% address.as_html4 %}
{% endfor %}
</code></pre>
<p>And if I want inline table, something likeso (I guess!):</p>
<pre><code>{% extends "base.html" %}
<table><tr>
{% for address in addresses %}
<tr><td> {% address.as_html4 </td><td> %} </td></tr>
{% endfor %}
</table>
</code></pre>
<p>The question is, then: Where is the best place to put the formatting? The logic?</p>
<p>Django seem to have the following (plausible) options:</p>
<ol>
<li><p>Put the formatting in models.py</p></li>
<li><p>Put the logic/formatting in views.py</p></li>
<li><p>Put the logic/formatting in some other sub-class of Person or Address (i.e. addresses/html4.py)</p></li>
<li><p>Create custom tags</p></li>
</ol>
<p>Help / insight much appreciated!</p>
| 8 | 2008-09-28T21:31:21Z | 146,829 | <p>I would use a template tag outputting data using a template html-file a k a <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags" rel="nofollow">inclusion-tag</a></p>
| 2 | 2008-09-28T21:52:19Z | [
"python",
"django",
"model-view-controller",
"design-patterns"
] |
In Django, where is the best place to put short snippets of HTML-formatted data? | 146,789 | <p>This question is related to (but perhaps not quite the same as):</p>
<p><a href="http://stackoverflow.com/questions/61451/does-django-have-html-helpers">http://stackoverflow.com/questions/61451/does-django-have-html-helpers</a></p>
<p>My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example:</p>
<p>I have two classes, Person and Address. There are multiple Addresses for each Person, setup likeso (in their respective <strong>models.py</strong>)</p>
<pre><code>class Person(models.Model):
...
class Address(models.Model):
contact = models.ForeignKey(Person)
</code></pre>
<p>Now, whenever I look at a Person, I want to see all their Addresses. So suppose <strong>Persons/views.py</strong> has something likeso:</p>
<pre><code>def detail(request, person_id):
person = get_object_or_404( Person, pk=person_id )
return render_to_response('persons/details.html',
{ 'title' : unicode(person), 'addresses': person.address_set.all() } )
</code></pre>
<p>And, I have a template, <strong>persons/details.html</strong>, with code, for example, like-so:</p>
<pre><code>{% extends "base.html" %}
{% for address in addresses %}
<b>{{ address.name }}</b>
{{ address.type }} <br>
{{ address.street_1 }}<br>
{{ address.street_2 }}<br>
{{ address.city }} {{ address.stateprov }} {{ address.postalcode }}<br>
{{ address.country }}
<hr>
{{ endfor }}
</code></pre>
<p>I am repeating this code quite a bit, often with minor variations, such when it's in a table, and then < br > must be substituted by < /td >< td >. Other times, I don't want a street_2 to display (or the < br > after it). All to say, there is fundamental logic that I want to express, that I am even more loath to tote around with block-and-copy!</p>
<p>What I want is a <strong>persons/details.html</strong> with, for example, the following: </p>
<pre><code>{% extends "base.html" %}
{% for address in addresses %}
{% address.as_html4 %}
{% endfor %}
</code></pre>
<p>And if I want inline table, something likeso (I guess!):</p>
<pre><code>{% extends "base.html" %}
<table><tr>
{% for address in addresses %}
<tr><td> {% address.as_html4 </td><td> %} </td></tr>
{% endfor %}
</table>
</code></pre>
<p>The question is, then: Where is the best place to put the formatting? The logic?</p>
<p>Django seem to have the following (plausible) options:</p>
<ol>
<li><p>Put the formatting in models.py</p></li>
<li><p>Put the logic/formatting in views.py</p></li>
<li><p>Put the logic/formatting in some other sub-class of Person or Address (i.e. addresses/html4.py)</p></li>
<li><p>Create custom tags</p></li>
</ol>
<p>Help / insight much appreciated!</p>
| 8 | 2008-09-28T21:31:21Z | 146,833 | <p>Sounds like an <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags" rel="nofollow">inclusion tag</a> is what you're looking for. You could have a template and tag for each major variation and use the tag's arguments to customise the context for each template as required.</p>
<p>Basic tag definition:</p>
<pre><code>@register.inclusion_tag('person/address.html')
def display_address(address):
return {'address': address}
</code></pre>
<p>Use in templates (assuming the templatetag module containing it has already been <code>{% load %}</code>-ed):</p>
<pre><code>{% display_address address %}
</code></pre>
| 12 | 2008-09-28T21:53:27Z | [
"python",
"django",
"model-view-controller",
"design-patterns"
] |
In Django, where is the best place to put short snippets of HTML-formatted data? | 146,789 | <p>This question is related to (but perhaps not quite the same as):</p>
<p><a href="http://stackoverflow.com/questions/61451/does-django-have-html-helpers">http://stackoverflow.com/questions/61451/does-django-have-html-helpers</a></p>
<p>My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example:</p>
<p>I have two classes, Person and Address. There are multiple Addresses for each Person, setup likeso (in their respective <strong>models.py</strong>)</p>
<pre><code>class Person(models.Model):
...
class Address(models.Model):
contact = models.ForeignKey(Person)
</code></pre>
<p>Now, whenever I look at a Person, I want to see all their Addresses. So suppose <strong>Persons/views.py</strong> has something likeso:</p>
<pre><code>def detail(request, person_id):
person = get_object_or_404( Person, pk=person_id )
return render_to_response('persons/details.html',
{ 'title' : unicode(person), 'addresses': person.address_set.all() } )
</code></pre>
<p>And, I have a template, <strong>persons/details.html</strong>, with code, for example, like-so:</p>
<pre><code>{% extends "base.html" %}
{% for address in addresses %}
<b>{{ address.name }}</b>
{{ address.type }} <br>
{{ address.street_1 }}<br>
{{ address.street_2 }}<br>
{{ address.city }} {{ address.stateprov }} {{ address.postalcode }}<br>
{{ address.country }}
<hr>
{{ endfor }}
</code></pre>
<p>I am repeating this code quite a bit, often with minor variations, such when it's in a table, and then < br > must be substituted by < /td >< td >. Other times, I don't want a street_2 to display (or the < br > after it). All to say, there is fundamental logic that I want to express, that I am even more loath to tote around with block-and-copy!</p>
<p>What I want is a <strong>persons/details.html</strong> with, for example, the following: </p>
<pre><code>{% extends "base.html" %}
{% for address in addresses %}
{% address.as_html4 %}
{% endfor %}
</code></pre>
<p>And if I want inline table, something likeso (I guess!):</p>
<pre><code>{% extends "base.html" %}
<table><tr>
{% for address in addresses %}
<tr><td> {% address.as_html4 </td><td> %} </td></tr>
{% endfor %}
</table>
</code></pre>
<p>The question is, then: Where is the best place to put the formatting? The logic?</p>
<p>Django seem to have the following (plausible) options:</p>
<ol>
<li><p>Put the formatting in models.py</p></li>
<li><p>Put the logic/formatting in views.py</p></li>
<li><p>Put the logic/formatting in some other sub-class of Person or Address (i.e. addresses/html4.py)</p></li>
<li><p>Create custom tags</p></li>
</ol>
<p>Help / insight much appreciated!</p>
| 8 | 2008-09-28T21:31:21Z | 153,012 | <p>I think template filter will be useful too. You can pass filter on each object, for example:</p>
<pre><code>{{ value|linebreaks }} # standard django filter
</code></pre>
<p>Will produce:</p>
<pre><code>If value is Joel\nis a slug, the output will be <p>Joel<br>is a slug</p>.
</code></pre>
<p>See <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ref-templates-builtins-filters" rel="nofollow">Django Built-in template tags and filters</a> complete reference.</p>
| 1 | 2008-09-30T13:26:16Z | [
"python",
"django",
"model-view-controller",
"design-patterns"
] |
Difflib.SequenceMatcher isjunk optional parameter query: how to ignore whitespaces, tabs, empty lines? | 147,437 | <p>I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use</p>
<pre><code>s=difflib.SequenceMatcher(isjunk,text1,text2)
ratio =s.ratio()
</code></pre>
<p>for this purpose.</p>
<p>So, the question is how to write the lambda expression for this isjunk method so the SequenceMatcher method will discount all the whitespaces, empty lines etc. I tried to use the parameter lambda x: x==" ", but the result isn't as great. For two closely similar text, the ratio is very low. This is highly counter intuitive. </p>
<p>For testing purpose, here are the two strings that you can use on testing:</p>
<blockquote>
<p>What Motivates jwovu to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books despite the fact that I donât
read </p>
<p>programming books. In order to win the
prize you have to write an entry and<br />
what motivatesfggmum to do your job
well. Hence this post. First
motivation </p>
<p>money. I know, this doesnât sound like
a great inspiration to many, and
saying that money is one of the
motivation factors might just blow my
chances away. </p>
<p>As if money is a taboo in programming
world. I know there are people who
canât be motivated by money. Mme, on
the other hand, am living in a real
world, </p>
<p>with house mortgage to pay, myself to
feed and bills to cover. So I canât
really exclude money from my
consideration. If I can get a large
sum of money for </p>
<p>doing a good job, then definitely
boost my morale. I wonât care whether
I am using an old workstation, or
forced to share rooms or cubicle with
other </p>
<p>people, or have to put up with an
annoying boss, or whatever. The fact
that at the end of the day I will walk
off with a large pile of money itself
is enough </p>
<p>for me to overcome all the obstacles,
put up with all the hard feelings and
hurt egos, tolerate a slow computer
and even endure</p>
</blockquote>
<p>And here's another string</p>
<blockquote>
<p>What Motivates You to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books, despite the fact that I don't
read programming books. In order to
win the prize you have to write an
entry and describes what motivates you
to do your job well. Hence this post.</p>
<p>First motivation, money. I know, this
doesn't sound like a great inspiration
to many, and saying that money is one
of the motivation factors might just
blow my chances away. As if money is a
taboo in programming world. I know
there are people who can't be
motivated by money. Kudos to them. Me,
on the other hand, am living in a real
world, with house mortgage to pay,
myself to feed and bills to cover. So
I can't really exclude money from my
consideration.</p>
<p>If I can get a large sum of money for
doing a good job, then thatwill
definitely boost my morale. I won't
care whether I am using an old
workstation, or forced to share rooms
or cubicle with other people, or have
to put up with an annoying boss, or
whatever. The fact that at the end of
the day I will walk off with a large
pile of money itself is enough for me
to overcome all the obstacles, put up
with all the hard feelings and hurt
egos, tolerate a slow computer and
even endure</p>
</blockquote>
<p>I ran the above command, and set the isjunk to lambda x:x==" ", the ratio is only 0.36. </p>
| 2 | 2008-09-29T03:41:45Z | 147,443 | <p>I haven't used Difflib.SequenceMatcher, but have you considered pre-processing the files to remove all blank lines and whitespace (perhaps via regular expressions) and then doing the compare?</p>
| 1 | 2008-09-29T03:47:19Z | [
"python"
] |
Difflib.SequenceMatcher isjunk optional parameter query: how to ignore whitespaces, tabs, empty lines? | 147,437 | <p>I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use</p>
<pre><code>s=difflib.SequenceMatcher(isjunk,text1,text2)
ratio =s.ratio()
</code></pre>
<p>for this purpose.</p>
<p>So, the question is how to write the lambda expression for this isjunk method so the SequenceMatcher method will discount all the whitespaces, empty lines etc. I tried to use the parameter lambda x: x==" ", but the result isn't as great. For two closely similar text, the ratio is very low. This is highly counter intuitive. </p>
<p>For testing purpose, here are the two strings that you can use on testing:</p>
<blockquote>
<p>What Motivates jwovu to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books despite the fact that I donât
read </p>
<p>programming books. In order to win the
prize you have to write an entry and<br />
what motivatesfggmum to do your job
well. Hence this post. First
motivation </p>
<p>money. I know, this doesnât sound like
a great inspiration to many, and
saying that money is one of the
motivation factors might just blow my
chances away. </p>
<p>As if money is a taboo in programming
world. I know there are people who
canât be motivated by money. Mme, on
the other hand, am living in a real
world, </p>
<p>with house mortgage to pay, myself to
feed and bills to cover. So I canât
really exclude money from my
consideration. If I can get a large
sum of money for </p>
<p>doing a good job, then definitely
boost my morale. I wonât care whether
I am using an old workstation, or
forced to share rooms or cubicle with
other </p>
<p>people, or have to put up with an
annoying boss, or whatever. The fact
that at the end of the day I will walk
off with a large pile of money itself
is enough </p>
<p>for me to overcome all the obstacles,
put up with all the hard feelings and
hurt egos, tolerate a slow computer
and even endure</p>
</blockquote>
<p>And here's another string</p>
<blockquote>
<p>What Motivates You to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books, despite the fact that I don't
read programming books. In order to
win the prize you have to write an
entry and describes what motivates you
to do your job well. Hence this post.</p>
<p>First motivation, money. I know, this
doesn't sound like a great inspiration
to many, and saying that money is one
of the motivation factors might just
blow my chances away. As if money is a
taboo in programming world. I know
there are people who can't be
motivated by money. Kudos to them. Me,
on the other hand, am living in a real
world, with house mortgage to pay,
myself to feed and bills to cover. So
I can't really exclude money from my
consideration.</p>
<p>If I can get a large sum of money for
doing a good job, then thatwill
definitely boost my morale. I won't
care whether I am using an old
workstation, or forced to share rooms
or cubicle with other people, or have
to put up with an annoying boss, or
whatever. The fact that at the end of
the day I will walk off with a large
pile of money itself is enough for me
to overcome all the obstacles, put up
with all the hard feelings and hurt
egos, tolerate a slow computer and
even endure</p>
</blockquote>
<p>I ran the above command, and set the isjunk to lambda x:x==" ", the ratio is only 0.36. </p>
| 2 | 2008-09-29T03:41:45Z | 147,732 | <p>Using your sample strings:</p>
<pre><code>>>> s=difflib.SequenceMatcher(lambda x: x == '\n', s1, s2)
>>> s.ratio()
0.94669848846459825
</code></pre>
<p>Interestingly if ' ' is also included as junk:</p>
<pre><code>>>> s=difflib.SequenceMatcher(lambda x: x in ' \n', s1, s2)
>>> s.ratio()
0.7653142402545744
</code></pre>
<p>Looks like the new lines are having a much greater affect than the spaces.</p>
| 1 | 2008-09-29T06:43:27Z | [
"python"
] |
Difflib.SequenceMatcher isjunk optional parameter query: how to ignore whitespaces, tabs, empty lines? | 147,437 | <p>I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use</p>
<pre><code>s=difflib.SequenceMatcher(isjunk,text1,text2)
ratio =s.ratio()
</code></pre>
<p>for this purpose.</p>
<p>So, the question is how to write the lambda expression for this isjunk method so the SequenceMatcher method will discount all the whitespaces, empty lines etc. I tried to use the parameter lambda x: x==" ", but the result isn't as great. For two closely similar text, the ratio is very low. This is highly counter intuitive. </p>
<p>For testing purpose, here are the two strings that you can use on testing:</p>
<blockquote>
<p>What Motivates jwovu to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books despite the fact that I donât
read </p>
<p>programming books. In order to win the
prize you have to write an entry and<br />
what motivatesfggmum to do your job
well. Hence this post. First
motivation </p>
<p>money. I know, this doesnât sound like
a great inspiration to many, and
saying that money is one of the
motivation factors might just blow my
chances away. </p>
<p>As if money is a taboo in programming
world. I know there are people who
canât be motivated by money. Mme, on
the other hand, am living in a real
world, </p>
<p>with house mortgage to pay, myself to
feed and bills to cover. So I canât
really exclude money from my
consideration. If I can get a large
sum of money for </p>
<p>doing a good job, then definitely
boost my morale. I wonât care whether
I am using an old workstation, or
forced to share rooms or cubicle with
other </p>
<p>people, or have to put up with an
annoying boss, or whatever. The fact
that at the end of the day I will walk
off with a large pile of money itself
is enough </p>
<p>for me to overcome all the obstacles,
put up with all the hard feelings and
hurt egos, tolerate a slow computer
and even endure</p>
</blockquote>
<p>And here's another string</p>
<blockquote>
<p>What Motivates You to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books, despite the fact that I don't
read programming books. In order to
win the prize you have to write an
entry and describes what motivates you
to do your job well. Hence this post.</p>
<p>First motivation, money. I know, this
doesn't sound like a great inspiration
to many, and saying that money is one
of the motivation factors might just
blow my chances away. As if money is a
taboo in programming world. I know
there are people who can't be
motivated by money. Kudos to them. Me,
on the other hand, am living in a real
world, with house mortgage to pay,
myself to feed and bills to cover. So
I can't really exclude money from my
consideration.</p>
<p>If I can get a large sum of money for
doing a good job, then thatwill
definitely boost my morale. I won't
care whether I am using an old
workstation, or forced to share rooms
or cubicle with other people, or have
to put up with an annoying boss, or
whatever. The fact that at the end of
the day I will walk off with a large
pile of money itself is enough for me
to overcome all the obstacles, put up
with all the hard feelings and hurt
egos, tolerate a slow computer and
even endure</p>
</blockquote>
<p>I ran the above command, and set the isjunk to lambda x:x==" ", the ratio is only 0.36. </p>
| 2 | 2008-09-29T03:41:45Z | 147,791 | <p>If you match all whitespaces the similarity is better:</p>
<pre><code>difflib.SequenceMatcher(lambda x: x in " \t\n", doc1, doc2).ratio()
</code></pre>
<p>However, difflib is not ideal to such a problem because these are two nearly identical documents, but typos and such produce differences for difflib where a human wouldn't see many.</p>
<p>Try reading up on <a href="http://en.wikipedia.org/wiki/Tf-idf">tf-idf</a>, <a href="http://en.wikipedia.org/wiki/Bayesian_probability">Bayesian probability</a>, <a href="http://en.wikipedia.org/wiki/Vector_space_model">Vector space Models</a> and <a href="http://en.wikipedia.org/wiki/W-shingling">w-shingling</a></p>
<p>I have written a an <a href="http://hg.codeflow.org/tfclassify">implementation of tf-idf</a> applying it to a vector space and using the dot product as a distance measure to classify documents.</p>
| 5 | 2008-09-29T07:17:02Z | [
"python"
] |
Difflib.SequenceMatcher isjunk optional parameter query: how to ignore whitespaces, tabs, empty lines? | 147,437 | <p>I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use</p>
<pre><code>s=difflib.SequenceMatcher(isjunk,text1,text2)
ratio =s.ratio()
</code></pre>
<p>for this purpose.</p>
<p>So, the question is how to write the lambda expression for this isjunk method so the SequenceMatcher method will discount all the whitespaces, empty lines etc. I tried to use the parameter lambda x: x==" ", but the result isn't as great. For two closely similar text, the ratio is very low. This is highly counter intuitive. </p>
<p>For testing purpose, here are the two strings that you can use on testing:</p>
<blockquote>
<p>What Motivates jwovu to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books despite the fact that I donât
read </p>
<p>programming books. In order to win the
prize you have to write an entry and<br />
what motivatesfggmum to do your job
well. Hence this post. First
motivation </p>
<p>money. I know, this doesnât sound like
a great inspiration to many, and
saying that money is one of the
motivation factors might just blow my
chances away. </p>
<p>As if money is a taboo in programming
world. I know there are people who
canât be motivated by money. Mme, on
the other hand, am living in a real
world, </p>
<p>with house mortgage to pay, myself to
feed and bills to cover. So I canât
really exclude money from my
consideration. If I can get a large
sum of money for </p>
<p>doing a good job, then definitely
boost my morale. I wonât care whether
I am using an old workstation, or
forced to share rooms or cubicle with
other </p>
<p>people, or have to put up with an
annoying boss, or whatever. The fact
that at the end of the day I will walk
off with a large pile of money itself
is enough </p>
<p>for me to overcome all the obstacles,
put up with all the hard feelings and
hurt egos, tolerate a slow computer
and even endure</p>
</blockquote>
<p>And here's another string</p>
<blockquote>
<p>What Motivates You to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books, despite the fact that I don't
read programming books. In order to
win the prize you have to write an
entry and describes what motivates you
to do your job well. Hence this post.</p>
<p>First motivation, money. I know, this
doesn't sound like a great inspiration
to many, and saying that money is one
of the motivation factors might just
blow my chances away. As if money is a
taboo in programming world. I know
there are people who can't be
motivated by money. Kudos to them. Me,
on the other hand, am living in a real
world, with house mortgage to pay,
myself to feed and bills to cover. So
I can't really exclude money from my
consideration.</p>
<p>If I can get a large sum of money for
doing a good job, then thatwill
definitely boost my morale. I won't
care whether I am using an old
workstation, or forced to share rooms
or cubicle with other people, or have
to put up with an annoying boss, or
whatever. The fact that at the end of
the day I will walk off with a large
pile of money itself is enough for me
to overcome all the obstacles, put up
with all the hard feelings and hurt
egos, tolerate a slow computer and
even endure</p>
</blockquote>
<p>I ran the above command, and set the isjunk to lambda x:x==" ", the ratio is only 0.36. </p>
| 2 | 2008-09-29T03:41:45Z | 148,364 | <p>Given the texts above, the test is indeed as suggested:</p>
<pre><code>difflib.SequenceMatcher(lambda x: x in " \t\n", doc1, doc2).ratio()
</code></pre>
<p>However, to speed up things a little, you can take advantage of CPython's <a href="http://mail.python.org/pipermail/python-list/2005-April/320354.html" rel="nofollow">method-wrappers</a>:</p>
<pre><code>difflib.SequenceMatcher(" \t\n".__contains__, doc1, doc2).ratio()
</code></pre>
<p>This avoids many python function calls.</p>
| 1 | 2008-09-29T11:48:48Z | [
"python"
] |
How does one do the equivalent of "import * from module" with Python's __import__ function? | 147,507 | <p>Given a string with a module name, how do you import everything in the module as if you had called:</p>
<pre><code>from module import *
</code></pre>
<p>i.e. given string S="module", how does one get the equivalent of the following:</p>
<pre><code>__import__(S, fromlist="*")
</code></pre>
<p>This doesn't seem to perform as expected (as it doesn't import anything).</p>
<p>Thanks!</p>
| 14 | 2008-09-29T04:28:41Z | 147,541 | <p>Please reconsider. The only thing worse than <code>import *</code> is <em>magic</em> <code>import *</code>.</p>
<p>If you really want to:</p>
<pre><code>m = __import__ (S)
try:
attrlist = m.__all__
except AttributeError:
attrlist = dir (m)
for attr in attrlist:
globals()[attr] = getattr (m, attr)
</code></pre>
| 26 | 2008-09-29T04:45:07Z | [
"python",
"python-import"
] |
How does one do the equivalent of "import * from module" with Python's __import__ function? | 147,507 | <p>Given a string with a module name, how do you import everything in the module as if you had called:</p>
<pre><code>from module import *
</code></pre>
<p>i.e. given string S="module", how does one get the equivalent of the following:</p>
<pre><code>__import__(S, fromlist="*")
</code></pre>
<p>This doesn't seem to perform as expected (as it doesn't import anything).</p>
<p>Thanks!</p>
| 14 | 2008-09-29T04:28:41Z | 160,636 | <p>The underlying problem is that I am developing some Django, but on more than one host (with colleagues), all with different settings. I was hoping to do something like this in the project/settings.py file:</p>
<pre><code>from platform import node
settings_files = { 'BMH.lan': 'settings_bmh.py", ... }
__import__( settings_files[ node() ] )
</code></pre>
<p>It seemed a simple solution (thus elegant), but I would agree that it has a smell to it and the simplicity goes out the loop when you have to use logic like what John Millikin posted (thanks). Here's essentially the solution I went with:</p>
<pre><code>from platform import node
from settings_global import *
n = node()
if n == 'BMH.lan':
from settings_bmh import *
# add your own, here...
else:
raise Exception("No host settings for '%s'. See settings.py." % node())
</code></pre>
<p>Which works fine for our purposes.</p>
| 0 | 2008-10-02T02:33:33Z | [
"python",
"python-import"
] |
How does one do the equivalent of "import * from module" with Python's __import__ function? | 147,507 | <p>Given a string with a module name, how do you import everything in the module as if you had called:</p>
<pre><code>from module import *
</code></pre>
<p>i.e. given string S="module", how does one get the equivalent of the following:</p>
<pre><code>__import__(S, fromlist="*")
</code></pre>
<p>This doesn't seem to perform as expected (as it doesn't import anything).</p>
<p>Thanks!</p>
| 14 | 2008-09-29T04:28:41Z | 293,189 | <p>I didn't find a good way to do it so I took a simpler but ugly way from <a href="http://www.djangosnippets.org/snippets/600/" rel="nofollow">http://www.djangosnippets.org/snippets/600/</a></p>
<pre><code>try:
import socket
hostname = socket.gethostname().replace('.','_')
exec "from host_settings.%s import *" % hostname
except ImportError, e:
raise e
</code></pre>
| -2 | 2008-11-15T22:55:08Z | [
"python",
"python-import"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.