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
Python list.index throws exception when index not found
674,229
<p>Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?</p> <p>To me it looks cleaner to deal with special values, etc than exceptions.</p> <p>EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None?</p>
9
2009-03-23T16:58:07Z
674,277
<p>It's a semantic argument. If you want to know the index of an element, you are claiming that it already exists in the list. If you want to know whether or not it exists, you should use <code>in</code>.</p>
1
2009-03-23T17:07:23Z
[ "python", "indexing", "list" ]
Python list.index throws exception when index not found
674,229
<p>Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?</p> <p>To me it looks cleaner to deal with special values, etc than exceptions.</p> <p>EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None?</p>
9
2009-03-23T16:58:07Z
674,281
<p>I agree with Devin Jeanpierre, and would add that dealing with special values may look good in small example cases but (with a few notable exceptions, e.g. NaN in FPUs and Null in SQL) it doesn't scale nearly as well. The only time it works is where:</p> <ul> <li>You've typically got lots of nested homogeneous pro...
2
2009-03-23T17:07:49Z
[ "python", "indexing", "list" ]
Python list.index throws exception when index not found
674,229
<p>Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?</p> <p>To me it looks cleaner to deal with special values, etc than exceptions.</p> <p>EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None?</p>
9
2009-03-23T16:58:07Z
674,391
<p>It's mainly to ensure that errors are caught as soon as possible. For example, consider the following:</p> <pre><code>l = [1, 2, 3] x = l.index("foo") #normally, this will raise an error l[x] #However, if line 2 returned None, it would error here </code></pre> <p>You'll notice that an error would get thrown at ...
3
2009-03-23T17:28:02Z
[ "python", "indexing", "list" ]
Python list.index throws exception when index not found
674,229
<p>Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?</p> <p>To me it looks cleaner to deal with special values, etc than exceptions.</p> <p>EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None?</p>
9
2009-03-23T16:58:07Z
675,358
<p>The "exception-vs-error value" debate is partly about code clarity. Consider code with an error value:</p> <pre><code>idx = sequence.index(x) if idx == ERROR: # do error processing else: print '%s occurred at position %s.' % (x, idx) </code></pre> <p>The error handling ends up stuffed in the middle of our...
4
2009-03-23T21:46:03Z
[ "python", "indexing", "list" ]
Python list.index throws exception when index not found
674,229
<p>Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?</p> <p>To me it looks cleaner to deal with special values, etc than exceptions.</p> <p>EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None?</p>
9
2009-03-23T16:58:07Z
28,539,502
<pre><code>def GetListIndex(list, searchString): try: return list.index(searchString) except ValueError: return False except Exception: raise </code></pre>
0
2015-02-16T10:38:51Z
[ "python", "indexing", "list" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
674,345
<p><strong><code>__new__</code></strong> is static class method, while <strong><code>__init__</code></strong> is instance method. <strong><code>__new__</code></strong> has to create the instance first, so <strong><code>__init__</code></strong> can initialize it. Note that <strong><code>__init__</code></strong> takes <...
108
2009-03-23T17:20:19Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
674,369
<blockquote> <p>Use <strong>__new__</strong> when you need to control the creation of a new instance. Use <strong>__init__</strong> when you need to control initialization of a new instance.</p> <p><strong>__new__</strong> is the first step of instance creation. It's called first, and is responsible for r...
332
2009-03-23T17:23:04Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
674,375
<blockquote> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>.</p> </blockquote> <p>Not much of a reason other than that it just is done that way. <code>__new__</code> doesn't have the responsibility of initializing the class, some other method does (<code>__...
-1
2009-03-23T17:23:37Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
674,377
<p>__new__ should return a new, blank instance of a class. __init__ is then called to initialise that instance. You're not calling __init__ in the "NEW" case of __new__, so it's being called for you. The code that is calling <code>__new__</code> doesn't keep track of whether __init__ has been called on a particular ins...
2
2009-03-23T17:23:42Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
674,399
<p>To quote the <a href="http://www.wingide.com/psupport/python-manual/2.4/ref/customization.html">documentation</a>:</p> <blockquote> <p>Typical implementations create a new instance of the class by invoking the superclass's __new__() method using "super(currentclass, cls).__new__(cls[, ...])"with appropriate a...
14
2009-03-23T17:29:23Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
8,665,179
<p>In most well-known OO languages, an expression like <code>SomeClass(arg1, arg2)</code> will allocate a new instance, initialise the instance's attributes, and then return it.</p> <p>In most well-known OO languages, the "initialise the instance's attributes" part can be customised for each class by defining a <stron...
68
2011-12-29T07:39:47Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
11,087,124
<p>The <code>__init__</code> is called after <code>__new__</code> so that when you override it in a subclass, your added code will still get called.</p> <p>If you are trying to subclass a class that already has a <code>__new__</code>, someone unaware of this might start by adapting the <code>__init__</code> and forwar...
2
2012-06-18T16:30:45Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
16,524,188
<p>I realize that this question is quite old but I had a similar issue. The following did what I wanted:</p> <pre><code>class Agent(object): _agents = dict() def __new__(cls, *p): number = p[0] if not number in cls._agents: cls._agents[number] = object.__new__(cls) return c...
6
2013-05-13T14:12:10Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
17,513,146
<p>I think the simple answer to this question is that, if <code>__new__</code> returns a value that is the same type as the class, the <code>__init__</code> function executes, otherwise it won't. In this case your code returns <em><code>A._dict('key')</code></em> which is the same class as <em><code>cls</code></em>, so...
6
2013-07-07T14:45:17Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
19,087,509
<p><a href="http://www.python.org/download/releases/2.2/descrintro/#__new__" rel="nofollow">Referring to this doc</a>: </p> <blockquote> <p>When subclassing immutable built-in types like numbers and strings, and occasionally in other situations, the static method <strong>new</strong> comes in handy. <strong>new<...
2
2013-09-30T06:13:28Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
23,258,199
<p>One should look at <strong>init</strong> as a simple constructor in traditional OO languages. For example, if you are familiar with Java or C++, the constructor is passed a pointer to its own instance implicitly. In the case of Java, it is the "this" variable. If one were to inspect the byte code generated for Java,...
1
2014-04-24T01:30:44Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
28,159,034
<p>When <code>__new__</code> returns instance of the same class, <code>__init__</code> is run afterwards on returned object. I.e. you can NOT use <code>__new__</code> to prevent <code>__init__</code> from being run. Even if you return previously created object from <code>__new__</code>, it will be double (triple, etc.....
4
2015-01-26T21:25:19Z
[ "python", "design-patterns", "class-design" ]
Python's use of __new__ and __init__?
674,304
<p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening ...
313
2009-03-23T17:13:01Z
31,723,324
<pre><code>class M(type): _dict = {} def __call__(cls, key): if key in cls._dict: print 'EXISTS' return cls._dict[key] else: print 'NEW' instance = super(M, cls).__call__(key) cls._dict[key] = instance return instance clas...
1
2015-07-30T12:04:51Z
[ "python", "design-patterns", "class-design" ]
problems Wrapping Patricia Tries using Swig, python
674,494
<p>I'm trying to wrap the Patricia Tries (Perl's NET::Patricia) to be exposed in python. I am having difficulty with one of the classes.</p> <p>So instances the patricia node (below) as viewed from python have a "data" property. Reading it goes fine, but writing to it breaks.</p> <pre><code>typedef struct _patricia...
1
2009-03-23T17:52:17Z
674,873
<p>It looks like you should pass SWIG a pointer to an integer. For example, if this was all in C, your error would be like this:</p> <pre><code>void set(struct _patricia_node_t *tree, void *data) { tree-&gt;data = data; } ... int value = 1; set(tree, &amp;value); // OK! HOORAY! set(tree, value); // NOT OK! FIR...
0
2009-03-23T19:25:06Z
[ "python", "c", "pointers", "swig" ]
problems Wrapping Patricia Tries using Swig, python
674,494
<p>I'm trying to wrap the Patricia Tries (Perl's NET::Patricia) to be exposed in python. I am having difficulty with one of the classes.</p> <p>So instances the patricia node (below) as viewed from python have a "data" property. Reading it goes fine, but writing to it breaks.</p> <pre><code>typedef struct _patricia...
1
2009-03-23T17:52:17Z
1,337,453
<p>I haven't used SWIG in a while, but I am pretty sure that you want to use a typemap that will take a <code>PyObject*</code> and cast it to the required <code>void*</code> and vice versa. Be sure to keep track of reference counts, of course.</p>
1
2009-08-26T20:58:55Z
[ "python", "c", "pointers", "swig" ]
problems Wrapping Patricia Tries using Swig, python
674,494
<p>I'm trying to wrap the Patricia Tries (Perl's NET::Patricia) to be exposed in python. I am having difficulty with one of the classes.</p> <p>So instances the patricia node (below) as viewed from python have a "data" property. Reading it goes fine, but writing to it breaks.</p> <pre><code>typedef struct _patricia...
1
2009-03-23T17:52:17Z
2,141,939
<p>An alternative is use <a href="http://www.mindrot.org/projects/py-radix/" rel="nofollow">PyRadix</a>, which uses the same underlying code. </p>
0
2010-01-26T19:19:06Z
[ "python", "c", "pointers", "swig" ]
How do I iterate over a Python dictionary, ordered by values?
674,509
<p>I've got a dictionary like:</p> <pre><code>{ 'a': 6, 'b': 1, 'c': 2 } </code></pre> <p>I'd like to iterate over it <em>by value</em>, not by key. In other words:</p> <pre><code>(b, 1) (c, 2) (a, 6) </code></pre> <p>What's the most straightforward way?</p>
11
2009-03-23T17:55:11Z
674,522
<pre><code>sorted(dictionary.items(), key=lambda x: x[1]) </code></pre> <p>for these of you that hate lambda :-)</p> <pre><code>import operator sorted(dictionary.items(), key=operator.itemgetter(1)) </code></pre> <p>However <code>operator</code> version requires CPython 2.5+</p>
24
2009-03-23T17:59:20Z
[ "python" ]
How do I iterate over a Python dictionary, ordered by values?
674,509
<p>I've got a dictionary like:</p> <pre><code>{ 'a': 6, 'b': 1, 'c': 2 } </code></pre> <p>I'd like to iterate over it <em>by value</em>, not by key. In other words:</p> <pre><code>(b, 1) (c, 2) (a, 6) </code></pre> <p>What's the most straightforward way?</p>
11
2009-03-23T17:55:11Z
674,551
<p>The <code>items</code> method gives you a list of (key,value) tuples, which can be sorted using <code>sorted</code> and a custom sort key:</p> <pre><code>Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) &gt;&gt;&gt; a={ 'a': 6, 'b': 1, 'c': 2 } &gt;&gt;&gt; sorted(a.items(), key=lambda (key,value): value) [('b', ...
3
2009-03-23T18:07:00Z
[ "python" ]
How do I iterate over a Python dictionary, ordered by values?
674,509
<p>I've got a dictionary like:</p> <pre><code>{ 'a': 6, 'b': 1, 'c': 2 } </code></pre> <p>I'd like to iterate over it <em>by value</em>, not by key. In other words:</p> <pre><code>(b, 1) (c, 2) (a, 6) </code></pre> <p>What's the most straightforward way?</p>
11
2009-03-23T17:55:11Z
674,784
<p>For non-Python 3 programs, you'll want to use iteritems to get the performance boost of generators, which yield values one at a time instead of returning all of them at once.</p> <pre><code>sorted(d.iteritems(), key=lambda x: x[1]) </code></pre> <p>For even larger dictionaries, we can go a step further and have th...
7
2009-03-23T19:02:36Z
[ "python" ]
How do I iterate over a Python dictionary, ordered by values?
674,509
<p>I've got a dictionary like:</p> <pre><code>{ 'a': 6, 'b': 1, 'c': 2 } </code></pre> <p>I'd like to iterate over it <em>by value</em>, not by key. In other words:</p> <pre><code>(b, 1) (c, 2) (a, 6) </code></pre> <p>What's the most straightforward way?</p>
11
2009-03-23T17:55:11Z
7,235,661
<p>It can often be very handy to use <b><a href="http://docs.python.org/library/collections.html#collections.namedtuple" rel="nofollow">namedtuple</a></b>. For example, you have a dictionary of name and score and you want to sort on 'score':</p> <pre><code>import collections Player = collections.namedtuple('Player', '...
4
2011-08-29T20:36:06Z
[ "python" ]
How can I convert a Python dictionary to a list of tuples?
674,519
<p>If I have a dictionary like:</p> <pre><code>{ 'a': 1, 'b': 2, 'c': 3 } </code></pre> <p>How can I convert it to this?</p> <pre><code>[ ('a', 1), ('b', 2), ('c', 3) ] </code></pre> <p>And how can I convert it to this?</p> <pre><code>[ (1, 'a'), (2, 'b'), (3, 'c') ] </code></pre>
110
2009-03-23T17:58:32Z
674,531
<pre><code>&gt;&gt;&gt; d = { 'a': 1, 'b': 2, 'c': 3 } &gt;&gt;&gt; d.items() [('a', 1), ('c', 3), ('b', 2)] &gt;&gt;&gt; [(v, k) for k, v in d.iteritems()] [(1, 'a'), (3, 'c'), (2, 'b')] </code></pre> <p>It's not in the order you want, but dicts don't have any specific order anyway. Sort it or organize it as necessar...
207
2009-03-23T18:01:38Z
[ "python" ]
How can I convert a Python dictionary to a list of tuples?
674,519
<p>If I have a dictionary like:</p> <pre><code>{ 'a': 1, 'b': 2, 'c': 3 } </code></pre> <p>How can I convert it to this?</p> <pre><code>[ ('a', 1), ('b', 2), ('c', 3) ] </code></pre> <p>And how can I convert it to this?</p> <pre><code>[ (1, 'a'), (2, 'b'), (3, 'c') ] </code></pre>
110
2009-03-23T17:58:32Z
674,532
<pre><code>[(k,v) for (k,v) in d.iteritems()] </code></pre> <p>and</p> <pre><code>[(v,k) for (k,v) in d.iteritems()] </code></pre>
1
2009-03-23T18:01:41Z
[ "python" ]
How can I convert a Python dictionary to a list of tuples?
674,519
<p>If I have a dictionary like:</p> <pre><code>{ 'a': 1, 'b': 2, 'c': 3 } </code></pre> <p>How can I convert it to this?</p> <pre><code>[ ('a', 1), ('b', 2), ('c', 3) ] </code></pre> <p>And how can I convert it to this?</p> <pre><code>[ (1, 'a'), (2, 'b'), (3, 'c') ] </code></pre>
110
2009-03-23T17:58:32Z
674,535
<p>What you want is <code>dict</code>'s <code>items()</code> and <code>iteritems()</code> methods. <code>items</code> returns a list of (key,value) tuples. Since tuples are immutable, they can't be reversed. Thus, you have to iterate the items and create new tuples to get the reversed (value,key) tuples. For iteration,...
4
2009-03-23T18:02:38Z
[ "python" ]
How can I convert a Python dictionary to a list of tuples?
674,519
<p>If I have a dictionary like:</p> <pre><code>{ 'a': 1, 'b': 2, 'c': 3 } </code></pre> <p>How can I convert it to this?</p> <pre><code>[ ('a', 1), ('b', 2), ('c', 3) ] </code></pre> <p>And how can I convert it to this?</p> <pre><code>[ (1, 'a'), (2, 'b'), (3, 'c') ] </code></pre>
110
2009-03-23T17:58:32Z
674,536
<p>You can use list comprehensions.</p> <pre><code>[(k,v) for k,v in a.iteritems()] </code></pre> <p>will get you [ ('a', 1), ('b', 2), ('c', 3) ] and </p> <pre><code>[(v,k) for k,v in a.iteritems()] </code></pre> <p>the other example.</p> <p><a href="http://docs.python.org/tutorial/datastructures.html#list-comp...
12
2009-03-23T18:02:50Z
[ "python" ]
How can I convert a Python dictionary to a list of tuples?
674,519
<p>If I have a dictionary like:</p> <pre><code>{ 'a': 1, 'b': 2, 'c': 3 } </code></pre> <p>How can I convert it to this?</p> <pre><code>[ ('a', 1), ('b', 2), ('c', 3) ] </code></pre> <p>And how can I convert it to this?</p> <pre><code>[ (1, 'a'), (2, 'b'), (3, 'c') ] </code></pre>
110
2009-03-23T17:58:32Z
674,573
<pre> >>> a={ 'a': 1, 'b': 2, 'c': 3 } >>> [(x,a[x]) for x in a.keys() ] [('a', 1), ('c', 3), ('b', 2)] >>> [(a[x],x) for x in a.keys() ] [(1, 'a'), (3, 'c'), (2, 'b')] </pre>
1
2009-03-23T18:12:51Z
[ "python" ]
How can I convert a Python dictionary to a list of tuples?
674,519
<p>If I have a dictionary like:</p> <pre><code>{ 'a': 1, 'b': 2, 'c': 3 } </code></pre> <p>How can I convert it to this?</p> <pre><code>[ ('a', 1), ('b', 2), ('c', 3) ] </code></pre> <p>And how can I convert it to this?</p> <pre><code>[ (1, 'a'), (2, 'b'), (3, 'c') ] </code></pre>
110
2009-03-23T17:58:32Z
674,594
<p>since no one else did, I'll add py3k versions:</p> <pre><code>&gt;&gt;&gt; d = { 'a': 1, 'b': 2, 'c': 3 } &gt;&gt;&gt; list(d.items()) [('a', 1), ('c', 3), ('b', 2)] &gt;&gt;&gt; [(v, k) for k, v in d.items()] [(1, 'a'), (3, 'c'), (2, 'b')] </code></pre>
19
2009-03-23T18:19:15Z
[ "python" ]
How can I convert a Python dictionary to a list of tuples?
674,519
<p>If I have a dictionary like:</p> <pre><code>{ 'a': 1, 'b': 2, 'c': 3 } </code></pre> <p>How can I convert it to this?</p> <pre><code>[ ('a', 1), ('b', 2), ('c', 3) ] </code></pre> <p>And how can I convert it to this?</p> <pre><code>[ (1, 'a'), (2, 'b'), (3, 'c') ] </code></pre>
110
2009-03-23T17:58:32Z
7,248,403
<p><b>Create a list of namedtuples</b></p> <p>It can often be very handy to use <b><a href="http://docs.python.org/library/collections.html#collections.namedtuple" rel="nofollow">namedtuple</a></b>. For example, you have a dictionary of 'name' as keys and 'score' as values like:</p> <pre><code>d = {'John':5, 'Alex':1...
6
2011-08-30T19:03:29Z
[ "python" ]
How can I convert a Python dictionary to a list of tuples?
674,519
<p>If I have a dictionary like:</p> <pre><code>{ 'a': 1, 'b': 2, 'c': 3 } </code></pre> <p>How can I convert it to this?</p> <pre><code>[ ('a', 1), ('b', 2), ('c', 3) ] </code></pre> <p>And how can I convert it to this?</p> <pre><code>[ (1, 'a'), (2, 'b'), (3, 'c') ] </code></pre>
110
2009-03-23T17:58:32Z
30,256,657
<p>By keys() and values() method of dictionary and zip.</p> <p>Zip will return a list of tuples, which acts like an ordered dictionary.</p> <p>Demo:</p> <pre><code>&gt;&gt;&gt; d = { 'a': 1, 'b': 2, 'c': 3 } &gt;&gt;&gt; zip(d.keys(), d.values()) [('a', 1), ('c', 3), ('b', 2)] &gt;&gt;&gt; zip(d.values(), d.keys()) ...
1
2015-05-15T10:02:44Z
[ "python" ]
How can I convert a Python dictionary to a list of tuples?
674,519
<p>If I have a dictionary like:</p> <pre><code>{ 'a': 1, 'b': 2, 'c': 3 } </code></pre> <p>How can I convert it to this?</p> <pre><code>[ ('a', 1), ('b', 2), ('c', 3) ] </code></pre> <p>And how can I convert it to this?</p> <pre><code>[ (1, 'a'), (2, 'b'), (3, 'c') ] </code></pre>
110
2009-03-23T17:58:32Z
39,097,455
<pre><code>d = {'John':5, 'Alex':10, 'Richard': 7} list = [] for i in d: k = (i,d[i]) list.append(k) print list </code></pre>
0
2016-08-23T09:31:01Z
[ "python" ]
Python, __init__ and self confusion
674,600
<p>Alright, so I was taking a look at some source when I came across this:</p> <pre><code>&gt;&gt;&gt; def __parse(self, filename): ... "parse ID3v1.0 tags from MP3 file" ... self.clear() ... try: ... fsock = open(filename, "rb", 0) ... try: ... fsock.see...
3
2009-03-23T18:20:44Z
674,619
<p>The <code>def __parse</code> was inside some class definition.</p> <p>You can't pull the method defs out of the class definitions. The method function definition is part of the class.</p> <p>Look at these two examples:</p> <pre><code>def add( a, b ): return a + b </code></pre> <p>And</p> <pre><code>class A...
8
2009-03-23T18:23:11Z
[ "python", "self", "init" ]
Python, __init__ and self confusion
674,600
<p>Alright, so I was taking a look at some source when I came across this:</p> <pre><code>&gt;&gt;&gt; def __parse(self, filename): ... "parse ID3v1.0 tags from MP3 file" ... self.clear() ... try: ... fsock = open(filename, "rb", 0) ... try: ... fsock.see...
3
2009-03-23T18:20:44Z
674,621
<p>self is passed in automatically by the instancemethod wrapper on classes. This function isn't wrapped; it's not a method, it's just a function. It doesn't even make sense without being attached to a class, since it needs the self parameter.</p>
0
2009-03-23T18:23:45Z
[ "python", "self", "init" ]
Python, __init__ and self confusion
674,600
<p>Alright, so I was taking a look at some source when I came across this:</p> <pre><code>&gt;&gt;&gt; def __parse(self, filename): ... "parse ID3v1.0 tags from MP3 file" ... self.clear() ... try: ... fsock = open(filename, "rb", 0) ... try: ... fsock.see...
3
2009-03-23T18:20:44Z
674,656
<p>As an aside, it <em>is</em> possible to create static methods of a class in Python. The simplest way to do this is via decorators (e.g. <code>@staticmethod</code>). I suspect this kind of thing is usually not the Pythonic solution though.</p>
0
2009-03-23T18:29:22Z
[ "python", "self", "init" ]
Python, __init__ and self confusion
674,600
<p>Alright, so I was taking a look at some source when I came across this:</p> <pre><code>&gt;&gt;&gt; def __parse(self, filename): ... "parse ID3v1.0 tags from MP3 file" ... self.clear() ... try: ... fsock = open(filename, "rb", 0) ... try: ... fsock.see...
3
2009-03-23T18:20:44Z
674,670
<p>Functions/methods can be written outside of a class and then used for a technique in Python called <strong>monkeypatching</strong>:</p> <pre><code>class C(object): def __init__(self): self.foo = 'bar' def __output(self): print self.foo C.output = __output c = C() c.output() </code></pre>
2
2009-03-23T18:32:44Z
[ "python", "self", "init" ]
Python, __init__ and self confusion
674,600
<p>Alright, so I was taking a look at some source when I came across this:</p> <pre><code>&gt;&gt;&gt; def __parse(self, filename): ... "parse ID3v1.0 tags from MP3 file" ... self.clear() ... try: ... fsock = open(filename, "rb", 0) ... try: ... fsock.see...
3
2009-03-23T18:20:44Z
675,417
<p>Looks like you're a bit confused about classes and object-oriented programming. The 'self' thing is one of the gotchas in python for people coming from other programming languages. IMO the official tutorial doesn't handle it too well. <a href="http://www.gidnetwork.com/b-133.html" rel="nofollow">This tutorial</a>...
1
2009-03-23T22:05:32Z
[ "python", "self", "init" ]
In Python 2.6, How Might You Pass a List Object to a Method Which Expects A List of Arguments?
674,690
<p>I have a list full of various bits of information that I would like to pass to several strings for inclusion via the new string <code>format</code> method. As a toy example, let us define </p> <p><code>thelist = ['a', 'b', 'c']</code></p> <p>I would like to do a print statement like <code>print '{0} {2}'.format(t...
1
2009-03-23T18:39:18Z
674,694
<pre><code>'{0} {2}'.format(*thelist) </code></pre> <p><a href="http://docs.python.org/reference/compound%5Fstmts.html#index-757" rel="nofollow">docs</a></p>
2
2009-03-23T18:41:11Z
[ "python", "list", "arguments" ]
In Python 2.6, How Might You Pass a List Object to a Method Which Expects A List of Arguments?
674,690
<p>I have a list full of various bits of information that I would like to pass to several strings for inclusion via the new string <code>format</code> method. As a toy example, let us define </p> <p><code>thelist = ['a', 'b', 'c']</code></p> <p>I would like to do a print statement like <code>print '{0} {2}'.format(t...
1
2009-03-23T18:39:18Z
674,706
<p><code>.format(*thelist)</code></p> <p>It's part of the calling syntax in Python. I don't know the name either, and I'm not convinced it has one. See the <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists">tutorial</a>.</p> <p>It doesn't just work on lists, though, it works for any i...
10
2009-03-23T18:43:31Z
[ "python", "list", "arguments" ]
benchmarking PHP vs Pylons
674,739
<p>I want to benchmark PHP vs Pylons. I want my comparison of both to be as even as possible, so here is what I came up with:</p> <ul> <li>PHP 5.1.6 with APC, using a smarty template connecting to a MySQL database</li> <li>Python 2.6.1, using Pylons with a mako template connecting the the same MySQL database</li> </ul...
2
2009-03-23T18:52:47Z
674,832
<p>If you're not using an ORM in PHP you should not use the SQLAlchemy ORM or SQL-Expression language either but use raw SQL commands. If you're using APC you should make sure that Python has write privileges to the folder your application is in, or that the .py files are precompiled.</p> <p>Also if you're using the ...
3
2009-03-23T19:15:57Z
[ "php", "python", "pylons", "benchmarking" ]
benchmarking PHP vs Pylons
674,739
<p>I want to benchmark PHP vs Pylons. I want my comparison of both to be as even as possible, so here is what I came up with:</p> <ul> <li>PHP 5.1.6 with APC, using a smarty template connecting to a MySQL database</li> <li>Python 2.6.1, using Pylons with a mako template connecting the the same MySQL database</li> </ul...
2
2009-03-23T18:52:47Z
674,919
<ol> <li><p>your PHP version is out of date, PHP has been in the 5.2.x area for awhile and while there are not massive improvements, there are enough changes that I would say to test anything older is an unfair comparison.</p></li> <li><p>PHP 5.3 is on the verge of becomming final and you should include that in your be...
2
2009-03-23T19:36:33Z
[ "php", "python", "pylons", "benchmarking" ]
Examples for string find in Python
674,764
<p>I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1.</p>
45
2009-03-23T18:57:43Z
674,774
<p>I'm not sure what you're looking for, do you mean <a href="http://docs.python.org/library/stdtypes.html#str.find"><code>find()</code></a>?</p> <pre><code>&gt;&gt;&gt; x = "Hello World" &gt;&gt;&gt; x.find('World') 6 &gt;&gt;&gt; x.find('Aloha'); -1 </code></pre>
87
2009-03-23T19:00:13Z
[ "python", "string", "find" ]
Examples for string find in Python
674,764
<p>I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1.</p>
45
2009-03-23T18:57:43Z
674,775
<p>you can use <a href="http://docs.python.org/library/stdtypes.html?highlight=index#str.index"><code>str.index</code></a> too:</p> <pre><code>&gt;&gt;&gt; 'sdfasdf'.index('cc') Traceback (most recent call last): File "&lt;pyshell#144&gt;", line 1, in &lt;module&gt; 'sdfasdf'.index('cc') ValueError: substring no...
37
2009-03-23T19:00:24Z
[ "python", "string", "find" ]
Examples for string find in Python
674,764
<p>I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1.</p>
45
2009-03-23T18:57:43Z
674,780
<p><code>find( sub[, start[, end]])</code></p> <p>Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. </p> <p>From <a href="http://www.python...
2
2009-03-23T19:01:32Z
[ "python", "string", "find" ]
Examples for string find in Python
674,764
<p>I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1.</p>
45
2009-03-23T18:57:43Z
674,781
<p>Honestly, this is the sort of situation where I just open up Python on the command line and start messing around:</p> <pre><code> &gt;&gt;&gt; x = "Dana Larose is playing with find()" &gt;&gt;&gt; x.find("Dana") 0 &gt;&gt;&gt; x.find("ana") 1 &gt;&gt;&gt; x.find("La") 5 &gt;&gt;&gt; x.find("La", 6) -1 </cod...
14
2009-03-23T19:02:04Z
[ "python", "string", "find" ]
Examples for string find in Python
674,764
<p>I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1.</p>
45
2009-03-23T18:57:43Z
674,790
<p>From <a href="http://docs.python.org/library/stdtypes.html">here</a>:</p> <p>str.find(sub[, start[, end]])<br /> Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return...
27
2009-03-23T19:03:50Z
[ "python", "string", "find" ]
Examples for string find in Python
674,764
<p>I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1.</p>
45
2009-03-23T18:57:43Z
12,258,082
<p>If you want to search for the last instance of a string in a text, you can run rfind.</p> <p>Example: </p> <pre><code> s="Hello" print s.rfind('l') </code></pre> <p>output: 3 </p> <p>*no import needed</p> <p><strong>Complete syntax:</strong></p> <pre><code>stringEx.rfind(substr, beg=0, end=len(stringEx)) ...
4
2012-09-04T06:44:36Z
[ "python", "string", "find" ]
Examples for string find in Python
674,764
<p>I am trying to find some examples but no luck. Does anyone know of some examples on the net? I would like to know what it returns when it can't find, and how to specify from start to end, which I guess is going to be 0, -1.</p>
45
2009-03-23T18:57:43Z
19,063,947
<p>Try this:</p> <pre><code>with open(file_dmp_path, 'rb') as file: fsize = bsize = os.path.getsize(file_dmp_path) word_len = len(SEARCH_WORD) while True: p = file.read(bsize).find(SEARCH_WORD) if p &gt; -1: pos_dec = file.tell() - (bsize - p) file.seek(pos_dec + word_len) bsize = fsize...
0
2013-09-28T06:11:36Z
[ "python", "string", "find" ]
OCR for sheet music
675,077
<p>Im considering doing a small project as a part of my masters for doing ocr just for sheetmusic instead of text.</p> <p>I think PIL and Python would be fine for simple proof of concept O"notes"R.</p> <p>My question is: Has anyone got any "dont do it with PIL use xyz instead" or something in that alley?</p> <p>EDIT...
17
2009-03-23T20:24:49Z
675,111
<p>You may be interested in contributing to <a href="http://sites.google.com/site/ocropus" rel="nofollow">this project</a>. Other than that, best of luck with your masters. </p>
2
2009-03-23T20:32:09Z
[ "python", "ocr" ]
OCR for sheet music
675,077
<p>Im considering doing a small project as a part of my masters for doing ocr just for sheetmusic instead of text.</p> <p>I think PIL and Python would be fine for simple proof of concept O"notes"R.</p> <p>My question is: Has anyone got any "dont do it with PIL use xyz instead" or something in that alley?</p> <p>EDIT...
17
2009-03-23T20:24:49Z
675,142
<p><a href="http://www.musitek.com/" rel="nofollow">http://www.musitek.com/</a> has commercial offerings -- you can look at their user guide and other specifications to get some hints as to how to proceed.</p>
2
2009-03-23T20:38:56Z
[ "python", "ocr" ]
OCR for sheet music
675,077
<p>Im considering doing a small project as a part of my masters for doing ocr just for sheetmusic instead of text.</p> <p>I think PIL and Python would be fine for simple proof of concept O"notes"R.</p> <p>My question is: Has anyone got any "dont do it with PIL use xyz instead" or something in that alley?</p> <p>EDIT...
17
2009-03-23T20:24:49Z
1,872,875
<p>My project ended with a report and some python software. Find it here:</p> <ul> <li><a href="https://dl.dropboxusercontent.com/u/204603/Noder/project.latest.pdf" rel="nofollow">Report</a></li> <li><a href="https://github.com/svrist/preomr" rel="nofollow">Code</a></li> </ul> <p>The gist of it is: It is hard to do g...
8
2009-12-09T10:07:36Z
[ "python", "ocr" ]
TLS connection with timeouts (and a few other difficulties)
675,130
<p>I have a HTTP client in Python which needs to use TLS. I need not only to make encrypted connections but also to retrieve info from the remote machine, such as the certificate issuer. I need to make connection to many HTTP servers, often badly behaved, so I absolutely need to have a timeout. With non-TLS connections...
2
2009-03-23T20:36:33Z
675,234
<p>Although I've never used it for exactly this purpose, <a href="http://twistedmatrix.com" rel="nofollow">Twisted</a> should do what you want. The only downside is that it's a rather large library, and you will also need to install <a href="http://pyopenssl.sourceforge.net/" rel="nofollow">PyOpenSSL</a> (Twisted depe...
1
2009-03-23T21:07:43Z
[ "python", "ssl" ]
TLS connection with timeouts (and a few other difficulties)
675,130
<p>I have a HTTP client in Python which needs to use TLS. I need not only to make encrypted connections but also to retrieve info from the remote machine, such as the certificate issuer. I need to make connection to many HTTP servers, often badly behaved, so I absolutely need to have a timeout. With non-TLS connections...
2
2009-03-23T20:36:33Z
741,811
<p>I assume the problems you're having is the following, you're opening a connection using PyOpenSSL and you always get a WantReadError exception. And you can't distinguish between this error and a timeout. Consider the following example:</p> <pre><code>#!/usr/bin/python import OpenSSL import socket import struct c...
1
2009-04-12T13:59:50Z
[ "python", "ssl" ]
TLS connection with timeouts (and a few other difficulties)
675,130
<p>I have a HTTP client in Python which needs to use TLS. I need not only to make encrypted connections but also to retrieve info from the remote machine, such as the certificate issuer. I need to make connection to many HTTP servers, often badly behaved, so I absolutely need to have a timeout. With non-TLS connections...
2
2009-03-23T20:36:33Z
1,441,827
<p>I would also recommend <a href="http://twistedmatrix.com/" rel="nofollow">Twisted</a>, and using <a href="http://chandlerproject.org/Projects/MeTooCrypto" rel="nofollow">M2Crypto</a> for the <a href="http://svn.osafoundation.org/m2crypto/trunk/M2Crypto/SSL/TwistedProtocolWrapper.py" rel="nofollow">TLS parts</a>.</p>...
0
2009-09-17T23:20:35Z
[ "python", "ssl" ]
TLS connection with timeouts (and a few other difficulties)
675,130
<p>I have a HTTP client in Python which needs to use TLS. I need not only to make encrypted connections but also to retrieve info from the remote machine, such as the certificate issuer. I need to make connection to many HTTP servers, often badly behaved, so I absolutely need to have a timeout. With non-TLS connections...
2
2009-03-23T20:36:33Z
30,604,711
<p>One simple solution could be to change the socket type depending on the operation. I tested this with gnutls and it worked:</p> <ol> <li>Do settimeout() on the socket before doing connect() on the bare socket wrapped by gnutls, that way connect() is subject to the timeout as you wanted.</li> <li>Make sure you remov...
0
2015-06-02T19:16:25Z
[ "python", "ssl" ]
python class __getitem__ negative index handling
675,140
<p>Is there a common function to do this? Right now I'm just doing the following (and overriding __len__)</p> <pre><code>idx &lt; 0: idx = len(self) + idx if idx &lt; 0 or idx &gt;= len(self): raise IndexError, "array index (%d) out of range [0, %d)" %(idx, len(self)) </code></pre>
1
2009-03-23T20:37:38Z
675,191
<p>That seems fine to me. I don't think there is a better or built-in way to do that; overriding is about providing your own functionality, after all.</p> <p>Edited to remove rather stupid suggestion.</p>
3
2009-03-23T20:52:14Z
[ "python", "class", "indexing" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,175
<p>It's definitely possible to implement properties in other languages. VB and F# for example have explicit property support. But these both target the CLR which has property support. </p> <p>VB.</p> <pre><code>Public Property Name As String Get return "someName" End Get Set ... End Set End Proper...
1
2009-03-23T20:46:31Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,183
<p>In C# properties are mostly just a compiler feature. The compiler generates special methods <code>get_PropertyName</code> and <code>set_PropertyName</code> and works out the calls and so forth. It also set the <code>specialname</code> IL property of the methods.</p> <p>If your language of choice supports some kind ...
6
2009-03-23T20:49:51Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,196
<p>The convention is to implement a <code>get_PropertyName()</code> and a <code>set_PropertyName()</code> method (that's all it is in the CLR as well. Properties are just syntactic sugar in VB.NET/C# - which is why a change from field to property or vice-versa is breaking and requires client code to recompile.</p> <pr...
-1
2009-03-23T20:53:23Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,197
<p>Delphi has a property pattern (with Setter and Getter methods), which also can be used in interfaces. Properties with "published" visibility also will be displayed in the IDE object inspector.</p> <p>A class definition with a property would look like this:</p> <pre><code>TFoo = class private FBar: string; proc...
2
2009-03-23T20:53:55Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,198
<p>Python definitely supports properties:</p> <pre><code>class Foo(object): def get_length_inches(self): return self.length_meters * 39.0 def set_length_inches(self, val): self.length_meters = val/39.0 length_inches = property(get_length_inches, set_length_inches) </code></pre> <p>Start...
19
2009-03-23T20:54:43Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,204
<p>I think this is the Python equivalent</p> <pre><code>class Length( object ): conversion = 39.0 def __init__( self, value ): self.set(value) def get( self ): return self.length_metres def set( self, value ): self.length_metres= value metres= property( get, set ) def ge...
2
2009-03-23T20:55:32Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,213
<p>ActionScript 3 (javascript on steroids) has get/set syntax also</p>
0
2009-03-23T20:57:44Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,216
<p>Delphi, from which C# is derived, has had properties from the word go. And the word go was about 15 years ago.</p>
4
2009-03-23T20:58:51Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,227
<p>Sadly, I haven't tried it myself yet, but I read that it was possible to implement properties in PHP through __set and __get magic methods. Here's a <a href="http://blog.dougalmatthews.com/2008/07/php-%5F%5Fset-and-%5F%5Fget-magic-methods/" rel="nofollow">blog post</a> on this subject.</p>
1
2009-03-23T21:04:20Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,256
<p>You can make something like it with <a href="http://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members" rel="nofollow">PHP5 magic functions</a>.</p> <pre><code>class Length { public $metres; public function __get($name) { if ($name == 'inches') return $this-&gt;metr...
0
2009-03-23T21:12:38Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,257
<p>Most dynamic languages support something like that. In Smalltalk and Ruby, fields are not directly exposed - The only way to get at them is through a method. In other words - All variables are private. Ruby has some macros (class methods really), to make it simpler to type:</p> <pre><code>class Thing attr_accesso...
3
2009-03-23T21:12:47Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,281
<p>In <a href="https://developer.mozilla.org/En/Core%5FJavaScript%5F1.5%5FGuide:Creating%5FNew%5FObjects:Defining%5FGetters%5Fand%5FSetters" rel="nofollow">JavaScript</a>:</p> <pre><code>var object = { // .. other property definitions ... get length_inches(){ return this.length_metres * 39.0; }, set length_inche...
8
2009-03-23T21:21:40Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,300
<p>You could do it in all sorts of languages, with varying degrees of syntactic sugar and magic. Python, as already mentioned, provides support for this (and, using decorators you could definitely clean it up even more). PHP could provide a reasonable facsimile with appropriate __get() and __set() methods (probably s...
0
2009-03-23T21:26:57Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,369
<p>When I first played with Visual Basic (like, version 1 or something) the first thing I did was try to recreate properties in C++. Probably before templates were available to me at the time, but now it would be something like:</p> <pre><code>template &lt;class TValue, class TOwner, class TKey&gt; class property { ...
0
2009-03-23T21:48:15Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,394
<p>Out of the box in VB (that's VB 6.0, not VB.net) and VBScript!</p> <pre><code>Public Property Get LengthInches() As Double LengthInches = LengthMetres * 39 End Property Public Property Let LengthInches(Value As Double) LengthMetres = Value / 39 End Property </code></pre> <p>Also possible to fake quite nicely ...
3
2009-03-23T21:58:53Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
675,435
<p>In Objective-C 2.0 / Cocoa:</p> <pre><code>@interface MyClass : NSObject { int myInt; NSString *myString; } @property int myInt; @property (nonatomic, copy) NSString *myString; @end </code></pre> <p>Then in the implementation, simply specify:</p> <pre><code>@synthesize myInt, myString; </code></pre> <p...
2
2009-03-23T22:13:32Z
[ "c#", "php", "javascript", "python", "properties" ]
Is it possible to implement properties in languages other than C#?
675,161
<p>During a bout of C# and WPF recently, I got to like C#'s properties:</p> <pre><code>public double length_inches { get { return length_metres * 39.0; } set { length_metres = value/39.0; } } </code></pre> <p>Noticing, of course, that length_metres may change from being a field to a property, and the code nee...
2
2009-03-23T20:43:04Z
676,139
<p><a href="http://boo.codehaus.org/Fields%2BAnd%2BProperties" rel="nofollow">Boo</a> is a .NET language very similar to Python, but with static typing. It can implement properties: </p> <pre><code>class MyClass: //a field, initialized to the value 1 regularfield as int = 1 //default access level: protected ...
0
2009-03-24T04:15:15Z
[ "c#", "php", "javascript", "python", "properties" ]
Tab-completion in Python interpreter in OS X Terminal
675,370
<p>Several months ago, I wrote a <a href="http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html">blog post</a> detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that...
21
2009-03-23T21:48:29Z
675,583
<p>This works for me on both Linux bash and OS X 10.4</p> <pre><code>import readline import rlcompleter readline.parse_and_bind('tab: complete') </code></pre>
1
2009-03-23T23:11:58Z
[ "python", "osx", "configuration", "interpreter", "tab-completion" ]
Tab-completion in Python interpreter in OS X Terminal
675,370
<p>Several months ago, I wrote a <a href="http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html">blog post</a> detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that...
21
2009-03-23T21:48:29Z
685,421
<p>To avoid having to use more GPL code, Apple doesn't include a real readline. Instead it uses the BSD-licensed <a href="http://www.thrysoee.dk/editline/">libedit</a>, which is only mostly-readline-compatible. Build your own Python (or use Fink or MacPorts) if you want completion.</p>
8
2009-03-26T11:47:57Z
[ "python", "osx", "configuration", "interpreter", "tab-completion" ]
Tab-completion in Python interpreter in OS X Terminal
675,370
<p>Several months ago, I wrote a <a href="http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html">blog post</a> detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that...
21
2009-03-23T21:48:29Z
987,402
<p>This should work under Leopard's python:</p> <pre><code>import rlcompleter import readline readline.parse_and_bind ("bind ^I rl_complete") </code></pre> <p>Whereas this one does not:</p> <pre><code>import readline, rlcompleter readline.parse_and_bind("tab: complete") </code></pre> <p>Save it in ~/.pythonrc.py an...
54
2009-06-12T15:43:41Z
[ "python", "osx", "configuration", "interpreter", "tab-completion" ]
Tab-completion in Python interpreter in OS X Terminal
675,370
<p>Several months ago, I wrote a <a href="http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html">blog post</a> detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that...
21
2009-03-23T21:48:29Z
1,258,115
<p>here is a full cross platform version of loading tab completion for Windows/OS X/Linux in one shot:</p> <pre><code>#Code UUID = '9301d536-860d-11de-81c8-0023dfaa9e40' import sys try: import readline except ImportError: try: import pyreadline as readline # throw open a browse...
11
2009-08-11T01:52:21Z
[ "python", "osx", "configuration", "interpreter", "tab-completion" ]
Tab-completion in Python interpreter in OS X Terminal
675,370
<p>Several months ago, I wrote a <a href="http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html">blog post</a> detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that...
21
2009-03-23T21:48:29Z
23,908,884
<p>If after trying the above, it still doesn't work, then try to execute in the shell:</p> <pre><code>sudo easy_install readline </code></pre> <p>Then, create <em>~/.profile</em> file with the content:</p> <pre><code>export PYTHONSTARTUP=$HOME/.pythonrc.py </code></pre> <p>and a <em>~/.pythonrc.py</em> file with th...
1
2014-05-28T10:17:56Z
[ "python", "osx", "configuration", "interpreter", "tab-completion" ]
Tab-completion in Python interpreter in OS X Terminal
675,370
<p>Several months ago, I wrote a <a href="http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html">blog post</a> detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that...
21
2009-03-23T21:48:29Z
37,261,714
<p>The documented way to tell libedit (the Mac OS semi-readline) from the real one is: if "libedit" in readline.<strong>doc</strong>: pass # Mac case else: pass # GNU readline case</p>
0
2016-05-16T19:25:27Z
[ "python", "osx", "configuration", "interpreter", "tab-completion" ]
learning python 3.0 on ubuntu
675,754
<p>[resolved]</p> <p>I tweaked the preferences in komodo edit and ended up with:</p> <p>don't auto indent</p> <p>don't allow file contents to override tab settings</p> <p>prefer tab characters over spaces</p> <p>4 spaces per indent</p> <p>4 width of each tab char</p> <p>I also set komodo to show whitespace and t...
0
2009-03-24T00:40:59Z
675,765
<p>The example used python 2.x , since <code>python</code> apparently referred to python2.x (for some x), not python3.0 (which is good, since most programs are for 2.x).</p> <p>The second two examples used python 3.0 . You mixed tabs and spaces in your source, and should get rid of the tab characters (don't retype-- u...
2
2009-03-24T00:44:07Z
[ "python", "ubuntu", "development-environment", "komodo" ]
Full examples of using pySerial package
676,172
<p>Can someone please show me a full python sample code that uses <strong>pyserial</strong>, i have the package and am wondering how to send the AT commands and read them back!</p>
63
2009-03-24T04:38:58Z
676,240
<pre><code>import serial ser = serial.Serial(0) # open first serial port print ser.portstr # check which port was really used ser.write("hello") # write a string ser.close() # close port </code></pre> <p>use <a href="http://pyserial.wiki.sourceforge.net/pySerial">http://pyserial.wiki.sourceforg...
40
2009-03-24T05:26:04Z
[ "python", "modem", "pyserial" ]
Full examples of using pySerial package
676,172
<p>Can someone please show me a full python sample code that uses <strong>pyserial</strong>, i have the package and am wondering how to send the AT commands and read them back!</p>
63
2009-03-24T04:38:58Z
676,257
<p>I have not used pyserial but based on the API documentation at <a href="http://pyserial.wiki.sourceforge.net/pySerial" rel="nofollow">http://pyserial.wiki.sourceforge.net/pySerial</a> it seems like a very nice interface. It might be worth double-checking the specification for AT commands of the device/radio/whateve...
0
2009-03-24T05:40:55Z
[ "python", "modem", "pyserial" ]
Full examples of using pySerial package
676,172
<p>Can someone please show me a full python sample code that uses <strong>pyserial</strong>, i have the package and am wondering how to send the AT commands and read them back!</p>
63
2009-03-24T04:38:58Z
7,654,527
<p>Blog post <a href="http://www.varesano.net/blog/fabio/serial%20rs232%20connections%20python">Serial RS232 connections in Python</a></p> <pre><code>import time import serial # configure the serial connections (the parameters differs on the device you are connecting to) ser = serial.Serial( port='/dev/ttyUSB1', ...
66
2011-10-04T21:57:12Z
[ "python", "modem", "pyserial" ]
Full examples of using pySerial package
676,172
<p>Can someone please show me a full python sample code that uses <strong>pyserial</strong>, i have the package and am wondering how to send the AT commands and read them back!</p>
63
2009-03-24T04:38:58Z
15,589,849
<p><a href="http://www.roman10.net/serial-port-communication-in-python/comment-page-1/#comment-1877" rel="nofollow">http://www.roman10.net/serial-port-communication-in-python/comment-page-1/#comment-1877</a></p> <pre><code>#!/usr/bin/python import serial, time #initialization and open the port #possible timeout valu...
14
2013-03-23T17:29:18Z
[ "python", "modem", "pyserial" ]
How do I generate test data for my Python script?
676,198
<p>A equation takes values in the following form :</p> <pre><code> x = [0x02,0x00] # which is later internally converted to in the called function to 0x300 y = [0x01, 0xFF] z = [0x01, 0x0F] </code></pre> <p>How do I generate a series of test values for this function ? for instance I want to send a 100 o...
3
2009-03-24T04:57:57Z
676,213
<p>use generators:</p> <pre><code>def gen_xyz( max_iteration ): for i in xrange( 0, max_iteration ): # code which will generate next ( x, y, z ) yield ( x, y, z ) for x, y, z in gen_xyz( 1000 ): f( x, y, z ) </code></pre>
3
2009-03-24T05:05:29Z
[ "python" ]
How do I generate test data for my Python script?
676,198
<p>A equation takes values in the following form :</p> <pre><code> x = [0x02,0x00] # which is later internally converted to in the called function to 0x300 y = [0x01, 0xFF] z = [0x01, 0x0F] </code></pre> <p>How do I generate a series of test values for this function ? for instance I want to send a 100 o...
3
2009-03-24T04:57:57Z
676,359
<p>The hex() function?</p> <pre><code>import random for i in range(10): a1, a2 = random.randint(1,100), random.randint(1,100) x = [hex(a1), hex(a2)] print x </code></pre> <p>..outputs something similar to..</p> <pre><code>['0x21', '0x4f'] ['0x59', '0x5c'] ['0x61', '0x40'] ['0x57', '0x45'] ['0x1a', '0x11'...
1
2009-03-24T06:48:50Z
[ "python" ]
Python and text manipulation
676,253
<p>I want to learn a text manipulation language and I have zeroed in on Python. Apart from text manipulation Python is also used for numerical applications, machine learning, AI, etc. </p> <p>My question is how do I approach the learning of Python language so that I am quickly able to write sophisticated text manipula...
8
2009-03-24T05:36:54Z
676,268
<p>I found the object.__doc__ and dir(obj) commands incredibly useful in learning the language.</p> <p>e.g.</p> <pre><code>a = "test,test,test" </code></pre> <p>What can I do with a? dir(a). Seems I can split a.</p> <pre><code>vec = a.split (",") </code></pre> <p>What is vec? vec.__doc__:</p> <p>"new list init...
2
2009-03-24T05:50:40Z
[ "python", "text" ]
Python and text manipulation
676,253
<p>I want to learn a text manipulation language and I have zeroed in on Python. Apart from text manipulation Python is also used for numerical applications, machine learning, AI, etc. </p> <p>My question is how do I approach the learning of Python language so that I am quickly able to write sophisticated text manipula...
8
2009-03-24T05:36:54Z
676,271
<p>Beyond regular expressions here are some important features:</p> <ul> <li>Generators, see <a href="http://www.dabeaz.com/generators-uk/">Generator Tricks for Systems Programmers</a> by David Beazley for a lot of great examples to pipeline unlimited amounts of text through generators.</li> </ul> <p>For tools, I rec...
18
2009-03-24T05:51:36Z
[ "python", "text" ]
Python and text manipulation
676,253
<p>I want to learn a text manipulation language and I have zeroed in on Python. Apart from text manipulation Python is also used for numerical applications, machine learning, AI, etc. </p> <p>My question is how do I approach the learning of Python language so that I am quickly able to write sophisticated text manipula...
8
2009-03-24T05:36:54Z
676,286
<p>There's a book <a href="http://gnosis.cx/TPiP/" rel="nofollow">Text Processing in Python</a>. I didn't read it myself yet but I've read other articles of this author and generally they're a good staff.</p>
4
2009-03-24T05:59:43Z
[ "python", "text" ]
Python and text manipulation
676,253
<p>I want to learn a text manipulation language and I have zeroed in on Python. Apart from text manipulation Python is also used for numerical applications, machine learning, AI, etc. </p> <p>My question is how do I approach the learning of Python language so that I am quickly able to write sophisticated text manipula...
8
2009-03-24T05:36:54Z
18,003,280
<p>Although I didn't read, <a href="http://rads.stackoverflow.com/amzn/click/B009NLMB8Q" rel="nofollow">Python for Data Analysis by Wes McKinney - 1 edition (October 8, 2012)</a> looks promising. </p>
0
2013-08-01T19:52:11Z
[ "python", "text" ]
Web crawlers and Google App Engine Hosted applications
676,460
<p>Is it impossible to run a web crawler on GAE along side with my app considering the I am running the free startup version?</p>
4
2009-03-24T07:44:38Z
676,771
<p>I suppose you can (i.e., <em>it's not impossible to</em>) run it, but it will be slow and you'll run into <a href="http://code.google.com/appengine/docs/quotas.html" rel="nofollow">limits</a> quite quickly. As CPU quotas are going to be decreased at the end of May even further, I'd recommend against it.</p>
0
2009-03-24T10:14:42Z
[ "python", "google-app-engine", "web-crawler" ]
Web crawlers and Google App Engine Hosted applications
676,460
<p>Is it impossible to run a web crawler on GAE along side with my app considering the I am running the free startup version?</p>
4
2009-03-24T07:44:38Z
677,133
<p>App Engine code only runs in response to HTTP requests, so you can't run a persistent crawler in the background. With the upcoming release of scheduled tasks, you could write a crawler that uses that functionality, but it would be less than ideal.</p>
1
2009-03-24T12:17:12Z
[ "python", "google-app-engine", "web-crawler" ]
Web crawlers and Google App Engine Hosted applications
676,460
<p>Is it impossible to run a web crawler on GAE along side with my app considering the I am running the free startup version?</p>
4
2009-03-24T07:44:38Z
677,320
<p>It's possible. But that's not really an application for appengine just as Arachnid wrote. If you manage to get it working I'll doubt you'll stay in the qotas for free accounts.</p>
0
2009-03-24T13:11:35Z
[ "python", "google-app-engine", "web-crawler" ]
Web crawlers and Google App Engine Hosted applications
676,460
<p>Is it impossible to run a web crawler on GAE along side with my app considering the I am running the free startup version?</p>
4
2009-03-24T07:44:38Z
681,355
<p>While Google hadn't exposed scheduling, queue and background tasks API, you can do any processing only as an answer to external HTTP request. You'd need some heartbeat service that will process one item from crawler's queue at a time (not to hit GAE limits).</p> <p>To do crawling from GAE, you have to split your ap...
3
2009-03-25T12:26:35Z
[ "python", "google-app-engine", "web-crawler" ]
Are there any built-in cross-thread events in python?
676,485
<p>Is there any built-in syntax in python that allows me to post a message to specific python thread inside my problem? Like 'queued connected signal' in pyQt or ::PostMessage() in Windows. I need this for asynchronous communication between program parts: there is a number of threads that handle network events and they...
8
2009-03-24T08:04:41Z
676,537
<p>I'm not really sure what you are looking for. But there is certainly no built-in syntax for that. Have a look at the <a href="http://docs.python.org/library/queue.html" rel="nofollow">queue</a> and <a href="http://docs.python.org/library/threading.html" rel="nofollow">threading</a> modules. There is a lot of helpfu...
1
2009-03-24T08:36:10Z
[ "python", "events", "delegates" ]
Are there any built-in cross-thread events in python?
676,485
<p>Is there any built-in syntax in python that allows me to post a message to specific python thread inside my problem? Like 'queued connected signal' in pyQt or ::PostMessage() in Windows. I need this for asynchronous communication between program parts: there is a number of threads that handle network events and they...
8
2009-03-24T08:04:41Z
677,120
<p>The <a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue</a> module is python is well suited to what you're describing.</p> <p>You could have one queue set up that is shared between all your threads. The threads that handle the network events can use queue.put to post events onto the queue. Th...
10
2009-03-24T12:11:51Z
[ "python", "events", "delegates" ]
Is there a cross-platform python low-level API to capture or generate keyboard events?
676,713
<p>I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-@ mapped to "my.email@address", so that every time some prog...
11
2009-03-24T09:48:25Z
676,773
<p>There is no such API. My solution was to write a helper module which would use a different helper depending on the value of <code>os.name</code>.</p> <p>On Windows, use the <a href="http://python.net/crew/mhammond/win32/Downloads.html">Win32 extensions</a>.</p> <p>On Linux, things are a bit more complex since real...
8
2009-03-24T10:15:09Z
[ "python", "cross-platform", "keyboard-events", "low-level-api" ]
Is there a cross-platform python low-level API to capture or generate keyboard events?
676,713
<p>I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-@ mapped to "my.email@address", so that every time some prog...
11
2009-03-24T09:48:25Z
676,799
<p>Cross-platform UI libraries such as <a href="http://wiki.python.org/moin/TkInter" rel="nofollow">Tkinter</a> or <a href="http://www.wxpython.org/" rel="nofollow">wxPython</a> have API for keyboard events. Using these you could map «CTRL» + «@» to an action. </p>
0
2009-03-24T10:23:58Z
[ "python", "cross-platform", "keyboard-events", "low-level-api" ]