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
list
Does Python have any for loop equivalent (not foreach)
1,950,098
<p>Python's iterators are great and all, but sometimes I really do want a C-style for loop - not a foreach loop. For example, I have a start date and an end date and I want to do something for every day in that range. I can do this with a while loop, of course:</p> <pre><code> current = start while current &lt;...
13
2009-12-23T00:41:31Z
1,950,179
<p>The elegant and Pythonic way to do it is to encapsulate the idea of a range of dates in its own generator, then use that generator in your code:</p> <pre><code>import datetime def daterange(start, end, delta): """ Just like `range`, but for dates! """ current = start while current &lt; end: yie...
30
2009-12-23T01:13:27Z
[ "python", "loops", "for-loop" ]
Does Python have any for loop equivalent (not foreach)
1,950,098
<p>Python's iterators are great and all, but sometimes I really do want a C-style for loop - not a foreach loop. For example, I have a start date and an end date and I want to do something for every day in that range. I can do this with a while loop, of course:</p> <pre><code> current = start while current &lt;...
13
2009-12-23T00:41:31Z
1,951,097
<p>Doing it in a compact way it's not easy in Python, as one of the basic concepts behind the language is not being able to make assignments on comparisons.</p> <p>For something complex, like a date, I think that the answer of Ned is great, but for easier cases, I found very useful the itertools.count() function, whic...
2
2009-12-23T06:54:56Z
[ "python", "loops", "for-loop" ]
Does Python have any for loop equivalent (not foreach)
1,950,098
<p>Python's iterators are great and all, but sometimes I really do want a C-style for loop - not a foreach loop. For example, I have a start date and an end date and I want to do something for every day in that range. I can do this with a while loop, of course:</p> <pre><code> current = start while current &lt;...
13
2009-12-23T00:41:31Z
3,681,429
<p>This will work in a pinch:</p> <pre><code>def cfor(start, test_func, cycle_func): """A generator function that emulates the most common case of the C for loop construct, where a variable is assigned a value at the begining, then on each next cycle updated in some way, and exited when a condition dep...
1
2010-09-10T00:00:08Z
[ "python", "loops", "for-loop" ]
Distributing Python programs
1,950,218
<p>How do I let my friends use my Python programs? They don't have python installed, but they can use command line programs. I don't have the skill to write GUI.</p> <p>Let, say I am writing some calculus calculator, with a lot of custom modules and files. How do I share it?</p>
8
2009-12-23T01:28:56Z
1,950,223
<p>You could use something like <a href="http://www.py2exe.org/">py2exe</a> to convert your Python program into an executable.</p>
11
2009-12-23T01:29:50Z
[ "python" ]
Distributing Python programs
1,950,218
<p>How do I let my friends use my Python programs? They don't have python installed, but they can use command line programs. I don't have the skill to write GUI.</p> <p>Let, say I am writing some calculus calculator, with a lot of custom modules and files. How do I share it?</p>
8
2009-12-23T01:28:56Z
1,950,233
<p>another alternative you can try is <a href="http://www.portablepython.com/wiki/PortablePython1.1Py2.6.1">Portable python</a>.</p>
7
2009-12-23T01:35:07Z
[ "python" ]
Distributing Python programs
1,950,218
<p>How do I let my friends use my Python programs? They don't have python installed, but they can use command line programs. I don't have the skill to write GUI.</p> <p>Let, say I am writing some calculus calculator, with a lot of custom modules and files. How do I share it?</p>
8
2009-12-23T01:28:56Z
1,950,924
<p>You have the options presented thus far: Portable Python and Py2Exe. Either can be pretty good.</p> <p>My suggestion: encourage your friends to install Python! As you know, it's free, and simple to install and download. If they want your application bad enough, installing Python will be a no-brainer.</p>
3
2009-12-23T05:57:30Z
[ "python" ]
Distributing Python programs
1,950,218
<p>How do I let my friends use my Python programs? They don't have python installed, but they can use command line programs. I don't have the skill to write GUI.</p> <p>Let, say I am writing some calculus calculator, with a lot of custom modules and files. How do I share it?</p>
8
2009-12-23T01:28:56Z
1,952,080
<p>A less general, but lightweight and simple way of putting many Python files into 1 or 2 files (Python programs) is Fredrik Lundh's <a href="http://effbot.org/zone/squeeze.htm" rel="nofollow">squeeze</a> program. When you "squeeze" a bunch of Python programs and modules, you can often produce a single Python program...
1
2009-12-23T10:53:37Z
[ "python" ]
Distributing Python programs
1,950,218
<p>How do I let my friends use my Python programs? They don't have python installed, but they can use command line programs. I don't have the skill to write GUI.</p> <p>Let, say I am writing some calculus calculator, with a lot of custom modules and files. How do I share it?</p>
8
2009-12-23T01:28:56Z
8,256,102
<p><a href="http://hackerboss.com/how-to-distribute-commercial-python-applications/" rel="nofollow">http://hackerboss.com/how-to-distribute-commercial-python-applications/</a> mentions using preinstalled, bundled, and frozen interpreters, but i suggest for speed and security, to compile using Shed Skin, Iron Python, Cy...
1
2011-11-24T11:10:48Z
[ "python" ]
pyyaml: dumping without tags
1,950,306
<p>I have</p> <pre><code>&gt;&gt;&gt; import yaml &gt;&gt;&gt; yaml.dump(u'abc') "!!python/unicode 'abc'\n" </code></pre> <p>But I want</p> <pre><code>&gt;&gt;&gt; import yaml &gt;&gt;&gt; yaml.dump(u'abc', magic='something') 'abc\n' </code></pre> <p>What magic param forces no tagging?</p>
40
2009-12-23T02:03:11Z
1,950,399
<p>You can use <code>safe_dump</code> instead of <code>dump</code>. Just keep in mind that it won't be able to represent arbitrary Python objects then. Also, when you <code>load</code> the YAML, you will get a <code>str</code> object instead of <code>unicode</code>.</p>
50
2009-12-23T02:34:41Z
[ "python", "yaml", "pyyaml" ]
pyyaml: dumping without tags
1,950,306
<p>I have</p> <pre><code>&gt;&gt;&gt; import yaml &gt;&gt;&gt; yaml.dump(u'abc') "!!python/unicode 'abc'\n" </code></pre> <p>But I want</p> <pre><code>&gt;&gt;&gt; import yaml &gt;&gt;&gt; yaml.dump(u'abc', magic='something') 'abc\n' </code></pre> <p>What magic param forces no tagging?</p>
40
2009-12-23T02:03:11Z
1,951,616
<p>How about this:</p> <pre><code>def unicode_representer(dumper, uni): node = yaml.ScalarNode(tag=u'tag:yaml.org,2002:str', value=uni) return node yaml.add_representer(unicode, unicode_representer) </code></pre> <p>This seems to make dumping unicode objects work the same as dumping str objects for me (Pytho...
11
2009-12-23T09:25:38Z
[ "python", "yaml", "pyyaml" ]
pyyaml: dumping without tags
1,950,306
<p>I have</p> <pre><code>&gt;&gt;&gt; import yaml &gt;&gt;&gt; yaml.dump(u'abc') "!!python/unicode 'abc'\n" </code></pre> <p>But I want</p> <pre><code>&gt;&gt;&gt; import yaml &gt;&gt;&gt; yaml.dump(u'abc', magic='something') 'abc\n' </code></pre> <p>What magic param forces no tagging?</p>
40
2009-12-23T02:03:11Z
20,720,773
<p>You need a new dumper class that does everything the standard Dumper class does but overrides the representers for str and unicode.</p> <pre><code>from yaml.dumper import Dumper from yaml.representer import SafeRepresenter class KludgeDumper(Dumper): pass KludgeDumper.add_representer(str, SafeRepresente...
2
2013-12-21T15:55:24Z
[ "python", "yaml", "pyyaml" ]
pyyaml: dumping without tags
1,950,306
<p>I have</p> <pre><code>&gt;&gt;&gt; import yaml &gt;&gt;&gt; yaml.dump(u'abc') "!!python/unicode 'abc'\n" </code></pre> <p>But I want</p> <pre><code>&gt;&gt;&gt; import yaml &gt;&gt;&gt; yaml.dump(u'abc', magic='something') 'abc\n' </code></pre> <p>What magic param forces no tagging?</p>
40
2009-12-23T02:03:11Z
34,859,143
<p>I've just started with Python and YAML, but probably this may also help. Just compare outputs:</p> <pre><code>def test_dump(self): print yaml.dump([{'name': 'value'}, {'name2': 1}], explicit_start=True) print yaml.dump_all([{'name': 'value'}, {'name2': 1}]) </code></pre>
0
2016-01-18T16:07:05Z
[ "python", "yaml", "pyyaml" ]
Is it Pythonic to check function argument types?
1,950,386
<p>I know, type checking function arguments is generally frowned upon in Python, but I think I've come up with a situation where it makes sense to do so. </p> <p>In my project I have an Abstract Base Class <code>Coord</code>, with a subclass <code>Vector</code>, which has more features like rotation, changing magnitud...
16
2009-12-23T02:31:03Z
1,950,420
<p>Your taste may vary, but the Pythonic(tm) style is to just go ahead and use objects as you need to. If they don't support the operations you're attempting, an exception will be raised. This is known as <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping">duck typing</a>.</p> <p>There are a few reasons for favorin...
23
2009-12-23T02:42:01Z
[ "python", "typechecking" ]
Is it Pythonic to check function argument types?
1,950,386
<p>I know, type checking function arguments is generally frowned upon in Python, but I think I've come up with a situation where it makes sense to do so. </p> <p>In my project I have an Abstract Base Class <code>Coord</code>, with a subclass <code>Vector</code>, which has more features like rotation, changing magnitud...
16
2009-12-23T02:31:03Z
1,950,437
<p>If this is an exception to the rule, it's ok. But if the engineering/design of your project revolves around type checking every function (or most of them) then maybe you don't want to use Python, how about C# instead?</p> <p>From my judgment, you making a decorator for type checking generally means that you're goin...
2
2009-12-23T02:49:08Z
[ "python", "typechecking" ]
Is it Pythonic to check function argument types?
1,950,386
<p>I know, type checking function arguments is generally frowned upon in Python, but I think I've come up with a situation where it makes sense to do so. </p> <p>In my project I have an Abstract Base Class <code>Coord</code>, with a subclass <code>Vector</code>, which has more features like rotation, changing magnitud...
16
2009-12-23T02:31:03Z
1,950,564
<p>One of the reasons Duck Typing is encouraged in Python is that someone might wrap one of your objects, and then it will look like the wrong type, but still work.</p> <p>Here is an example of a class that wraps an object. A <code>LoggedObject</code> acts in all ways like the object it wraps, but when you call the <...
9
2009-12-23T03:38:10Z
[ "python", "typechecking" ]
Is it Pythonic to check function argument types?
1,950,386
<p>I know, type checking function arguments is generally frowned upon in Python, but I think I've come up with a situation where it makes sense to do so. </p> <p>In my project I have an Abstract Base Class <code>Coord</code>, with a subclass <code>Vector</code>, which has more features like rotation, changing magnitud...
16
2009-12-23T02:31:03Z
1,950,585
<p>There has been some talk about this because Py3k supports a <a href="http://www.python.org/dev/peps/pep-3107/" rel="nofollow">function annotations</a> of which type annotations are an application. There was also an effort to roll <a href="http://oakwinter.com/code/typecheck/" rel="nofollow">type checking</a> in Pyth...
1
2009-12-23T03:43:00Z
[ "python", "typechecking" ]
Is it Pythonic to check function argument types?
1,950,386
<p>I know, type checking function arguments is generally frowned upon in Python, but I think I've come up with a situation where it makes sense to do so. </p> <p>In my project I have an Abstract Base Class <code>Coord</code>, with a subclass <code>Vector</code>, which has more features like rotation, changing magnitud...
16
2009-12-23T02:31:03Z
1,952,103
<p>In addition to the ideas already mentioned, you might want to "coerce" the input data into a type that has the operations you need. For instance, you might want to convert a tuple of coordinates into a Numpy array, so that you can perform linear algebra operations on it. The coercion code is quite general:</p> <p...
1
2009-12-23T10:59:45Z
[ "python", "typechecking" ]
What does classmethod do in this code?
1,950,414
<p>In django.utils.tree.py:</p> <pre><code>def _new_instance(cls, children=None, connector=None, negated=False): obj = Node(children, connector, negated) obj.__class__ = cls return obj _new_instance = classmethod(_new_instance) </code></pre> <p>I don't know what <code>classmethod</code> do...
13
2009-12-23T02:39:39Z
1,950,430
<p>It makes it possible to call the method on the class instead of an object:</p> <pre><code>class MyClass(object): def _new_instance(cls, blah): pass _new_instance = classmethod(_new_instance) MyClass._new_instance("blah") </code></pre>
3
2009-12-23T02:46:11Z
[ "python" ]
What does classmethod do in this code?
1,950,414
<p>In django.utils.tree.py:</p> <pre><code>def _new_instance(cls, children=None, connector=None, negated=False): obj = Node(children, connector, negated) obj.__class__ = cls return obj _new_instance = classmethod(_new_instance) </code></pre> <p>I don't know what <code>classmethod</code> do...
13
2009-12-23T02:39:39Z
1,950,927
<p><code>classmethod</code> is a descriptor, wrapping a function, and you can call the resulting object on a class or (equivalently) an instance thereof:</p> <pre><code>&gt;&gt;&gt; class x(object): ... def c1(*args): print 'c1', args ... c1 = classmethod(c1) ... @classmethod ... def c2(*args): print 'c2', arg...
52
2009-12-23T05:59:07Z
[ "python" ]
wxPython file dialog error: missing "|" in the wildcard string!
1,950,454
<p>I am on Windows7, using Python 2.6 and wxPython 2.8.10.1. I am trying to get this Open File dialog to work but am running into a weird error. This looks like a valid wildcard string to me, but whenever I choose a file and click 'Ok' on the File Dialog, I get this:</p> <pre><code>Traceback (most recent call last):...
2
2009-12-23T02:56:55Z
1,950,466
<p>The wildcard string has a quirky format, borrowed from Win32:</p> <pre><code>Desc1|wildcard1|Desc2|wildcard2 ... </code></pre> <p>There should be an odd number of pipes, so that the pipe-separated pieces form pairs, a description, and a wildcard. For example:</p> <pre><code>Spreadsheet (*.xls)|*.xls|Plain-old te...
7
2009-12-23T03:01:45Z
[ "python", "wxpython" ]
python lottery suggestion
1,950,539
<p>I know python offers random module to do some simple lottery. Let say random.shuffle() is a good one.</p> <p>However, I want to build my own simple one. What should I look into? Is there any specific mathematical philosophies behind lottery?</p> <p>Let say, the simplest situation. 100 names and generate 20 names r...
0
2009-12-23T03:30:22Z
1,950,553
<p>See the <a href="http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle" rel="nofollow">Fisher-Yates Shuffle</a>, described also in Knuth's <a href="http://en.wikipedia.org/wiki/The_Art_of_Computer_Programming" rel="nofollow">The Art of Computer Programming</a>.</p>
3
2009-12-23T03:36:00Z
[ "python" ]
python lottery suggestion
1,950,539
<p>I know python offers random module to do some simple lottery. Let say random.shuffle() is a good one.</p> <p>However, I want to build my own simple one. What should I look into? Is there any specific mathematical philosophies behind lottery?</p> <p>Let say, the simplest situation. 100 names and generate 20 names r...
0
2009-12-23T03:30:22Z
1,950,571
<p>You can use: <code>random.sample</code></p> <blockquote> <p>Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.</p> </blockquote> <p>For a more low-level approach, use `random.choice', in a loop:</p> <blockquote> <p>Return a random...
1
2009-12-23T03:39:15Z
[ "python" ]
python lottery suggestion
1,950,539
<p>I know python offers random module to do some simple lottery. Let say random.shuffle() is a good one.</p> <p>However, I want to build my own simple one. What should I look into? Is there any specific mathematical philosophies behind lottery?</p> <p>Let say, the simplest situation. 100 names and generate 20 names r...
0
2009-12-23T03:30:22Z
1,950,575
<p>The main shortcoming of software-based methods of generating lottery numbers is the fact that all random numbers generated by software are <em>pseudo-random</em>.</p> <p><strong>This may not be a problem for your simple application</strong>, but you did ask about a 'specific mathematical philosophy'. You will have ...
0
2009-12-23T03:39:45Z
[ "python" ]
python lottery suggestion
1,950,539
<p>I know python offers random module to do some simple lottery. Let say random.shuffle() is a good one.</p> <p>However, I want to build my own simple one. What should I look into? Is there any specific mathematical philosophies behind lottery?</p> <p>Let say, the simplest situation. 100 names and generate 20 names r...
0
2009-12-23T03:30:22Z
1,950,627
<p>You can generate your own pseudo-random numbers -- there's a huge amount of theory behind that, start for example <a href="http://en.wikipedia.org/wiki/Pseudorandom%5Fnumber%5Fgenerator" rel="nofollow">here</a> -- and of course you won't be able to compete with Python's <code>random</code> "Mersenne twister" (explai...
4
2009-12-23T04:00:59Z
[ "python" ]
python lottery suggestion
1,950,539
<p>I know python offers random module to do some simple lottery. Let say random.shuffle() is a good one.</p> <p>However, I want to build my own simple one. What should I look into? Is there any specific mathematical philosophies behind lottery?</p> <p>Let say, the simplest situation. 100 names and generate 20 names r...
0
2009-12-23T03:30:22Z
1,950,904
<p>I praise your desire to do this on your own.</p> <p>Back in the 1950's, random numbers were unavailable to most people without a <em>supercomputer</em> (of the time). The RAND corporation published a book called <em>a million random digits with 100,000 normal deviates</em> which had, literally, just that: random nu...
2
2009-12-23T05:52:43Z
[ "python" ]
What is the purpose of deepcopy's second parameter, memo?
1,950,563
<pre><code>from copy import* a=[1,2,3,4] c={'a':'aaa'} print c #{'a': 'aaa'} b=deepcopy(a,c) print b print c # print {'a': 'aaa', 10310992: 3, 10310980: 4, 10311016: 1, 11588784: [1, 2, 3, 4, [1, 2, 3, 4]], 11566456: [1, 2, 3, 4], 10311004: 2} </code></pre> <p>why c print that</p> <p>Please try to use the code, rat...
2
2009-12-23T03:37:56Z
1,950,593
<p>You can read more by checking the Python online documentation:</p> <p><a href="http://docs.python.org/library/copy.html" rel="nofollow">http://docs.python.org/library/copy.html</a></p> <p>The <code>deepcopy()</code> function is recursive, and it will work its way down through a deeply nested object. It uses a dic...
2
2009-12-23T03:45:11Z
[ "python" ]
What is the purpose of deepcopy's second parameter, memo?
1,950,563
<pre><code>from copy import* a=[1,2,3,4] c={'a':'aaa'} print c #{'a': 'aaa'} b=deepcopy(a,c) print b print c # print {'a': 'aaa', 10310992: 3, 10310980: 4, 10311016: 1, 11588784: [1, 2, 3, 4, [1, 2, 3, 4]], 11566456: [1, 2, 3, 4], 10311004: 2} </code></pre> <p>why c print that</p> <p>Please try to use the code, rat...
2
2009-12-23T03:37:56Z
1,950,602
<p>It's the <code>memo</code> dict, where id-to-object correspondence is kept to reconstruct complex object graphs perfectly. Hard to "use the code", but, let's try:</p> <pre><code>&gt;&gt;&gt; import copy &gt;&gt;&gt; memo = {} &gt;&gt;&gt; x = range(5) &gt;&gt;&gt; y = copy.deepcopy(x, memo) &gt;&gt;&gt; memo {3996...
6
2009-12-23T03:47:56Z
[ "python" ]
What is the purpose of deepcopy's second parameter, memo?
1,950,563
<pre><code>from copy import* a=[1,2,3,4] c={'a':'aaa'} print c #{'a': 'aaa'} b=deepcopy(a,c) print b print c # print {'a': 'aaa', 10310992: 3, 10310980: 4, 10311016: 1, 11588784: [1, 2, 3, 4, [1, 2, 3, 4]], 11566456: [1, 2, 3, 4], 10311004: 2} </code></pre> <p>why c print that</p> <p>Please try to use the code, rat...
2
2009-12-23T03:37:56Z
14,872,903
<p>Here's a quick illustration I used for explaining this to myself:</p> <pre><code>a = [1,2,3] memo = {} b = copy.deepcopy(a,memo) # now memo = {139907464678864: [1, 2, 3], 9357408: 1, 9357440: 2, 9357472: 3, 28258000: [1, 2, 3, [1, 2, 3]]} key = 139907464678864 print(id(a) == key) #True print(id(b) ==...
0
2013-02-14T10:39:42Z
[ "python" ]
Library for programming Abstract Syntax Trees in Python
1,950,578
<p>I'm creating a tree to represent a simple language. I'm very familiar with Abstract Syntax Trees, and have worked on frameworks for building and using them in C++. Is there a standard python library for specifying or manipulating arbitrary ASTs? Failing that, is there a tree library which is useful for the same purp...
10
2009-12-23T03:40:22Z
1,950,592
<p>ASTs are very simple to implement in Python. For example, for my <a href="https://github.com/eliben/pycparser" rel="nofollow">pycparser</a> project (a complete C parser in Python) I've implemented ASTs based on ideas borrowed from Python's modules. The various AST nodes are specified in a YAML configuration file, an...
7
2009-12-23T03:44:58Z
[ "python", "abstract-syntax-tree" ]
Library for programming Abstract Syntax Trees in Python
1,950,578
<p>I'm creating a tree to represent a simple language. I'm very familiar with Abstract Syntax Trees, and have worked on frameworks for building and using them in C++. Is there a standard python library for specifying or manipulating arbitrary ASTs? Failing that, is there a tree library which is useful for the same purp...
10
2009-12-23T03:40:22Z
1,955,012
<p>If you represent your grammar elements as expressions in pyparsing, you can attach a parse action to each expression which returns a class instance containing the parsed tokens in a parser-specific type. There are a couple of examples on the pyparsing wiki that illustrate this technique (<a href="http://pyparsing.wi...
0
2009-12-23T20:05:55Z
[ "python", "abstract-syntax-tree" ]
Library for programming Abstract Syntax Trees in Python
1,950,578
<p>I'm creating a tree to represent a simple language. I'm very familiar with Abstract Syntax Trees, and have worked on frameworks for building and using them in C++. Is there a standard python library for specifying or manipulating arbitrary ASTs? Failing that, is there a tree library which is useful for the same purp...
10
2009-12-23T03:40:22Z
1,965,937
<p>This blog entry, though short on implementation detail, describes a nice interface that Python ASTs could implement.</p> <p><a href="http://chris-lamb.co.uk/2006/12/08/visitor-pattern-in-python/" rel="nofollow">http://chris-lamb.co.uk/2006/12/08/visitor-pattern-in-python/</a></p>
0
2009-12-27T13:21:21Z
[ "python", "abstract-syntax-tree" ]
Library for programming Abstract Syntax Trees in Python
1,950,578
<p>I'm creating a tree to represent a simple language. I'm very familiar with Abstract Syntax Trees, and have worked on frameworks for building and using them in C++. Is there a standard python library for specifying or manipulating arbitrary ASTs? Failing that, is there a tree library which is useful for the same purp...
10
2009-12-23T03:40:22Z
23,001,299
<p><a href="https://pypi.python.org/pypi/pyast/1.0" rel="nofollow"><code>pyast</code></a> is a package for building declarative abstract syntax trees.</p>
1
2014-04-11T00:09:17Z
[ "python", "abstract-syntax-tree" ]
Python: Split list into list of dicts?
1,950,672
<p>Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list:</p> <pre><code>data = ['ID:0:0:0', 'Status:Ok', 'Name:PhysicalDisk0:0:0', 'State:Online', 'FailurePredicted:No', 'I...
2
2009-12-23T04:21:19Z
1,950,694
<pre><code>import re results = [] temp = {} for item in data: (key, value) = re.search('(.*?):(.*)', item).groups() if temp.has_key(key): temp = {} temp[key] = value if temp not in results: results.append(temp) </code></pre>
1
2009-12-23T04:31:11Z
[ "python", "list", "dictionary" ]
Python: Split list into list of dicts?
1,950,672
<p>Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list:</p> <pre><code>data = ['ID:0:0:0', 'Status:Ok', 'Name:PhysicalDisk0:0:0', 'State:Online', 'FailurePredicted:No', 'I...
2
2009-12-23T04:21:19Z
1,950,722
<p>If you have no more info than "each repetition of a key signals the need to start a new dict", your code can be improved only marginally, for example as:</p> <pre><code>results = [] curd = {} for x in data: k, v = x.split(':', 1) if k in curd: results.append(curd) curd = {} curd[k] = v results.append(...
1
2009-12-23T04:42:06Z
[ "python", "list", "dictionary" ]
Python: Split list into list of dicts?
1,950,672
<p>Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list:</p> <pre><code>data = ['ID:0:0:0', 'Status:Ok', 'Name:PhysicalDisk0:0:0', 'State:Online', 'FailurePredicted:No', 'I...
2
2009-12-23T04:21:19Z
1,950,726
<pre><code>result = [{}] for item in data: key, val = item.split(":", 1) if key in result[-1]: result.append({}) result[-1][key] = val </code></pre>
6
2009-12-23T04:43:07Z
[ "python", "list", "dictionary" ]
Python: Split list into list of dicts?
1,950,672
<p>Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list:</p> <pre><code>data = ['ID:0:0:0', 'Status:Ok', 'Name:PhysicalDisk0:0:0', 'State:Online', 'FailurePredicted:No', 'I...
2
2009-12-23T04:21:19Z
1,950,758
<pre><code>ret = [] ITEMS_AMOUNT = 5 while True: tmp = {} for i in data[0:ITEMS_AMOUNT]: tmp.update(dict([i.split(':', 1)])) ret.append(tmp) if len(data) == ITEMS_AMOUNT: break data = data[ITEMS_AMOUNT:] print ret </code></pre>
0
2009-12-23T04:52:56Z
[ "python", "list", "dictionary" ]
Python: Split list into list of dicts?
1,950,672
<p>Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list:</p> <pre><code>data = ['ID:0:0:0', 'Status:Ok', 'Name:PhysicalDisk0:0:0', 'State:Online', 'FailurePredicted:No', 'I...
2
2009-12-23T04:21:19Z
1,950,787
<pre><code>d=dict([]) c=0 whatiwant=["ID","Status","Name","State","Failure Predicted"] for line in open("file"): line=line.rstrip() sline=line.split(":",1) sline[0]=sline[0].strip() if sline[0]=="ID": c+=1 d.setdefault(c,[]) if sline[0] in whatiwant: d[c].append((sline[0],' '...
0
2009-12-23T05:00:54Z
[ "python", "list", "dictionary" ]
SendKeys failing after 2 runs in thread
1,950,781
<h1>Python and SendKeys</h1> <pre><code>import SendKeys, threading, pyHook, pythoncom class Auto(threading.Thread): def run(self): SendKeys.SendKeys("{ENTER}",pause=0.1); print('Sent'); exit(); def OnKeyboardEvent(event): if event.Ascii == 22: Auto().start(); return True hm = pyHook.Ho...
2
2009-12-23T04:58:58Z
1,950,832
<p>I am not so sure with the program but if you put <code>exit();</code> in the middle of the program, It will quit program completely.</p> <p>So Could you try without <code>exit();</code>?</p>
0
2009-12-23T05:21:44Z
[ "python", "sendkeys" ]
SendKeys failing after 2 runs in thread
1,950,781
<h1>Python and SendKeys</h1> <pre><code>import SendKeys, threading, pyHook, pythoncom class Auto(threading.Thread): def run(self): SendKeys.SendKeys("{ENTER}",pause=0.1); print('Sent'); exit(); def OnKeyboardEvent(event): if event.Ascii == 22: Auto().start(); return True hm = pyHook.Ho...
2
2009-12-23T04:58:58Z
1,950,985
<p>It seems that SendKeys is thread safe. The following code works on Vista - Python 2.6</p> <pre><code>class Auto(threading.Thread): def run(self): SendKeys.SendKeys("#",pause=0.1); print('Sent'); exit(); for i in xrange(30): Auto().start() </code></pre> <p>Maybe the problem comes fr...
1
2009-12-23T06:18:59Z
[ "python", "sendkeys" ]
Python - Things I shouldn't be doing?
1,951,012
<p>I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code:</p> <pre><code>... junk_block = "".join(open("foo.txt","rb").read().split()) ... </code></pre> <p>I don't do this anymore because I can see that it makes code harder to read, but would the code ru...
4
2009-12-23T06:31:03Z
1,951,042
<p>First of all, there's not really a reason you <em>shouldn't</em> use the first example - it'd quite readable in that it's concise about what it does. No reason to break it up since it's just a linear combination of calls.</p> <p>Second, <code>import</code> within a function block is useful if there's a particular l...
4
2009-12-23T06:40:16Z
[ "python" ]
Python - Things I shouldn't be doing?
1,951,012
<p>I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code:</p> <pre><code>... junk_block = "".join(open("foo.txt","rb").read().split()) ... </code></pre> <p>I don't do this anymore because I can see that it makes code harder to read, but would the code ru...
4
2009-12-23T06:31:03Z
1,951,045
<p>If you want to know if your second code fragment is slower, the quick way to find out would be to just use <a href="http://docs.python.org/library/timeit.html" rel="nofollow">timeit</a>. I wouldn't expect there to be that much difference though, since they seem pretty equivalent. </p> <p>You should also ask if a pe...
0
2009-12-23T06:40:58Z
[ "python" ]
Python - Things I shouldn't be doing?
1,951,012
<p>I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code:</p> <pre><code>... junk_block = "".join(open("foo.txt","rb").read().split()) ... </code></pre> <p>I don't do this anymore because I can see that it makes code harder to read, but would the code ru...
4
2009-12-23T06:31:03Z
1,951,079
<p>from <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> (which is worth reading anyway)</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants</p> </blockquote>
3
2009-12-23T06:50:05Z
[ "python" ]
Python - Things I shouldn't be doing?
1,951,012
<p>I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code:</p> <pre><code>... junk_block = "".join(open("foo.txt","rb").read().split()) ... </code></pre> <p>I don't do this anymore because I can see that it makes code harder to read, but would the code ru...
4
2009-12-23T06:31:03Z
1,951,172
<p>As long as you're inside a function (<strong>not</strong> at module top level), assigning intermediate results to local barenames has an essentially-negligible cost (at module top level, assigning to the "local" barenames implies churning on a dict -- the module's <code>__dict__</code> -- and is measurably costlier ...
21
2009-12-23T07:17:34Z
[ "python" ]
Python - Things I shouldn't be doing?
1,951,012
<p>I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code:</p> <pre><code>... junk_block = "".join(open("foo.txt","rb").read().split()) ... </code></pre> <p>I don't do this anymore because I can see that it makes code harder to read, but would the code ru...
4
2009-12-23T06:31:03Z
1,951,173
<p>I think the two codes are readable. I (and that's just a question of personal style) will probably use the first, adding a coment line, something like: "Open the file and convert the data inside into a list"</p> <p>Also, there are times when I use the second, maybe not so separated, but something like</p> <pre><co...
0
2009-12-23T07:17:42Z
[ "python" ]
Python - Things I shouldn't be doing?
1,951,012
<p>I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code:</p> <pre><code>... junk_block = "".join(open("foo.txt","rb").read().split()) ... </code></pre> <p>I don't do this anymore because I can see that it makes code harder to read, but would the code ru...
4
2009-12-23T06:31:03Z
1,951,198
<p>That line has the same result as this:</p> <p>junk_block = open("foo.txt","rb").read().replace(' ', '')</p> <p>In your example you are splitting the words of the text into a list of words, and then you are joining them back together with no spaces. The above example instead uses the str.replace() method.</p> <p>T...
2
2009-12-23T07:29:35Z
[ "python" ]
python gnutella programming
1,951,113
<p>I wanna learn how to build a p2p application in python that conforms to the gnutella protocol so it can tap-in the existing network like limewire, etc.</p> <p>Any body who knows something where to start or a ste-by-step guide? I've been reading the <a href="http://wiki.limewire.org/index.php?title=GDF" rel="nofollo...
0
2009-12-23T06:58:40Z
1,951,203
<p>First of all: <strong>read the <a href="http://rfc-gnutella.sourceforge.net/src/rfc-0%5F6-draft.html" rel="nofollow">protocol specification</a> carefully</strong></p> <p>There are multiple python Gnutella implementations, I was able to find at least the following with quick googling: <a href="http://quack.sourcefor...
2
2009-12-23T07:31:56Z
[ "python", "p2p" ]
How to change the default property on a set in python and Google AppEngine
1,951,379
<p>In the following code:</p> <pre><code>class ClassA(db.Model): name = db.StringProperty() class ClassB(db.Model): name = db.StringProperty() deleted_flag = db.BooleanProperty() classA = db.ReferenceProperty(ClassA) </code></pre> <p>ClassA will have a property called <code>classb_set</code>. When I...
0
2009-12-23T08:22:46Z
1,953,036
<p>You can always use a Python property to accomplish your goal:</p> <pre><code>class ClassA(db.Model): name = db.StringProperty() def __get_classBdeleted(self): return self.classB_set.filter('deleted_flag =', 'True') classBdeleted = property(__get_classBdeleted) class ClassB(db.Model): name...
4
2009-12-23T14:14:04Z
[ "python", "google-app-engine" ]
Who can call __get__, __set__ and __del__?
1,951,415
<p>This is my code. I don't know why it doesn't work.</p> <pre><code>class a: def __get__(self): return 'xxx' def aa(self): print 'aaaa' b=a() print b.get('aa') </code></pre> <p>Please try to answer in code, because my English is not very good. Thank you.</p> <pre><code>class HideX(object): ...
0
2009-12-23T08:35:23Z
1,951,442
<p>I think you should read a bit more on <a href="http://users.rcn.com/python/download/Descriptor.htm" rel="nofollow">Descriptors</a> before you try to use them.</p>
1
2009-12-23T08:41:43Z
[ "python", "descriptor" ]
Who can call __get__, __set__ and __del__?
1,951,415
<p>This is my code. I don't know why it doesn't work.</p> <pre><code>class a: def __get__(self): return 'xxx' def aa(self): print 'aaaa' b=a() print b.get('aa') </code></pre> <p>Please try to answer in code, because my English is not very good. Thank you.</p> <pre><code>class HideX(object): ...
0
2009-12-23T08:35:23Z
1,951,604
<p>You are calling <code>obj.get</code>, but there is no get function in <code>class A</code>, hence error, either rename <code>__get__</code> to <code>get</code> or if you by chance are trying to use descriptors do something like this</p> <pre><code>class A(object): def __get__(self, obj, klass): print "_...
1
2009-12-23T09:23:02Z
[ "python", "descriptor" ]
How to read/write .sit files with Python in Linux
1,951,419
<p>How to read/write a .sit archive using Python in Linux?</p>
0
2009-12-23T08:36:02Z
1,951,466
<p>For dealing with older library formats I tend to fall back on command line utilities. You should be able to find sit manipulation tools such as this one:</p> <p><a href="http://ctan.binkerton.com/ctan.readme.php?filename=tools/unstuff/unsit.c" rel="nofollow">http://ctan.binkerton.com/ctan.readme.php?filename=tools...
0
2009-12-23T08:47:18Z
[ "python", "file", "extract" ]
Parsing a C header file in Python
1,951,421
<p>Does anyone know a spiffy way to use C header files in Python? For example I have a C program that includes a global variable:</p> <pre><code>typedef struct ImageInfo { uint8_t revisionMajor; uint8_t revisionMinor; uint16_t checksum; } ImageInfo; ImageInfo gImageInfo; /* Placed at a specific add...
13
2009-12-23T08:36:07Z
1,951,444
<p>Take a look at <a href="http://www.language-binding.net/pygccxml/pygccxml.html">pygccxml</a>. I use it to build in-memory graphs of my C / C++ source code that I can use as the basis for many code generation tasks.</p> <p>PS: When I first started out with Python based code-generation I actually tried to write a pa...
8
2009-12-23T08:42:05Z
[ "python", "c" ]
Parsing a C header file in Python
1,951,421
<p>Does anyone know a spiffy way to use C header files in Python? For example I have a C program that includes a global variable:</p> <pre><code>typedef struct ImageInfo { uint8_t revisionMajor; uint8_t revisionMinor; uint16_t checksum; } ImageInfo; ImageInfo gImageInfo; /* Placed at a specific add...
13
2009-12-23T08:36:07Z
1,951,468
<p><a href="http://sourceforge.net/projects/cppheaderparser/">Have a look at this C++ header parser written in Python</a>. You can also write your own parser using any of these tools:</p> <ul> <li><a href="http://pyparsing.wikispaces.com/">pyparsing</a></li> <li><a href="http://www.dabeaz.com/ply/">ply</a></li> <li><p...
11
2009-12-23T08:47:35Z
[ "python", "c" ]
Parsing a C header file in Python
1,951,421
<p>Does anyone know a spiffy way to use C header files in Python? For example I have a C program that includes a global variable:</p> <pre><code>typedef struct ImageInfo { uint8_t revisionMajor; uint8_t revisionMinor; uint16_t checksum; } ImageInfo; ImageInfo gImageInfo; /* Placed at a specific add...
13
2009-12-23T08:36:07Z
1,953,543
<p>This was mentioned on SO yesterday; I haven't had a chance to check it out more thoroughly yet, but I'm meaning to. The <code>pycparser</code>, a "C parser and AST generator written in Python".</p> <p><a href="https://github.com/eliben/pycparser">https://github.com/eliben/pycparser</a></p>
22
2009-12-23T15:47:52Z
[ "python", "c" ]
Parsing a C header file in Python
1,951,421
<p>Does anyone know a spiffy way to use C header files in Python? For example I have a C program that includes a global variable:</p> <pre><code>typedef struct ImageInfo { uint8_t revisionMajor; uint8_t revisionMinor; uint16_t checksum; } ImageInfo; ImageInfo gImageInfo; /* Placed at a specific add...
13
2009-12-23T08:36:07Z
9,668,387
<p>For the same purpose I'm considering <a href="https://code.launchpad.net/~luke-campagnola/pyclibrary/main" rel="nofollow" title="pyclibrary">pyclibrary</a>, it is not a complete C parser but it is aimed at parsing C header files, so it is much easier to use than pycparser or some gccxml-based parser: although weakly...
2
2012-03-12T13:56:54Z
[ "python", "c" ]
How can I create a static variable in a Python class via the C API?
1,952,379
<p>I want to do the equivalent of</p> <pre><code>class Foo(object): bar = 1 </code></pre> <p>using Python's C API. In other words, I want to create a Python class which has a static variable, using C.</p> <p>How can I do this?</p>
7
2009-12-23T11:59:20Z
1,953,315
<p>You can pass that source code to <a href="http://docs.python.org/c-api/veryhigh.html#Py%5FCompileString" rel="nofollow">Py_CompileString</a> with the appropriate flags.</p> <p>If you already have the class you could use <a href="http://docs.python.org/c-api/object.html#PyObject%5FSetAttr" rel="nofollow">PyObject_Se...
2
2009-12-23T15:06:59Z
[ "python", "c" ]
How can I create a static variable in a Python class via the C API?
1,952,379
<p>I want to do the equivalent of</p> <pre><code>class Foo(object): bar = 1 </code></pre> <p>using Python's C API. In other words, I want to create a Python class which has a static variable, using C.</p> <p>How can I do this?</p>
7
2009-12-23T11:59:20Z
1,999,039
<p>Found it! It's just a matter of setting the tp_dict element of the type object and filling adding entries to it for each of the static variables. The following C code creates the same static variable as the Python code above:</p> <pre><code>PyTypeObject type; // ...other initialisation... type.tp_dict = PyDict_New(...
4
2010-01-04T11:44:15Z
[ "python", "c" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
1,952,481
<ol> <li><p>Checking for <code>__iter__</code> works on sequence types, but it would fail on e.g. strings. I would like to know the right answer too, until then, here is one possibility (which would work on strings, too):</p> <pre><code>try: some_object_iterator = iter(some_object) except TypeError, te: print ...
449
2009-12-23T12:16:43Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
1,952,485
<p>This isn't sufficient: the object returned by <code>__iter__</code> must implement the iteration protocol (i.e. <code>next</code> method). See the relevant section in the <a href="http://docs.python.org/library/stdtypes.html#iterator-types">documentation</a>.</p> <p>In Python, a good practice is to " try and see " ...
22
2009-12-23T12:17:39Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
1,952,507
<p>You could try this:</p> <pre><code>def iterable(a): try: (x for x in a) return True except TypeError: return False </code></pre> <p>If we can make a generator that iterates over it (but never use the generator so it doesn't take up space), it's iterable. Seems like a "duh" kind of t...
9
2009-12-23T12:21:12Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
1,952,508
<pre><code>try: #treat object as iterable except TypeError, e: #object is not actually iterable </code></pre> <p>Don't run checks to see <s>if your duck really is a duck</s> to see if it is iterable or not, treat it as if it was and complain if it wasn't.</p>
13
2009-12-23T12:21:35Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
1,952,655
<h2>Duck typing</h2> <pre><code>try: iterator = iter(theElement) except TypeError: # not iterable else: # iterable # for obj in iterator: # pass </code></pre> <h2>Type checking</h2> <p>Use the <a href="http://docs.python.org/library/abc.html">Abstract Base Classes</a>. They need at least Python 2.6 ...
428
2009-12-23T12:53:38Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
1,952,735
<p>I found a nice solution <a href="http://bytes.com/topic/python/answers/514838-how-test-if-object-sequence-iterable" rel="nofollow">here</a>:</p> <pre><code>isiterable = lambda obj: isinstance(obj, basestring) \ or getattr(obj, '__iter__', False) </code></pre>
9
2009-12-23T13:13:41Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
1,952,851
<p>In Python &lt;= 2.5, you can't and shouldn't - iterable was an "informal" interface.</p> <p>But since Python 2.6 and 3.0 you can leverage the new ABC (abstract base class) infrastructure along with some builtin ABCs which are available in the collections module:</p> <pre><code>from collections import Iterable cla...
9
2009-12-23T13:35:47Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
4,136,141
<p>The best solution I've found so far:</p> <p><code>hasattr(obj, '__contains__')</code></p> <p>which basically checks if the object implements the <code>in</code> operator.</p> <p><strong>Advantages</strong> (none of the other solutions has all three):</p> <ul> <li>it is an expression (works as a <strong>lambda</s...
13
2010-11-09T16:40:45Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
10,664,278
<p>According to the <a href="https://docs.python.org/2/glossary.html#term-iterable" rel="nofollow">Python 2 Glossary</a>, iterables are</p> <blockquote> <p>all sequence types (such as <code>list</code>, <code>str</code>, and <code>tuple</code>) and some non-sequence types like <code>dict</code> and <code>file</code>...
4
2012-05-19T10:17:48Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
15,598,574
<p>I often find convenient, inside my scripts, to define an <code>iterable</code> function. (Now incorporates Alfe's suggested simplification):</p> <pre><code>import collections def iterable(obj): return isinstance(obj, collections.Iterable): </code></pre> <p>so you can test if any object is iterable in the very...
4
2013-03-24T12:41:00Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
33,897,506
<p>The easiest way, respecting the Python's <a href="https://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a>, is to catch the error (Python knows perfectly what does it expect from an object to become an iterator):</p> <pre><code>class A(object): def __getitem__(self, item): return someth...
1
2015-11-24T15:25:40Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
36,154,791
<pre><code>def is_iterable(x): try: 0 in x except TypeError: return False else: return True </code></pre> <p>This will say yes to all manner of iterable objects, but it will <strong>say no to strings</strong>. (That's what I want for example when a recursive function could take a st...
1
2016-03-22T12:46:14Z
[ "python", "iterable" ]
In Python, how do I determine if an object is iterable?
1,952,464
<p>Is there a method like <code>isiterable</code>? The only solution I have found so far is to call</p> <pre><code>hasattr(myObj, '__iter__') </code></pre> <p>But I am not sure how fool-proof this is.</p>
566
2009-12-23T12:13:55Z
36,407,550
<p>I'd like to shed a little bit more light on the interplay of <code>iter</code>, <code>__iter__</code> and <code>__getitem__</code> and what happens behind the curtains. Armed with that knowledge, you will be able to understand why the best you can do is</p> <pre><code>try: iter(maybe_iterable) print('iterat...
8
2016-04-04T16:04:01Z
[ "python", "iterable" ]
Get request object in a db model?
1,952,704
<p>Is there a way so that I can get access to request object, while saving a db object, without explicitly passing it e.g.</p> <pre><code>class RequestData(db.Model): ... def put(self): # autopopulate fields from current request </code></pre> <p>I just want a quick way to access request, instead of pa...
2
2009-12-23T13:06:17Z
1,985,358
<p>There isn't any pre-built way of achieving this to the best of my knowledge, however writing such a piece of code should not be very hard.</p> <p>If its GAE, the <a href="http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request_arguments" rel="nofollow">self.request.arguments() method</a>...
0
2009-12-31T13:18:14Z
[ "python", "google-app-engine" ]
Get request object in a db model?
1,952,704
<p>Is there a way so that I can get access to request object, while saving a db object, without explicitly passing it e.g.</p> <pre><code>class RequestData(db.Model): ... def put(self): # autopopulate fields from current request </code></pre> <p>I just want a quick way to access request, instead of pa...
2
2009-12-23T13:06:17Z
1,985,362
<p>views.py:</p> <pre><code>import threading request_storage = threading.local() def myview(request): request_storage.data = request </code></pre> <p>models.py:</p> <pre><code>class MyClass(): def save(): from views import request_storage request_storage.data.GET['myarg'] </code></pre> <p>th...
0
2009-12-31T13:18:53Z
[ "python", "google-app-engine" ]
Get request object in a db model?
1,952,704
<p>Is there a way so that I can get access to request object, while saving a db object, without explicitly passing it e.g.</p> <pre><code>class RequestData(db.Model): ... def put(self): # autopopulate fields from current request </code></pre> <p>I just want a quick way to access request, instead of pa...
2
2009-12-23T13:06:17Z
1,985,464
<p>Since Google AppEngine uses CGI protocol, the request information is all there in the environment variables (See <a href="http://hoohoo.ncsa.illinois.edu/cgi/env.html" rel="nofollow">CGI Environment Variables</a>).</p> <p>You can regenerate the request object just like this:</p> <pre><code>req = google.appengine.e...
2
2009-12-31T13:43:43Z
[ "python", "google-app-engine" ]
email last lines from a text file in python
1,952,734
<p>I am trying to set up an email function that will email the last 15 lines of a results.txt file in python. I am not sure how to do this and was asking do I have to connect to an email server or does python have some other way of sending email. The code below is what i have got so far and any help would be appreciate...
1
2009-12-23T13:13:39Z
1,952,748
<pre><code>msg = MIMEText("\n".join(fp.read().split("\n")[-15:])) </code></pre> <p>Or if you don't need blank lines at end, do like</p> <pre><code>msg = MIMEText("\n".join(fp.read().strip().split("\n")[-15:])) </code></pre>
1
2009-12-23T13:16:33Z
[ "python", "email", "smtp" ]
email last lines from a text file in python
1,952,734
<p>I am trying to set up an email function that will email the last 15 lines of a results.txt file in python. I am not sure how to do this and was asking do I have to connect to an email server or does python have some other way of sending email. The code below is what i have got so far and any help would be appreciate...
1
2009-12-23T13:13:39Z
1,952,755
<p>You can have a look at this one:</p> <p><a href="http://docs.python.org/library/email-examples.html" rel="nofollow">http://docs.python.org/library/email-examples.html</a></p>
1
2009-12-23T13:18:03Z
[ "python", "email", "smtp" ]
email last lines from a text file in python
1,952,734
<p>I am trying to set up an email function that will email the last 15 lines of a results.txt file in python. I am not sure how to do this and was asking do I have to connect to an email server or does python have some other way of sending email. The code below is what i have got so far and any help would be appreciate...
1
2009-12-23T13:13:39Z
1,952,758
<pre><code>msg = MIMEText(''.join(fp.readlines()[-15:])) </code></pre>
2
2009-12-23T13:18:25Z
[ "python", "email", "smtp" ]
email last lines from a text file in python
1,952,734
<p>I am trying to set up an email function that will email the last 15 lines of a results.txt file in python. I am not sure how to do this and was asking do I have to connect to an email server or does python have some other way of sending email. The code below is what i have got so far and any help would be appreciate...
1
2009-12-23T13:13:39Z
1,953,004
<p>There is no way for your machine to send mail without connecting to a server (otherwise how would the mail get out of your machine?). Most people have a readily available SMTP server provided for them, either by their company (if this is on an intranet) or by their ISP (if a home user). You would need the host nam...
4
2009-12-23T14:06:03Z
[ "python", "email", "smtp" ]
email last lines from a text file in python
1,952,734
<p>I am trying to set up an email function that will email the last 15 lines of a results.txt file in python. I am not sure how to do this and was asking do I have to connect to an email server or does python have some other way of sending email. The code below is what i have got so far and any help would be appreciate...
1
2009-12-23T13:13:39Z
1,953,592
<p>You might want to have a look at my <a href="http://pypi.python.org/pypi/mailer/" rel="nofollow">mailer</a> module. It wraps the email modules in the standard library.</p> <pre><code>from mailer import Mailer from mailer import Message message = Message(From="me@example.com", To="you@example.com"...
0
2009-12-23T15:54:50Z
[ "python", "email", "smtp" ]
permutations of two lists in python
1,953,194
<p>I have two lists like:</p> <pre><code>list1 = ['square','circle','triangle'] list2 = ['red','green'] </code></pre> <p>How can I create all permutations of these lists, like this:</p> <pre><code>[ 'squarered', 'squaregreen', 'redsquare', 'greensquare', 'circlered', 'circlegreen', 'redcircle', 'greencircle'...
12
2009-12-23T14:44:12Z
1,953,216
<p>How about</p> <pre><code>[x + y for x in list1 for y in list2] + [y + x for x in list1 for y in list2] </code></pre> <p>Example IPython interaction:</p> <pre><code>In [3]: list1 = ['square', 'circle', 'triangle'] In [4]: list2 = ['red', 'green'] In [5]: [x + y for x in list1 for y in list2] + [y + x for x in li...
8
2009-12-23T14:50:01Z
[ "python" ]
permutations of two lists in python
1,953,194
<p>I have two lists like:</p> <pre><code>list1 = ['square','circle','triangle'] list2 = ['red','green'] </code></pre> <p>How can I create all permutations of these lists, like this:</p> <pre><code>[ 'squarered', 'squaregreen', 'redsquare', 'greensquare', 'circlered', 'circlegreen', 'redcircle', 'greencircle'...
12
2009-12-23T14:44:12Z
1,953,229
<p>You want the <strong><a href="http://docs.python.org/library/itertools.html#itertools.product"><code>itertools.product</code></a></strong> method, which will give you the <strong><a href="http://en.wikipedia.org/wiki/Cartesian%5Fproduct">Cartesian product</a></strong> of both lists.</p> <pre><code>&gt;&gt;&gt; impo...
34
2009-12-23T14:52:37Z
[ "python" ]
permutations of two lists in python
1,953,194
<p>I have two lists like:</p> <pre><code>list1 = ['square','circle','triangle'] list2 = ['red','green'] </code></pre> <p>How can I create all permutations of these lists, like this:</p> <pre><code>[ 'squarered', 'squaregreen', 'redsquare', 'greensquare', 'circlered', 'circlegreen', 'redcircle', 'greencircle'...
12
2009-12-23T14:44:12Z
1,953,233
<p>You can in any case do something like:</p> <pre><code>perms = [] for shape in list1: for color in list2: perms.append(shape+color) </code></pre>
1
2009-12-23T14:52:55Z
[ "python" ]
permutations of two lists in python
1,953,194
<p>I have two lists like:</p> <pre><code>list1 = ['square','circle','triangle'] list2 = ['red','green'] </code></pre> <p>How can I create all permutations of these lists, like this:</p> <pre><code>[ 'squarered', 'squaregreen', 'redsquare', 'greensquare', 'circlered', 'circlegreen', 'redcircle', 'greencircle'...
12
2009-12-23T14:44:12Z
1,953,235
<p>I think what you are looking for is the product of two lists, not the permutations:</p> <pre><code>#!/usr/bin/env python import itertools list1=['square','circle','triangle'] list2=['red','green'] for shape,color in itertools.product(list1,list2): print(shape+color) </code></pre> <p>yields</p> <pre><code>squ...
5
2009-12-23T14:53:21Z
[ "python" ]
permutations of two lists in python
1,953,194
<p>I have two lists like:</p> <pre><code>list1 = ['square','circle','triangle'] list2 = ['red','green'] </code></pre> <p>How can I create all permutations of these lists, like this:</p> <pre><code>[ 'squarered', 'squaregreen', 'redsquare', 'greensquare', 'circlered', 'circlegreen', 'redcircle', 'greencircle'...
12
2009-12-23T14:44:12Z
1,953,238
<pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; map(''.join, itertools.chain(itertools.product(list1, list2), itertools.product(list2, list1))) ['squarered', 'squaregreen', 'circlered', 'circlegreen', 'trianglered', 'trianglegreen', 'redsquare', 'redcircle', 'redtriangle', 'greensquare', 'greencircle', 'greentria...
16
2009-12-23T14:54:41Z
[ "python" ]
Retrieving doubly raised exceptions original stack trace in python
1,953,237
<p>If I have a scenario where an exception is raised, caught, then raised again inside the except: block, is there a way to capture the initial stack frame from which it was raised? </p> <p>The stack-trace that gets printed as python exits describes the place where the exception is raised a second time. Is there a w...
4
2009-12-23T14:54:30Z
1,953,591
<p>It's a common mistake to re-raise an exception by specifying the exception instance again, like this:</p> <pre><code>except Exception, ex: # do something raise ex </code></pre> <p>This strips the original traceback info and starts a new one. What you should do instead is this, without explicitly specify...
11
2009-12-23T15:54:34Z
[ "python", "exception" ]
Weird unpickling error when using multiprocessing
1,953,261
<p>I get the following error when using multiprocessing:</p> <pre><code>Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner self.run() File "/usr/lib/python2.6/threading.py", line 477, in run self.__target(*self.__args, **s...
2
2009-12-23T14:57:47Z
1,953,402
<p>I've done thread-safety in C++, Java, and Delphi, but not Python, so take my comments with a grain of salt.</p> <p><a href="http://effbot.org/zone/thread-synchronization.htm" rel="nofollow">This page on Python and Thread-Safety</a> specifically mentions the assignment of a dictionary to be atomic and thread-safe. ...
0
2009-12-23T15:22:42Z
[ "python", "exception", "multiprocessing", "pickle" ]
Weird unpickling error when using multiprocessing
1,953,261
<p>I get the following error when using multiprocessing:</p> <pre><code>Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner self.run() File "/usr/lib/python2.6/threading.py", line 477, in run self.__target(*self.__args, **s...
2
2009-12-23T14:57:47Z
1,981,025
<p>Try using the <code>pickle</code> module rather than the <code>cPickle</code> module -- <code>pickle</code> is written in pure Python, and often it gives more useful error messages than <code>cPickle</code>. (Though sometimes I've had to resort to making a local copy of <code>pickle.py</code>, and adding in a few d...
3
2009-12-30T16:22:06Z
[ "python", "exception", "multiprocessing", "pickle" ]
Weird unpickling error when using multiprocessing
1,953,261
<p>I get the following error when using multiprocessing:</p> <pre><code>Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner self.run() File "/usr/lib/python2.6/threading.py", line 477, in run self.__target(*self.__args, **s...
2
2009-12-23T14:57:47Z
13,021,511
<p>I think this a problem with pickability/unpickelability of some python functions. See this post:</p> <p><a href="http://khinsen.wordpress.com/2012/02/06/teaching-parallel-computing-in-python/" rel="nofollow">http://khinsen.wordpress.com/2012/02/06/teaching-parallel-computing-in-python/</a></p> <p>I have had simila...
1
2012-10-22T23:35:05Z
[ "python", "exception", "multiprocessing", "pickle" ]
Get html output from python code
1,953,649
<p>I have dictionary and would like to produce html page where will be drawn simple html table with keys and values. How it can be done from python code?</p>
5
2009-12-23T16:03:48Z
1,953,674
<p>You maybe interested by markup see <a href="http://markup.sourceforge.net/" rel="nofollow">http://markup.sourceforge.net/</a></p>
1
2009-12-23T16:07:50Z
[ "python", "html" ]
Get html output from python code
1,953,649
<p>I have dictionary and would like to produce html page where will be drawn simple html table with keys and values. How it can be done from python code?</p>
5
2009-12-23T16:03:48Z
1,953,685
<pre><code>output = "&lt;html&gt;&lt;body&gt;&lt;table&gt;" for key in your_dict: output += "&lt;tr&gt;&lt;td&gt;%s&lt;/td&gt;&lt;td&gt;%s&lt;/td&gt;&lt;/tr&gt;" % (key, your_dict[key]) output += "&lt;/table&gt;&lt;/body&gt;&lt;/html&gt; print output </code></pre>
8
2009-12-23T16:09:15Z
[ "python", "html" ]
Get html output from python code
1,953,649
<p>I have dictionary and would like to produce html page where will be drawn simple html table with keys and values. How it can be done from python code?</p>
5
2009-12-23T16:03:48Z
1,953,746
<p>You can use a template engine like <a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja</a>. A list of engines for templating is available <a href="http://wiki.python.org/moin/Templating" rel="nofollow">here</a>.</p>
2
2009-12-23T16:16:26Z
[ "python", "html" ]
Get html output from python code
1,953,649
<p>I have dictionary and would like to produce html page where will be drawn simple html table with keys and values. How it can be done from python code?</p>
5
2009-12-23T16:03:48Z
1,954,150
<p>You may also consider using <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a> template library.</p>
1
2009-12-23T17:23:02Z
[ "python", "html" ]
Get html output from python code
1,953,649
<p>I have dictionary and would like to produce html page where will be drawn simple html table with keys and values. How it can be done from python code?</p>
5
2009-12-23T16:03:48Z
1,955,131
<p>Along with the numerous template engines, you might consider using Python's built in <a href="http://docs.python.org/library/string.html#template-strings" rel="nofollow">Template.</a> It will give you basic templating functionality without needing to learn (or choose) a template library.</p>
0
2009-12-23T20:28:40Z
[ "python", "html" ]
Building a weakref cache in python
1,953,666
<p>I'm currently coding a project in python where I need a sort of cache of generic objects, I have settled on using WeakValueDictionaries for this. These generic objects are often referenced by many other non-generic objects. My main problem though is that I can't seem to wrap my head around a way of making these Weak...
0
2009-12-23T16:06:25Z
1,953,752
<p>Maybe I'm not understanding your question, but making a dictionary of weakly referenced values available to your code isn't really any different from making a dictionary of anything else available to your code. I would store a reference to the <code>WeakValueDictionary</code> on:</p> <ul> <li>each instance (refere...
1
2009-12-23T16:17:30Z
[ "python", "caching", "weak-references" ]
Python, PyTables, Java - tying all together
1,953,731
<h1>Question in nutshell</h1> <p>What is the best way to get Python and Java to play nice with each other?</p> <h1>More detailed explanation</h1> <p>I have a somewhat complicated situation. I'll try my best to explain both in pictures and words. Here's the current system architecture:</p> <p><img src="http://i50....
24
2009-12-23T16:14:12Z
1,953,764
<p>You could try <a href="http://wiki.python.org/jython/WhyJython" rel="nofollow">Jython</a>, a Python interpreter for the JVM which can <code>import</code> Java classes.</p> <p><strong><a href="http://www.jython.org/" rel="nofollow">Jython project homepage</a></strong></p> <p><sup>Unfortunately, that's all I know on...
0
2009-12-23T16:19:31Z
[ "java", "python", "architecture", "hdf5", "pytables" ]
Python, PyTables, Java - tying all together
1,953,731
<h1>Question in nutshell</h1> <p>What is the best way to get Python and Java to play nice with each other?</p> <h1>More detailed explanation</h1> <p>I have a somewhat complicated situation. I'll try my best to explain both in pictures and words. Here's the current system architecture:</p> <p><img src="http://i50....
24
2009-12-23T16:14:12Z
1,953,842
<p>Do not make this more complex than it needs to be.</p> <p>Your Java process can -- simply -- spawn a separate subprocess to run your PyTables queries. Let the Operating System do what OS's do best.</p> <p>Your Java application can simply fork a process which has the necessary parameters as command-line options. ...
5
2009-12-23T16:32:28Z
[ "java", "python", "architecture", "hdf5", "pytables" ]
Python, PyTables, Java - tying all together
1,953,731
<h1>Question in nutshell</h1> <p>What is the best way to get Python and Java to play nice with each other?</p> <h1>More detailed explanation</h1> <p>I have a somewhat complicated situation. I'll try my best to explain both in pictures and words. Here's the current system architecture:</p> <p><img src="http://i50....
24
2009-12-23T16:14:12Z
1,954,175
<p>This is an epic question, and there are lots of considerations. Since you didn't mention any specific performance or architectural constraints, I'll try and offer the best well-rounded suggestions.</p> <p>The initial plan of using PyTables as an intermediary layer between your other elements and the datafiles seem...
13
2009-12-23T17:27:12Z
[ "java", "python", "architecture", "hdf5", "pytables" ]
Python, PyTables, Java - tying all together
1,953,731
<h1>Question in nutshell</h1> <p>What is the best way to get Python and Java to play nice with each other?</p> <h1>More detailed explanation</h1> <p>I have a somewhat complicated situation. I'll try my best to explain both in pictures and words. Here's the current system architecture:</p> <p><img src="http://i50....
24
2009-12-23T16:14:12Z
3,539,368
<p>Not sure if this is good etiquette. I couldn't fit all my comments into a normal comment, and the post has no activity for 8 months. </p> <p>Just wanted to see how this was going for you? We have a very very very similar situation where I work - only the simulation is written in C and the storage format is binary...
0
2010-08-21T22:55:46Z
[ "java", "python", "architecture", "hdf5", "pytables" ]
Accessing XMLNS attribute with Python Elementree?
1,953,761
<p>How can one access NS attributes through using ElementTree? </p> <p>With the following:</p> <pre><code>&lt;data xmlns="http://www.foo.net/a" xmlns:a="http://www.foo.net/a" book="1" category="ABS" date="2009-12-22"&gt; </code></pre> <p>When I try to root.get('xmlns') I get back None, Category and Date are fine, An...
11
2009-12-23T16:19:07Z
1,954,382
<p>I think <code>element.tag</code> is what you're looking for. Note that your example is missing a trailing slash, so it's unbalanced and won't parse. I've added one in my example.</p> <pre><code>&gt;&gt;&gt; from xml.etree import ElementTree as ET &gt;&gt;&gt; data = '''&lt;data xmlns="http://www.foo.net/a" ... ...
7
2009-12-23T18:03:29Z
[ "python", "xml", "elementtree" ]
Accessing XMLNS attribute with Python Elementree?
1,953,761
<p>How can one access NS attributes through using ElementTree? </p> <p>With the following:</p> <pre><code>&lt;data xmlns="http://www.foo.net/a" xmlns:a="http://www.foo.net/a" book="1" category="ABS" date="2009-12-22"&gt; </code></pre> <p>When I try to root.get('xmlns') I get back None, Category and Date are fine, An...
11
2009-12-23T16:19:07Z
10,151,590
<p>Look at the effbot namespaces documentation/examples; specifically the <a href="http://effbot.org/zone/element-namespaces.htm" rel="nofollow">parse_map</a> function. It shows you how to add an *ns_map* attribute to each element which contains the prefix/URI mapping that applies to that specific element.</p> <p>How...
4
2012-04-14T06:33:22Z
[ "python", "xml", "elementtree" ]
Can I store a python dictionary in google's BigTable datastore without serializing it explicitly?
1,953,784
<p>I have a python dictionary that I would like to store in Google's BigTable datastore (it is an attribute in a <code>db.Model</code> class).</p> <p>Is there an easy way to do this? i.e. using a <code>db.DictionaryProperty</code>? Or do I have to use pickle to serialize my dictionary? My dictionary is relatively str...
1
2009-12-23T16:21:50Z
1,953,899
<p>I think you cannot avoid serializing your objects.</p> <p>I would define the following model to store each key, value pair:</p> <pre><code>class DictModel(db.Model): value = db.TextProperty() </code></pre> <p>To save to the datastore I'd use:</p> <pre><code>def set_value(key, value): key = DictModel(valu...
1
2009-12-23T16:40:19Z
[ "python", "google-app-engine", "pickle" ]
Can I store a python dictionary in google's BigTable datastore without serializing it explicitly?
1,953,784
<p>I have a python dictionary that I would like to store in Google's BigTable datastore (it is an attribute in a <code>db.Model</code> class).</p> <p>Is there an easy way to do this? i.e. using a <code>db.DictionaryProperty</code>? Or do I have to use pickle to serialize my dictionary? My dictionary is relatively str...
1
2009-12-23T16:21:50Z
1,953,956
<p><a href="http://osdir.com/ml/GoogleAppEngine/2009-05/msg01093.html">Here's another approach</a>:</p> <pre><code>class DictProperty(db.Property): data_type = dict def get_value_for_datastore(self, model_instance): value = super(DictProperty, self).get_value_for_datastore(model_instance) return db.Blob(p...
8
2009-12-23T16:50:42Z
[ "python", "google-app-engine", "pickle" ]