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 processing (e.g. math or SQL)</li>
<li>You don't care about distinguishing error types</li>
<li>You don't care where the error occurred</li>
<li>The operations are pure functions, with no side effects.</li>
<li>Failure can be given a reasonable meaning at the higher level (e.g. "No rows matched")</li>
</ul>
| 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 <code>l[x]</code> rather than at <code>x = l.index("foo")</code> if index were to return None. In this example, that's not really a big deal. But imagine that the third line is in some completely different place in a million-line program. This can lead to a bit of a debugging nightmare.</p>
| 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 algorithm, obscuring program flow. On the other hand:</p>
<pre><code>try:
idx = sequence.index(x)
print '%s occurred at position %s.' % (x, idx)
except IndexError:
# do error processing
</code></pre>
<p>In this case, the amount of code is effectively the same, but the main algorithm is unbroken by error handling.</p>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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 <strong><code>self</code></strong> as parameter. Until you create instance there is no <strong><code>self</code></strong>.</p>
<p>Now, I gather, that you're trying to implement <a href="http://en.wikipedia.org/wiki/Singleton_pattern">singleton pattern</a> in Python. There are a few ways to do that.</p>
<p>Also, as of Python 2.6, you can use class <a href="http://www.python.org/dev/peps/pep-0318/">decorators</a>. </p>
<pre><code>def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
...
</code></pre>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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 returning a new
instance of your class. In contrast,
<strong>__init__</strong> doesn't return anything; it's only responsible for initializing the
instance after it's been created.</p>
<p>In general, you shouldn't need to
override <strong>__new__</strong> unless you're
subclassing an immutable type like
str, int, unicode or tuple.</p>
</blockquote>
<p>From: <a href="http://mail.python.org/pipermail/tutor/2008-April/061426.html">http://mail.python.org/pipermail/tutor/2008-April/061426.html</a></p>
<p>You should consider that what you are trying to do is usually done with a <a href="http://en.wikipedia.org/wiki/Factory%5Fobject">Factory</a> and that's the best way to do it. Using <strong>__new__</strong> is not a good clean solution so please consider the usage of a factory. Here you have <a href="http://code.activestate.com/recipes/86900/">a good factory example</a>.</p>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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>__call__</code>, possibly-- I don't know for sure).</p>
<blockquote>
<p>I wasn't expecting this. Can anyone tell me why this is happening and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
</blockquote>
<p>You could have <code>__init__</code> do nothing if it's already been initialized, or you could write a new metaclass with a new <code>__call__</code> that only calls <code>__init__</code> on new instances, and otherwise just returns <code>__new__(...)</code>.</p>
| -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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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 instance or not nor should it, because you're doing something very unusual here.</p>
<p>You could add an attribute to the object in the __init__ function to indicate that it's been initialised. Check for the existence of that attribute as the first thing in __init__ and don't proceed any further if it has been.</p>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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 arguments and then
modifying the newly-created instance as necessary before returning it.</p>
<p>...</p>
<p>If __new__() does not return an instance of cls, then the new
instance's __init__() method will not be invoked.</p>
<p>__new__() is intended mainly to allow subclasses of immutable
types (like int, str, or tuple) to customize instance creation.</p>
</blockquote>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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 <strong>constructor</strong>, which is basically just a block of code that operates on the new instance (using the arguments provided to the constructor expression) to set up whatever initial conditions are desired. In Python, this corresponds to the class' <code>__init__</code> method.</p>
<p>Python's <code>__new__</code> is nothing more and nothing less than similar per-class customisation of the "allocate a new instance" part. This of course allows you to do unusual things such as returning an existing instance rather than allocating a new one. So in Python, we shouldn't really think of this part as necessarily involving allocation; all that we require is that <code>__new__</code> comes up with a suitable instance from somewhere.</p>
<p>But it's still only half of the job, and there's no way for the Python system to know that sometimes you want to run the other half of the job (<code>__init__</code>) afterwards and sometimes you don't. If you want that behavior, you have to say so explicitly.</p>
<p>Often, you can refactor so you only need <code>__new__</code>, or so you don't need <code>__new__</code>, or so that <code>__init__</code> behaves differently on an already-initialised object. But if you really want to, Python does actually allow you to redefine "the job", so that <code>SomeClass(arg1, arg2)</code> doesn't necessarily call <code>__new__</code> followed by <code>__init__</code>. To do this, you need to create a metaclass, and define its <code>__call__</code> method.</p>
<p>A metaclass is just the class of a class. And a class' <code>__call__</code> method controls what happens when you call instances of the class. So a <em>metaclass</em>' <code>__call__</code> method controls what happens when you call a class; i.e. it allows you to <strong>redefine the instance-creation mechanism from start to finish</strong>. This is the level at which you can most elegantly implement a completely non-standard instance creation process such as the singleton pattern. In fact, with less than 10 lines of code you can implement a <code>Singleton</code> metaclass that then doesn't even require you to futz with <code>__new__</code> <strong>at all</strong>, and can turn <em>any</em> otherwise-normal class into a singleton by simply adding <code>__metaclass__ = Singleton</code>!</p>
<pre><code>class Singleton(type):
def __init__(self, *args, **kwargs):
super(Singleton, self).__init__(*args, **kwargs)
self.__instance = None
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super(Singleton, self).__call__(*args, **kwargs)
return self.__instance
</code></pre>
<p>However this is probably deeper magic than is really warranted for this situation!</p>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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 forwarding the call down to the subclass <code>__init__</code>. This convention of calling <code>__init__</code> after <code>__new__</code> helps that work as expected.</p>
<p>The <code>__init__</code> still needs to allow for any parameters the superclass <code>__new__</code> needed, but failing to do so will usually create a clear runtime error. And the <code>__new__</code> should probably explicitly allow for <code>*args</code> and '**kw', to make it clear that extension is OK.</p>
<p>It is generally bad form to have both <code>__new__</code> and <code>__init__</code> in the same class at the same level of inheritance, because of the behavior the original poster described.</p>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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 cls._agents[number]
def __init__(self, number):
self.number = number
def __eq__(self, rhs):
return self.number == rhs.number
Agent("a") is Agent("a") == True
</code></pre>
<p>I used this page as a resource <a href="http://infohost.nmt.edu/tcc/help/pubs/python/web/new-new-method.html">http://infohost.nmt.edu/tcc/help/pubs/python/web/new-new-method.html</a></p>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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 <code>__init__</code> will be executed.</p>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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</strong> is the first step in instance construction, invoked
before <strong>init</strong>. </p>
<p>The <strong>new</strong> method is called with the class as its
first argument; its responsibility is to return a new instance of that
class. </p>
<p>Compare this to <strong>init</strong>: <strong>init</strong> is called with an instance
as its first argument, and it doesn't return anything; its
responsibility is to initialize the instance. </p>
<p>There are situations
where a new instance is created without calling <strong>init</strong> (for example
when the instance is loaded from a pickle). There is no way to create
a new instance without calling <strong>new</strong> (although in some cases you can
get away with calling a base class's <strong>new</strong>).</p>
</blockquote>
<p>Regarding what you wish to achieve, there also in same doc info about Singleton pattern</p>
<pre><code>class Singleton(object):
def __new__(cls, *args, **kwds):
it = cls.__dict__.get("__it__")
if it is not None:
return it
cls.__it__ = it = object.__new__(cls)
it.init(*args, **kwds)
return it
def init(self, *args, **kwds):
pass
</code></pre>
<p>you may also use this implementation from PEP 318, using a decorator</p>
<pre><code>def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
...
</code></pre>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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, one would notice two calls. The first call is to an "new" method, and then next call is to the init method(which is the actual call to the user defined constructor). This two step process enables creation of the actual instance before calling the constructor method of the class which is just another method of that instance.</p>
<p>Now, in the case of Python, <strong>new</strong> is a added facility that is accessible to the user. Java does not provide that flexibility, due to its typed nature. If a language provided that facility, then the implementor of <strong>new</strong> could do many things in that method before returning the instance, including creating a totally new instance of a unrelated object in some cases. And, this approach also works out well for especially for immutable types in the case of Python. </p>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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...) initialized by <code>__init__</code> again and again.</p>
<p>Here is the generic approach to Singleton pattern which extends vartec answer above and fixes it:</p>
<pre><code>def SingletonClass(cls):
class Single(cls):
__doc__ = cls.__doc__
_initialized = False
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Single, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self, *args, **kwargs):
if self._initialized:
return
super(Single, self).__init__(*args, **kwargs)
self.__class__._initialized = True # Its crucial to set this variable on the class!
return Single
</code></pre>
<p>Full story is <a href="http://tech.zarmory.com/2015/01/python-singleton-pattern-generic.html" rel="nofollow">here</a>.</p>
<p>Another approach, which in fact involves <code>__new__</code> is to use classmethods:</p>
<pre><code>class Singleton(object):
__initialized = False
def __new__(cls, *args, **kwargs):
if not cls.__initialized:
cls.__init__(*args, **kwargs)
cls.__initialized = True
return cls
class MyClass(Singleton):
@classmethod
def __init__(cls, x, y):
print "init is here"
@classmethod
def do(cls):
print "doing stuff"
</code></pre>
<p>Please pay attention, that with this approach you need to decorate ALL of your methods with <code>@classmethod</code>, because you'll never use any real instance of <code>MyClass</code>.</p>
| 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 and how I implement this functionality otherwise? (apart from putting the implementation into the <code>__new__</code> which feels quite hacky).</p>
<p>Here's an example:</p>
<pre><code>class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
</code></pre>
<p>Outputs:</p>
<pre><code>NEW
INIT
EXISTS
INIT
EXISTS
INIT
</code></pre>
<p>Why?</p>
| 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
class A(object):
__metaclass__ = M
def __init__(self, key):
print 'INIT'
self.key = key
print
a1 = A('aaa')
a2 = A('bbb')
a3 = A('aaa')
</code></pre>
<p>outputs:</p>
<pre><code>NEW
INIT
NEW
INIT
EXISTS
</code></pre>
<p>NB As a side effect <code>M._dict</code> property automatically becomes accessible from <code>A</code> as <code>A._dict</code> so take care not to overwrite it incidentally.</p>
| 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_node_t {
u_int bit; /* flag if this node used */
prefix_t *prefix; /* who we are in patricia tree */
struct _patricia_node_t *l, *r; /* left and right children */
struct _patricia_node_t *parent;/* may be used */
void *data; /* pointer to data */
void *user1; /* pointer to usr data (ex. route flap info) */
} patricia_node_t;
</code></pre>
<p>Specifically:</p>
<pre><code>>>> N = patricia.patricia_node_t()
>>> assert N.data == None
>>> N.data = 1
TypeError: in method 'patricia_node_t_data_set', argument 2 of type 'void *'
</code></pre>
<p>Now my C is weak. From what I read in the SWIG book, I think this means I need to pass it a pointer to data. According to <a href="http://www.swig.org/Doc1.3/Python.html#Python%5Fnn18" rel="nofollow">the book</a> :</p>
<blockquote>
<p>Also, if you need to pass the raw pointer value to some external python library, you can do it by casting the pointer object to an integer... However, the inverse operation is not possible, i.e., you can't build a Swig pointer object from a raw integer value. </p>
</blockquote>
<p>Questions:</p>
<ol>
<li>am I understanding this correctly?</li>
<li>how do I get around this? Is %extends? typemap? Specifics would be very helpful.</li>
</ol>
<p>Notes:</p>
<ol>
<li>I can't change the C source, but I can extend it in additional .h files or the interface .i file. </li>
<li>From what I understand, that "data" field should be able to contain "anything" for some reasonable value of "anything" that I don't really know.</li>
</ol>
| 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->data = data;
}
...
int value = 1;
set(tree, &value); // OK! HOORAY!
set(tree, value); // NOT OK! FIRE SCORPIONS!
</code></pre>
<p>And it seems to me you're doing the Python equivalent of <code>set(tree, value)</code>. Now I'm not an expert with SWIG but perhaps you could pass a tuple instead of an integer? Does <code>N.data = (1,)</code> work? This was the answer suggested by an <a href="http://www.franz.com/support/tech%5Fcorner/swig111605.lhtml" rel="nofollow">Allegro CL + SWIG</a> example, but I dunno how well it applies to Python.</p>
| 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_node_t {
u_int bit; /* flag if this node used */
prefix_t *prefix; /* who we are in patricia tree */
struct _patricia_node_t *l, *r; /* left and right children */
struct _patricia_node_t *parent;/* may be used */
void *data; /* pointer to data */
void *user1; /* pointer to usr data (ex. route flap info) */
} patricia_node_t;
</code></pre>
<p>Specifically:</p>
<pre><code>>>> N = patricia.patricia_node_t()
>>> assert N.data == None
>>> N.data = 1
TypeError: in method 'patricia_node_t_data_set', argument 2 of type 'void *'
</code></pre>
<p>Now my C is weak. From what I read in the SWIG book, I think this means I need to pass it a pointer to data. According to <a href="http://www.swig.org/Doc1.3/Python.html#Python%5Fnn18" rel="nofollow">the book</a> :</p>
<blockquote>
<p>Also, if you need to pass the raw pointer value to some external python library, you can do it by casting the pointer object to an integer... However, the inverse operation is not possible, i.e., you can't build a Swig pointer object from a raw integer value. </p>
</blockquote>
<p>Questions:</p>
<ol>
<li>am I understanding this correctly?</li>
<li>how do I get around this? Is %extends? typemap? Specifics would be very helpful.</li>
</ol>
<p>Notes:</p>
<ol>
<li>I can't change the C source, but I can extend it in additional .h files or the interface .i file. </li>
<li>From what I understand, that "data" field should be able to contain "anything" for some reasonable value of "anything" that I don't really know.</li>
</ol>
| 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_node_t {
u_int bit; /* flag if this node used */
prefix_t *prefix; /* who we are in patricia tree */
struct _patricia_node_t *l, *r; /* left and right children */
struct _patricia_node_t *parent;/* may be used */
void *data; /* pointer to data */
void *user1; /* pointer to usr data (ex. route flap info) */
} patricia_node_t;
</code></pre>
<p>Specifically:</p>
<pre><code>>>> N = patricia.patricia_node_t()
>>> assert N.data == None
>>> N.data = 1
TypeError: in method 'patricia_node_t_data_set', argument 2 of type 'void *'
</code></pre>
<p>Now my C is weak. From what I read in the SWIG book, I think this means I need to pass it a pointer to data. According to <a href="http://www.swig.org/Doc1.3/Python.html#Python%5Fnn18" rel="nofollow">the book</a> :</p>
<blockquote>
<p>Also, if you need to pass the raw pointer value to some external python library, you can do it by casting the pointer object to an integer... However, the inverse operation is not possible, i.e., you can't build a Swig pointer object from a raw integer value. </p>
</blockquote>
<p>Questions:</p>
<ol>
<li>am I understanding this correctly?</li>
<li>how do I get around this? Is %extends? typemap? Specifics would be very helpful.</li>
</ol>
<p>Notes:</p>
<ol>
<li>I can't change the C source, but I can extend it in additional .h files or the interface .i file. </li>
<li>From what I understand, that "data" field should be able to contain "anything" for some reasonable value of "anything" that I don't really know.</li>
</ol>
| 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)
>>> a={ 'a': 6, 'b': 1, 'c': 2 }
>>> sorted(a.items(), key=lambda (key,value): value)
[('b', 1), ('c', 2), ('a', 6)]
</code></pre>
<p>In Python 3, the lambda expression will have to be changed to <code>lambda x: x[1]</code>.</p>
| 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 the key function <a href="http://svn.python.org/projects/python/trunk/Modules/operator.c">be in C</a> instead of Python as it is right now with the lambda.</p>
<pre><code>import operator
sorted(d.iteritems(), key=operator.itemgetter(1))
</code></pre>
<p>Hooray!</p>
| 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', 'score name')
d = {'John':5, 'Alex':10, 'Richard': 7}
</code></pre>
<p>sorting with lowest score first:</p>
<pre><code>worst = sorted(Player(v,k) for (k,v) in d.items())
</code></pre>
<p>sorting with highest score first:</p>
<pre><code>best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)
</code></pre>
<p>The order of 'key' and 'value' in the listed tuples is (value, key), but now you can get the name and score of, let's say the second-best player (index=1) very Pythonically like this:</p>
<pre><code> player = best[1]
player.name
'Richard'
player.score
7
</code></pre>
| 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>>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(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 necessary.</p>
<p>See: <a href="http://docs.python.org/library/stdtypes.html#dict.items">items()</a>, <a href="http://docs.python.org/library/stdtypes.html#dict.iteritems">iteritems()</a></p>
<hr>
<p>In Python 3.x, you would not use <code>iteritems</code> (which no longer exists), but instead use <code>items</code>, which now returns a "view" into the dictionary items. See the <a href="http://docs.python.org/release/3.0.1/whatsnew/3.0.html#views-and-iterators-instead-of-lists">What's New</a> document for Python 3.0, and the new <a href="http://docs.python.org/py3k/library/stdtypes.html#dictionary-view-objects">documentation on views</a>.</p>
| 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, <code>iteritems</code> is preferable since it uses a generator to produce the (key,value) tuples rather than having to keep the entire list in memory.</p>
<pre><code>Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>>
</code></pre>
| 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-comprehensions" rel="nofollow">Read more about list comprehensions</a> if you like, it's very interesting what you can do with them.</p>
| 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>>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> [(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':10, 'Richard': 7}
</code></pre>
<p>You can list the items as tuples, sorted if you like, and get the name and score of, let's say the player with the highest score (index=0) very Pythonically like this:</p>
<pre><code>>>> player = best[0]
>>> player.name
'Alex'
>>> player.score
10
</code></pre>
<p>How to do this:</p>
<p><b>list in random order or keeping order of <a href="http://docs.python.org/library/collections.html#collections.OrderedDict" rel="nofollow">collections.OrderedDict</a>:</b></p>
<pre><code>import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())
</code></pre>
<p><b> in order, sorted by value ('score'):</b></p>
<pre><code>import collections
Player = collections.namedtuple('Player', 'score name')
</code></pre>
<p>sorted with lowest score first:</p>
<pre><code>worst = sorted(Player(v,k) for (k,v) in d.items())
</code></pre>
<p>sorted with highest score first:</p>
<pre><code>best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)
</code></pre>
| 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>>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]
>>>
</code></pre>
| 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>>>> def __parse(self, filename):
... "parse ID3v1.0 tags from MP3 file"
... self.clear()
... try:
... fsock = open(filename, "rb", 0)
... try:
... fsock.seek(-128, 2)
... tagdata = fsock.read(128)
... finally:
... fsock.close()
... if tagdata[:3] == 'TAG':
... for tag, (start, end, parseFunc) in self.tagDataMap.items():
... self[tag] = parseFunc(tagdata[start:end])
... except IOError:
... pass
...
</code></pre>
<p>So, I decided to test it out.</p>
<pre><code> >>> __parse("blah.mp3")
</code></pre>
<p>And, I received this error: </p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __parse() takes exactly 2 arguments (1 given)
</code></pre>
<p>This wouldn't be the first time I've encountered this, I keep thinking I'm meant to include self in the argument parameter list, but I know that that's not right. Could someone explain to me why this happens a lot with code I try to play around with, I suppose its due to my level of understanding about the terms, I barely even understand what init or self does, or why it's relevant. def x(b): print b is the same as def x(self, b): self.b = b print self.b isn't it? Why does it matter so much!</p>
<p>I just want a basic explanation, so I can get this out of my mind,thanks.</p>
| 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 Adder( object ):
def __init__( self ):
self.grand_total = 0
def add( self, a, b ):
self.grand_total += a+b
return a+b
</code></pre>
<p>Notes.</p>
<ol>
<li><p>The function does not use <code>self</code>.</p></li>
<li><p>The class method does use <code>self</code>. Generally, all instance methods will use <code>self</code>, unless they have specific decorators like <code>@classmethod</code> that say otherwise.</p></li>
<li><p>The function doesn't depend on anything else else.</p></li>
<li><p>The class method depends on being called by an instance of the class <code>Adder</code>; further, it depends on that instance of the class <code>Adder</code> having been initialized correctly. In this case, the initialization function (<code>__init__</code>) has assured that each instance of <code>Adder</code> always has an instance variable named <code>grand_total</code> and that instance variable has an initial value of <code>0</code>.</p></li>
<li><p>You can't pull the <code>add</code> method function out of the <code>Adder</code> class and use it separately. It is not a stand-alone function. It was defined <em>inside</em> the class and has certain expectations because of that location <em>inside</em> the class.</p></li>
</ol>
| 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>>>> def __parse(self, filename):
... "parse ID3v1.0 tags from MP3 file"
... self.clear()
... try:
... fsock = open(filename, "rb", 0)
... try:
... fsock.seek(-128, 2)
... tagdata = fsock.read(128)
... finally:
... fsock.close()
... if tagdata[:3] == 'TAG':
... for tag, (start, end, parseFunc) in self.tagDataMap.items():
... self[tag] = parseFunc(tagdata[start:end])
... except IOError:
... pass
...
</code></pre>
<p>So, I decided to test it out.</p>
<pre><code> >>> __parse("blah.mp3")
</code></pre>
<p>And, I received this error: </p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __parse() takes exactly 2 arguments (1 given)
</code></pre>
<p>This wouldn't be the first time I've encountered this, I keep thinking I'm meant to include self in the argument parameter list, but I know that that's not right. Could someone explain to me why this happens a lot with code I try to play around with, I suppose its due to my level of understanding about the terms, I barely even understand what init or self does, or why it's relevant. def x(b): print b is the same as def x(self, b): self.b = b print self.b isn't it? Why does it matter so much!</p>
<p>I just want a basic explanation, so I can get this out of my mind,thanks.</p>
| 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>>>> def __parse(self, filename):
... "parse ID3v1.0 tags from MP3 file"
... self.clear()
... try:
... fsock = open(filename, "rb", 0)
... try:
... fsock.seek(-128, 2)
... tagdata = fsock.read(128)
... finally:
... fsock.close()
... if tagdata[:3] == 'TAG':
... for tag, (start, end, parseFunc) in self.tagDataMap.items():
... self[tag] = parseFunc(tagdata[start:end])
... except IOError:
... pass
...
</code></pre>
<p>So, I decided to test it out.</p>
<pre><code> >>> __parse("blah.mp3")
</code></pre>
<p>And, I received this error: </p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __parse() takes exactly 2 arguments (1 given)
</code></pre>
<p>This wouldn't be the first time I've encountered this, I keep thinking I'm meant to include self in the argument parameter list, but I know that that's not right. Could someone explain to me why this happens a lot with code I try to play around with, I suppose its due to my level of understanding about the terms, I barely even understand what init or self does, or why it's relevant. def x(b): print b is the same as def x(self, b): self.b = b print self.b isn't it? Why does it matter so much!</p>
<p>I just want a basic explanation, so I can get this out of my mind,thanks.</p>
| 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>>>> def __parse(self, filename):
... "parse ID3v1.0 tags from MP3 file"
... self.clear()
... try:
... fsock = open(filename, "rb", 0)
... try:
... fsock.seek(-128, 2)
... tagdata = fsock.read(128)
... finally:
... fsock.close()
... if tagdata[:3] == 'TAG':
... for tag, (start, end, parseFunc) in self.tagDataMap.items():
... self[tag] = parseFunc(tagdata[start:end])
... except IOError:
... pass
...
</code></pre>
<p>So, I decided to test it out.</p>
<pre><code> >>> __parse("blah.mp3")
</code></pre>
<p>And, I received this error: </p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __parse() takes exactly 2 arguments (1 given)
</code></pre>
<p>This wouldn't be the first time I've encountered this, I keep thinking I'm meant to include self in the argument parameter list, but I know that that's not right. Could someone explain to me why this happens a lot with code I try to play around with, I suppose its due to my level of understanding about the terms, I barely even understand what init or self does, or why it's relevant. def x(b): print b is the same as def x(self, b): self.b = b print self.b isn't it? Why does it matter so much!</p>
<p>I just want a basic explanation, so I can get this out of my mind,thanks.</p>
| 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>>>> def __parse(self, filename):
... "parse ID3v1.0 tags from MP3 file"
... self.clear()
... try:
... fsock = open(filename, "rb", 0)
... try:
... fsock.seek(-128, 2)
... tagdata = fsock.read(128)
... finally:
... fsock.close()
... if tagdata[:3] == 'TAG':
... for tag, (start, end, parseFunc) in self.tagDataMap.items():
... self[tag] = parseFunc(tagdata[start:end])
... except IOError:
... pass
...
</code></pre>
<p>So, I decided to test it out.</p>
<pre><code> >>> __parse("blah.mp3")
</code></pre>
<p>And, I received this error: </p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __parse() takes exactly 2 arguments (1 given)
</code></pre>
<p>This wouldn't be the first time I've encountered this, I keep thinking I'm meant to include self in the argument parameter list, but I know that that's not right. Could someone explain to me why this happens a lot with code I try to play around with, I suppose its due to my level of understanding about the terms, I barely even understand what init or self does, or why it's relevant. def x(b): print b is the same as def x(self, b): self.b = b print self.b isn't it? Why does it matter so much!</p>
<p>I just want a basic explanation, so I can get this out of my mind,thanks.</p>
| 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> seems quite good.</p>
<p>If you've ever learnt java, <code>self</code> in python is very similar to <code>this</code> in java. The difference is that python requires you to list <code>self</code> as the first argument to every function in a class definition.</p>
<p>If python is your first programming language (or your first object-oriented language), you could remember this as a simple rule-of-thumb: if you're defining a function that's part of a class, you need to include <code>self</code> as the first argument. If you're defining a function that's not part of a class, you shouldn't include <code>self</code> in the arguments. You can't take a class function and make it stand-alone without doing some (or possibly a lot of) extra coding. Finally, never include <code>self</code> as an argument when <em>calling</em> a function.</p>
<p>There are exceptions to those rules, but they're not worth worrying about now.</p>
| 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(thelist)</code> and <code>print '{1} {2}'.format(thelist)</code></p>
<p>When I run this, I receive the message <code>IndexError: tuple index out of range</code>; when mucking about, it clearly takes the whole list as a single object. I would, of course, rather it translate <code>thelist</code> to <code>'a', 'b', 'c'</code>.</p>
<p>I tried using a tuple and received the same error.</p>
<p>What on Earth is this particular technique called? If I knew the name, I could have searched for it. "Expand" is clearly not it. "Explode" doesn't yield anything useful.</p>
<p>My actual use is much longer and more tedious than the toy example.</p>
| 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(thelist)</code> and <code>print '{1} {2}'.format(thelist)</code></p>
<p>When I run this, I receive the message <code>IndexError: tuple index out of range</code>; when mucking about, it clearly takes the whole list as a single object. I would, of course, rather it translate <code>thelist</code> to <code>'a', 'b', 'c'</code>.</p>
<p>I tried using a tuple and received the same error.</p>
<p>What on Earth is this particular technique called? If I knew the name, I could have searched for it. "Expand" is clearly not it. "Explode" doesn't yield anything useful.</p>
<p>My actual use is much longer and more tedious than the toy example.</p>
| 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 iterable object.</p>
| 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>
<p>Is there anything that I should change in that setup to make it a more fair comparison?</p>
<p>I'm going to run it on a spare server that has almost no activity, 2G of ram and 4 cores.</p>
<p>Any suggestions of how I should or shouldn't benchmark them? I plan on using ab to do the actual benchmarking.</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/77086/which-is-faster-python-webpages-or-php-webpages">Which is faster, python webpages or php webpages?</a></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 smarty cache consider enabling the Mako cache as well for fairness sake.</p>
<p>However there is a catch: the Python MySQL adapter is incredible bad. For the database connections you will probably notice either slow performance (if SQLAlchemy performs the unicode decoding for itself) or it leaks memory (if the MySQL adapter does that).</p>
<p>Both issues you don't have with PHP because there is no unicode support. So for total fairness you would have to disable unicode in the database connection (which however is an incredible bad idea).</p>
<p>So: there doesn't seem to be a fair way to compare PHP and Pylons :)</p>
| 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>
<p>Is there anything that I should change in that setup to make it a more fair comparison?</p>
<p>I'm going to run it on a spare server that has almost no activity, 2G of ram and 4 cores.</p>
<p>Any suggestions of how I should or shouldn't benchmark them? I plan on using ab to do the actual benchmarking.</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/77086/which-is-faster-python-webpages-or-php-webpages">Which is faster, python webpages or php webpages?</a></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 benchmarks as there are massive improvements to PHP 5.x as well as being the last version of 5.x, if you really want to split hairs PHP 6 is also in alpha/beta and that's a heavy overhaul also.</p></li>
<li><p>Comparing totally different languages can be interesting but don't forget you are comparing apples to oranges, and the biggest bottleneck in any 2/3/N-Tier app is waiting on I/O. So the biggest factor is your database speed, comparing PHP vs Python VS ASP.Net purely on speed is pointless as all 3 of them will execute in less than 1 second but yet you can easily wait 2-3 seconds on your database query, depending on your hardware and what you are doing.</p></li>
<li><p><strong>If you are worried what is faster, you're taking the absolute wrong approach to choosing a platform.</strong> There are more important issues, such as (not in order):</p>
<p>a. How easily can I find skilled devs in that platform</p>
<p>b. How much do those skilled devs cost</p>
<p>c. How much ROI does the language offer</p>
<p>d. How feature rich is the language</p></li>
</ol>
| 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>>>> x = "Hello World"
>>> x.find('World')
6
>>> 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>>>> 'sdfasdf'.index('cc')
Traceback (most recent call last):
File "<pyshell#144>", line 1, in <module>
'sdfasdf'.index('cc')
ValueError: substring not found
>>> 'sdfasdf'.index('df')
1
</code></pre>
| 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.org/doc/2.4.4/lib/string-methods.html" rel="nofollow">the docs</a>.</p>
| 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> >>> x = "Dana Larose is playing with find()"
>>> x.find("Dana")
0
>>> x.find("ana")
1
>>> x.find("La")
5
>>> x.find("La", 6)
-1
</code></pre>
<p>Python's interpreter makes this sort of experimentation easy. (Same goes for other languages with a similar interpreter)</p>
| 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 -1 if sub is not found."</p>
<p>So, some examples:</p>
<pre><code>>>> str = "abcdefioshgoihgs sijsiojs "
>>> str.find('a')
0
>>> str.find('g')
10
>>> str.find('s',11)
15
>>> str.find('s',15)
15
>>> str.find('s',16)
17
>>> str.find('s',11,14)
-1
</code></pre>
| 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))
</code></pre>
| 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 > -1:
pos_dec = file.tell() - (bsize - p)
file.seek(pos_dec + word_len)
bsize = fsize - file.tell()
if file.tell() < fsize:
seek = file.tell() - word_len + 1
file.seek(seek)
else:
break
</code></pre>
| 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: My delicius links regarding the subject if anyone is interested: <a href="http://delicious.com/seet/DIKU-09b4%2Bb1">http://delicious.com/seet/DIKU-09b4%2Bb1</a></p>
<p>=========================================================================</p>
<p>EDIT2:</p>
<p>Actually, now I know a lot more about OCR for sheet music or OMR as it is called.</p>
<p>Within academia the area has been researched since late 60/early 70 and building an OMR system is not a simple task. To get a summary of the problems and the research until early 2000 you could read <a href="http://www.springerlink.com/content/x1nv36548113k51u/">"The challenge of Optical Music Recognition"</a> which is quite successful in drawing up the lines of the field.</p>
<p>Regarding existing software I know of at least these:</p>
<ul>
<li><a href="http://www.visiv.co.uk/">Sharpeye</a></li>
<li><a href="http://www.neuratron.com/photoscore.htm">Photoscore</a></li>
<li><a href="http://www.musitek.com/">Smartscore X</a></li>
<li><a href="http://www.capella-software.com/capscan.htm">Capella Scan</a></li>
<li><a href="http://www.myriad-online.com/en/products/pdftomusic.htm">PdfToMusic</a></li>
</ul>
<p>And my unscientific tests gave me the idea that photoscore was the most robust one.</p>
<p>For Opensource software <a href="https://audiveris.dev.java.net/">Audiveris</a> is the only complete thing I found and is written in Java.</p>
<p>Regarding my original question I am using <a href="http://gamera.informatik.hsnr.de/">Gamera</a>. Gamera is an opensource tool for document image analysis which provides tools to do all the basic stuff needed for analysing images for recognition. Gamera has a python interface and the possibility to write c++ "toolkits". For example is it possible to <a href="http://lionel.kr.hs-niederrhein.de/~dalitz/data/projekte/stafflines/">download and use a staffline removal toolkit for gamera.</a></p>
| 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: My delicius links regarding the subject if anyone is interested: <a href="http://delicious.com/seet/DIKU-09b4%2Bb1">http://delicious.com/seet/DIKU-09b4%2Bb1</a></p>
<p>=========================================================================</p>
<p>EDIT2:</p>
<p>Actually, now I know a lot more about OCR for sheet music or OMR as it is called.</p>
<p>Within academia the area has been researched since late 60/early 70 and building an OMR system is not a simple task. To get a summary of the problems and the research until early 2000 you could read <a href="http://www.springerlink.com/content/x1nv36548113k51u/">"The challenge of Optical Music Recognition"</a> which is quite successful in drawing up the lines of the field.</p>
<p>Regarding existing software I know of at least these:</p>
<ul>
<li><a href="http://www.visiv.co.uk/">Sharpeye</a></li>
<li><a href="http://www.neuratron.com/photoscore.htm">Photoscore</a></li>
<li><a href="http://www.musitek.com/">Smartscore X</a></li>
<li><a href="http://www.capella-software.com/capscan.htm">Capella Scan</a></li>
<li><a href="http://www.myriad-online.com/en/products/pdftomusic.htm">PdfToMusic</a></li>
</ul>
<p>And my unscientific tests gave me the idea that photoscore was the most robust one.</p>
<p>For Opensource software <a href="https://audiveris.dev.java.net/">Audiveris</a> is the only complete thing I found and is written in Java.</p>
<p>Regarding my original question I am using <a href="http://gamera.informatik.hsnr.de/">Gamera</a>. Gamera is an opensource tool for document image analysis which provides tools to do all the basic stuff needed for analysing images for recognition. Gamera has a python interface and the possibility to write c++ "toolkits". For example is it possible to <a href="http://lionel.kr.hs-niederrhein.de/~dalitz/data/projekte/stafflines/">download and use a staffline removal toolkit for gamera.</a></p>
| 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: My delicius links regarding the subject if anyone is interested: <a href="http://delicious.com/seet/DIKU-09b4%2Bb1">http://delicious.com/seet/DIKU-09b4%2Bb1</a></p>
<p>=========================================================================</p>
<p>EDIT2:</p>
<p>Actually, now I know a lot more about OCR for sheet music or OMR as it is called.</p>
<p>Within academia the area has been researched since late 60/early 70 and building an OMR system is not a simple task. To get a summary of the problems and the research until early 2000 you could read <a href="http://www.springerlink.com/content/x1nv36548113k51u/">"The challenge of Optical Music Recognition"</a> which is quite successful in drawing up the lines of the field.</p>
<p>Regarding existing software I know of at least these:</p>
<ul>
<li><a href="http://www.visiv.co.uk/">Sharpeye</a></li>
<li><a href="http://www.neuratron.com/photoscore.htm">Photoscore</a></li>
<li><a href="http://www.musitek.com/">Smartscore X</a></li>
<li><a href="http://www.capella-software.com/capscan.htm">Capella Scan</a></li>
<li><a href="http://www.myriad-online.com/en/products/pdftomusic.htm">PdfToMusic</a></li>
</ul>
<p>And my unscientific tests gave me the idea that photoscore was the most robust one.</p>
<p>For Opensource software <a href="https://audiveris.dev.java.net/">Audiveris</a> is the only complete thing I found and is written in Java.</p>
<p>Regarding my original question I am using <a href="http://gamera.informatik.hsnr.de/">Gamera</a>. Gamera is an opensource tool for document image analysis which provides tools to do all the basic stuff needed for analysing images for recognition. Gamera has a python interface and the possibility to write c++ "toolkits". For example is it possible to <a href="http://lionel.kr.hs-niederrhein.de/~dalitz/data/projekte/stafflines/">download and use a staffline removal toolkit for gamera.</a></p>
| 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 good OMR and takes a lot of effort. I didn't have the time to do complete OMR (and it looks like it's not that needed after all). </p>
<p>I implemented a tool that can do preprocessing of sheet music before handing it to a OMR tool like Photoscore or the like. The preprocessing includes removal of lyrics and dynamics as this information is not needed for statistical analysis of the music in large music corpora</p>
| 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,
<code>mysocket.settimeout(5)</code> does what I want.</p>
<p>Among the many TLS Python modules:</p>
<p><a href="http://pypi.python.org/pypi/python-gnutls" rel="nofollow">python-gnutls</a> does not allow to use settimeout() on sockets because
it uses non-blocking sockets:</p>
<pre><code>gnutls.errors.OperationWouldBlock: Function was interrupted.
</code></pre>
<p><a href="http://pyopenssl.sourceforge.net/" rel="nofollow">python-openssl</a> has a similar issue:</p>
<pre><code>OpenSSL.SSL.WantReadError
</code></pre>
<p>The <a href="http://docs.python.org/library/ssl.html" rel="nofollow">SSL module</a> of the standard library does not work with Python
2.5.</p>
<p>Other libraries like <a href="http://trevp.net/tlslite/" rel="nofollow">TLSlite</a> apparently does not give access to
the metadata of the certificate.</p>
<p>The program is threaded so I cannot use signals. I need detailed
control on the HTTP dialog so I cannot use a standard library like urllib2.</p>
<p>Background: this is
the survey project <a href="http://www.dnswitness.net/" rel="nofollow">DNSwitness</a>. Relevant SO threads: <a href="http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call">Timeout on a
Python function call</a> and <a href="http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python">How to limit execution time of a function call in Python</a>.</p>
| 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 depends on it). If you've never used it before, Twisted's callback-based architecture can take some getting used to (you <strong>really</strong> want to read the tutorials before starting).</p>
<p>But aside from that, it's designed around the idea of managing a lot of connections, it of course lets you specify timeouts, reconnects, etc., and you can retrieve certificate info (see <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.ssl.Certificate.html" rel="nofollow">here</a>).</p>
| 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,
<code>mysocket.settimeout(5)</code> does what I want.</p>
<p>Among the many TLS Python modules:</p>
<p><a href="http://pypi.python.org/pypi/python-gnutls" rel="nofollow">python-gnutls</a> does not allow to use settimeout() on sockets because
it uses non-blocking sockets:</p>
<pre><code>gnutls.errors.OperationWouldBlock: Function was interrupted.
</code></pre>
<p><a href="http://pyopenssl.sourceforge.net/" rel="nofollow">python-openssl</a> has a similar issue:</p>
<pre><code>OpenSSL.SSL.WantReadError
</code></pre>
<p>The <a href="http://docs.python.org/library/ssl.html" rel="nofollow">SSL module</a> of the standard library does not work with Python
2.5.</p>
<p>Other libraries like <a href="http://trevp.net/tlslite/" rel="nofollow">TLSlite</a> apparently does not give access to
the metadata of the certificate.</p>
<p>The program is threaded so I cannot use signals. I need detailed
control on the HTTP dialog so I cannot use a standard library like urllib2.</p>
<p>Background: this is
the survey project <a href="http://www.dnswitness.net/" rel="nofollow">DNSwitness</a>. Relevant SO threads: <a href="http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call">Timeout on a
Python function call</a> and <a href="http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python">How to limit execution time of a function call in Python</a>.</p>
| 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
context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
connection = OpenSSL.SSL.Connection(context,s)
connection.connect(("www.gmail.com",443))
# Put the socket in blocking mode
connection.setblocking(1)
# Set the timeout using the setsockopt
tv = struct.pack('ii', int(6), int(0))
connection.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, tv)
print "Connected to " , connection.getpeername()
print "Sate " , connection.state_string()
while True:
try:
connection.do_handshake()
break
except OpenSSL.SSL.WantReadError:
print "Exception"
pass
print "Sate " , connection.state_string()
print connection.send("koekoek\r\n")
while True:
try:
recvstr = connection.recv(1024)
break
except OpenSSL.SSL.WantReadError:
print "Exception"
pass
print recvstr
</code></pre>
<p>This will open an SSL connection to gmail, send an invalid string, read the response and print it. Note that:
* the connection is explicitely set to blocking-mode
* the recv timeout is explicitely set to in this case 6 seconds.</p>
<p>Now what will the behavior be, when the timeout occurs, the WantReadError exception will be thornw, in this case after waiting for 6 seconds. (You can remove the while True to avoid the retry, but in this case i added them for testing). The timeout set on the socket only appears to be effective in the connect() call. </p>
<p>An alternative would be when keeping the sockets in non-blocking mode which probably applies for the GNUTLS case as well is to perform the timekeeping yourself, you get the time when you launch the call, and in the while True, try: except WantReadError you perform the check every time yourself to see if you haven't been waiting for too long.</p>
| 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,
<code>mysocket.settimeout(5)</code> does what I want.</p>
<p>Among the many TLS Python modules:</p>
<p><a href="http://pypi.python.org/pypi/python-gnutls" rel="nofollow">python-gnutls</a> does not allow to use settimeout() on sockets because
it uses non-blocking sockets:</p>
<pre><code>gnutls.errors.OperationWouldBlock: Function was interrupted.
</code></pre>
<p><a href="http://pyopenssl.sourceforge.net/" rel="nofollow">python-openssl</a> has a similar issue:</p>
<pre><code>OpenSSL.SSL.WantReadError
</code></pre>
<p>The <a href="http://docs.python.org/library/ssl.html" rel="nofollow">SSL module</a> of the standard library does not work with Python
2.5.</p>
<p>Other libraries like <a href="http://trevp.net/tlslite/" rel="nofollow">TLSlite</a> apparently does not give access to
the metadata of the certificate.</p>
<p>The program is threaded so I cannot use signals. I need detailed
control on the HTTP dialog so I cannot use a standard library like urllib2.</p>
<p>Background: this is
the survey project <a href="http://www.dnswitness.net/" rel="nofollow">DNSwitness</a>. Relevant SO threads: <a href="http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call">Timeout on a
Python function call</a> and <a href="http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python">How to limit execution time of a function call in Python</a>.</p>
| 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,
<code>mysocket.settimeout(5)</code> does what I want.</p>
<p>Among the many TLS Python modules:</p>
<p><a href="http://pypi.python.org/pypi/python-gnutls" rel="nofollow">python-gnutls</a> does not allow to use settimeout() on sockets because
it uses non-blocking sockets:</p>
<pre><code>gnutls.errors.OperationWouldBlock: Function was interrupted.
</code></pre>
<p><a href="http://pyopenssl.sourceforge.net/" rel="nofollow">python-openssl</a> has a similar issue:</p>
<pre><code>OpenSSL.SSL.WantReadError
</code></pre>
<p>The <a href="http://docs.python.org/library/ssl.html" rel="nofollow">SSL module</a> of the standard library does not work with Python
2.5.</p>
<p>Other libraries like <a href="http://trevp.net/tlslite/" rel="nofollow">TLSlite</a> apparently does not give access to
the metadata of the certificate.</p>
<p>The program is threaded so I cannot use signals. I need detailed
control on the HTTP dialog so I cannot use a standard library like urllib2.</p>
<p>Background: this is
the survey project <a href="http://www.dnswitness.net/" rel="nofollow">DNSwitness</a>. Relevant SO threads: <a href="http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call">Timeout on a
Python function call</a> and <a href="http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python">How to limit execution time of a function call in Python</a>.</p>
| 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 remove the timeout with settimeout(None) or setblocking(1) BEFORE GnuTLS's handshake()</li>
</ol>
| 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 < 0:
idx = len(self) + idx
if idx < 0 or idx >= 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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 Property
</code></pre>
<p>I do not believe javascript or PHP supports property syntax but I'm not very familiar with those languages. It is possible to create field get/set accessor methods in pretty much any language which simulate properties. </p>
<p>Under the hood, .Net properties really just result down to get/set methods. They just have a really nice wrapper :)</p>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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 of preprocessor, you can implement something similar but otherwise you're pretty much stuck with what you got. </p>
<p>And of course, if you're implementing your own .NET language you can do what the C# compiler does as well. </p>
<p>Due to the implementation details, there are actually subtle differences between fields and properties. See <a href="http://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c/653799#653799">this question</a> for details.</p>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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>
<pre><code>public int get_SomeValue() { return someValue; }
public void set_SomeValue(int value) { someValue = value; }
private int someValue = 10;
// client
int someValue = someClass.get_SomeValue();
someClass.set_SomeValue(12);
</code></pre>
| -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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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;
procedure SetBar(Value: string);
function GetBar: string;
public
property Bar: string read GetBar write SetBar;
end;
</code></pre>
<p>or (without Setter / Getter):</p>
<pre><code>TFoo = class
private
FBar: string;
public
property Bar: string read FBar write FBar;
end;
</code></pre>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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>Starting in Python 2.5, syntactic sugar exists for read-only properties, and in 2.6, writable ones as well:</p>
<pre><code>class Foo(object):
# 2.5 or later
@property
def length_inches(self):
return self.length_meters * 39.0
# 2.6 or later
@length_inches.setter
def length_inches(self, val):
self.length_meters = val/39.0
</code></pre>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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 get_inches( self ):
return self.length_metres*self.conversion
def set_inches( self, value ):
self.length_metres= value/self.conversion
inches = property( get_inches, set_inches )
</code></pre>
<p>It works like this.</p>
<pre><code>>>> l=Length(2)
>>> l.metres
2
>>> l.inches
78.0
>>> l.inches=47
>>> l.metres
1.2051282051282051
</code></pre>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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->metres * 39;
}
public function __set($name, $value) {
if ($name == 'inches')
$this->metres = $value/39.0;
}
}
$l = new Length;
$l->metres = 3;
echo $l->inches;
</code></pre>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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_accessor :length_inches
end
</code></pre>
<p>will make a getter and a setter for <code>length_inches</code>. Behind the scenes, it's simply generating this:</p>
<pre><code>class Thing
def length_inches
@length_inches
end
def length_inches=(value)
@length_inches = value
end
end
</code></pre>
<p>(Ruby crash-course: The <code>@</code> prefix means it's an instance variable. <code>return</code> is implicit in Ruby. <code>t.length_inches = 42</code> will automatically invoke <code>length_inches=(42)</code>, if <code>t</code> is a <code>Thingy</code>.)</p>
<p>If you later on want to put some logic in the getters/setters, you can simply manually implement the same methods:</p>
<pre><code>class Thing
def length_inches
@length_metres * 39.0
end
def length_inches=(value)
@length_metres = value / 39.0
end
end
</code></pre>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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_inches(value){ this.length_metres = value/39.0; }
};
</code></pre>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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 some indirection to . If you're working with Perl, you could use some source filters to replicate the behavior. Ruby already requires everything to go through </p>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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 <class TValue, class TOwner, class TKey>
class property
{
TOwner *owner_;
public:
property(TOwner *owner)
: owner_(owner) {}
TValue value() const
{
return owner_->get_property(TKey());
}
operator TValue() const
{
return value();
}
TValue operator=(const TValue &value)
{
owner_->set_property(TKey(), value);
return value;
}
};
class my_class
{
public:
my_class()
: first_name(this), limbs(this) {}
struct limbs_k {};
struct first_name_k {};
property<std::string, my_class, first_name_k> first_name;
property<int, my_class, limbs_k> limbs;
std::string get_property(const first_name_k &);
void set_property(const first_name_k &, const std::string &value);
int get_property(const limbs_k &);
void set_property(const limbs_k &, int value);
};
</code></pre>
<p>Note that the "key" parameter is ignored in the implementations of <code>get_property</code>/<code>set_property</code> - it's only there to effectively act as part of the name of the function, via overload resolution.</p>
<p>Now the user of <code>my_class</code> would be able to refer to the public members <code>first_name</code> and <code>limbs</code> in many situations as if they were raw fields, but they merely provide an alternative syntax for calling the corresponding <code>get_property</code>/<code>set_property</code> member functions.</p>
<p>It's not perfect, because there are some situations where you'd have to call value() on a property to get the value, whenever the compiler is unable to infer the required type conversion. Also you might get a warning from the passing of <code>this</code> to members in the constructor, but you could silence that in this case.</p>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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 in PHP creating a class that you extend in combination with naming guidelines, protected members and magic functions. Yuch.</p>
| 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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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>This generates the accessors for that member variable with key-value-coding compliant naming conventions like:</p>
<pre><code>- (void)setMyString:(NSString *)newString
{
[myString autorelease];
myString = [newString copy];
}
</code></pre>
<p>Saves a lot of work typing out your accessors.</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 need not care. WPF can also bind UI elements to object properties very happily.</p>
<p>When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.</p>
<p>Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.</p>
<p>The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it? </p>
| 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
//a string field
mystringfield as string = "hello"
//a private field
private _privatefield as int
//a public field
public publicfield as int = 3
//a static field: the value is stored in one place and shared by all
//instances of this class
static public staticfield as int = 4
//a property (default access level: public)
RegularProperty as int:
get: //getter: called when you retrieve property
return regularfield
set: //setter: notice the special "value" variable
regularfield = value
ReadOnlyProperty as int:
get:
return publicfield
SetOnlyProperty as int:
set:
publicfield = value
//a field with an automatically generated property
[Property(MyAutoProperty)]
_mypropertyfield as int = 5
</code></pre>
| 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 I sometimes have to switch to the standard interpreter due to IPython unicode issues.</p>
<p>Recently I've done some work in OS X. To my discontent, the script doesn't seem to work for OS X's Terminal application. I'm hoping some of you with experience in OS X might be able to help me trouble-shoot it so it can work in Terminal, as well.</p>
<p>I am reproducing the code below</p>
<pre><code>import atexit
import os.path
try:
import readline
except ImportError:
pass
else:
import rlcompleter
class IrlCompleter(rlcompleter.Completer):
"""
This class enables a "tab" insertion if there's no text for
completion.
The default "tab" is four spaces. You can initialize with '\t' as
the tab if you wish to use a genuine tab.
"""
def __init__(self, tab=' '):
self.tab = tab
rlcompleter.Completer.__init__(self)
def complete(self, text, state):
if text == '':
readline.insert_text(self.tab)
return None
else:
return rlcompleter.Completer.complete(self,text,state)
#you could change this line to bind another key instead tab.
readline.parse_and_bind('tab: complete')
readline.set_completer(IrlCompleter('\t').complete)
# Restore our command-line history, and save it when Python exits.
history_path = os.path.expanduser('~/.pyhistory')
if os.path.isfile(history_path):
readline.read_history_file(history_path)
atexit.register(lambda x=history_path: readline.write_history_file(x))
</code></pre>
<p>Note that I have slightly edited it from the version on my blog post so that the <code>IrlCompleter</code> is initialized with a true tab, which seems to be what is output by the Tab key in Terminal.</p>
| 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 I sometimes have to switch to the standard interpreter due to IPython unicode issues.</p>
<p>Recently I've done some work in OS X. To my discontent, the script doesn't seem to work for OS X's Terminal application. I'm hoping some of you with experience in OS X might be able to help me trouble-shoot it so it can work in Terminal, as well.</p>
<p>I am reproducing the code below</p>
<pre><code>import atexit
import os.path
try:
import readline
except ImportError:
pass
else:
import rlcompleter
class IrlCompleter(rlcompleter.Completer):
"""
This class enables a "tab" insertion if there's no text for
completion.
The default "tab" is four spaces. You can initialize with '\t' as
the tab if you wish to use a genuine tab.
"""
def __init__(self, tab=' '):
self.tab = tab
rlcompleter.Completer.__init__(self)
def complete(self, text, state):
if text == '':
readline.insert_text(self.tab)
return None
else:
return rlcompleter.Completer.complete(self,text,state)
#you could change this line to bind another key instead tab.
readline.parse_and_bind('tab: complete')
readline.set_completer(IrlCompleter('\t').complete)
# Restore our command-line history, and save it when Python exits.
history_path = os.path.expanduser('~/.pyhistory')
if os.path.isfile(history_path):
readline.read_history_file(history_path)
atexit.register(lambda x=history_path: readline.write_history_file(x))
</code></pre>
<p>Note that I have slightly edited it from the version on my blog post so that the <code>IrlCompleter</code> is initialized with a true tab, which seems to be what is output by the Tab key in Terminal.</p>
| 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 I sometimes have to switch to the standard interpreter due to IPython unicode issues.</p>
<p>Recently I've done some work in OS X. To my discontent, the script doesn't seem to work for OS X's Terminal application. I'm hoping some of you with experience in OS X might be able to help me trouble-shoot it so it can work in Terminal, as well.</p>
<p>I am reproducing the code below</p>
<pre><code>import atexit
import os.path
try:
import readline
except ImportError:
pass
else:
import rlcompleter
class IrlCompleter(rlcompleter.Completer):
"""
This class enables a "tab" insertion if there's no text for
completion.
The default "tab" is four spaces. You can initialize with '\t' as
the tab if you wish to use a genuine tab.
"""
def __init__(self, tab=' '):
self.tab = tab
rlcompleter.Completer.__init__(self)
def complete(self, text, state):
if text == '':
readline.insert_text(self.tab)
return None
else:
return rlcompleter.Completer.complete(self,text,state)
#you could change this line to bind another key instead tab.
readline.parse_and_bind('tab: complete')
readline.set_completer(IrlCompleter('\t').complete)
# Restore our command-line history, and save it when Python exits.
history_path = os.path.expanduser('~/.pyhistory')
if os.path.isfile(history_path):
readline.read_history_file(history_path)
atexit.register(lambda x=history_path: readline.write_history_file(x))
</code></pre>
<p>Note that I have slightly edited it from the version on my blog post so that the <code>IrlCompleter</code> is initialized with a true tab, which seems to be what is output by the Tab key in Terminal.</p>
| 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 and execute in .bash_profile</p>
<pre><code>export PYTHONSTARTUP=$HOME/.pythonrc.py
</code></pre>
| 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 I sometimes have to switch to the standard interpreter due to IPython unicode issues.</p>
<p>Recently I've done some work in OS X. To my discontent, the script doesn't seem to work for OS X's Terminal application. I'm hoping some of you with experience in OS X might be able to help me trouble-shoot it so it can work in Terminal, as well.</p>
<p>I am reproducing the code below</p>
<pre><code>import atexit
import os.path
try:
import readline
except ImportError:
pass
else:
import rlcompleter
class IrlCompleter(rlcompleter.Completer):
"""
This class enables a "tab" insertion if there's no text for
completion.
The default "tab" is four spaces. You can initialize with '\t' as
the tab if you wish to use a genuine tab.
"""
def __init__(self, tab=' '):
self.tab = tab
rlcompleter.Completer.__init__(self)
def complete(self, text, state):
if text == '':
readline.insert_text(self.tab)
return None
else:
return rlcompleter.Completer.complete(self,text,state)
#you could change this line to bind another key instead tab.
readline.parse_and_bind('tab: complete')
readline.set_completer(IrlCompleter('\t').complete)
# Restore our command-line history, and save it when Python exits.
history_path = os.path.expanduser('~/.pyhistory')
if os.path.isfile(history_path):
readline.read_history_file(history_path)
atexit.register(lambda x=history_path: readline.write_history_file(x))
</code></pre>
<p>Note that I have slightly edited it from the version on my blog post so that the <code>IrlCompleter</code> is initialized with a true tab, which seems to be what is output by the Tab key in Terminal.</p>
| 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 browser if we fail both readline and pyreadline
except ImportError:
import webbrowser
webbrowser.open("http://ipython.scipy.org/moin/PyReadline/Intro#line-36")
# throw open a browser
#pass
else:
import rlcompleter
if(sys.platform == 'darwin'):
readline.parse_and_bind ("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
</code></pre>
<p>From <a href="http://www.farmckon.net/?p=181">http://www.farmckon.net/?p=181</a></p>
| 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 I sometimes have to switch to the standard interpreter due to IPython unicode issues.</p>
<p>Recently I've done some work in OS X. To my discontent, the script doesn't seem to work for OS X's Terminal application. I'm hoping some of you with experience in OS X might be able to help me trouble-shoot it so it can work in Terminal, as well.</p>
<p>I am reproducing the code below</p>
<pre><code>import atexit
import os.path
try:
import readline
except ImportError:
pass
else:
import rlcompleter
class IrlCompleter(rlcompleter.Completer):
"""
This class enables a "tab" insertion if there's no text for
completion.
The default "tab" is four spaces. You can initialize with '\t' as
the tab if you wish to use a genuine tab.
"""
def __init__(self, tab=' '):
self.tab = tab
rlcompleter.Completer.__init__(self)
def complete(self, text, state):
if text == '':
readline.insert_text(self.tab)
return None
else:
return rlcompleter.Completer.complete(self,text,state)
#you could change this line to bind another key instead tab.
readline.parse_and_bind('tab: complete')
readline.set_completer(IrlCompleter('\t').complete)
# Restore our command-line history, and save it when Python exits.
history_path = os.path.expanduser('~/.pyhistory')
if os.path.isfile(history_path):
readline.read_history_file(history_path)
atexit.register(lambda x=history_path: readline.write_history_file(x))
</code></pre>
<p>Note that I have slightly edited it from the version on my blog post so that the <code>IrlCompleter</code> is initialized with a true tab, which seems to be what is output by the Tab key in Terminal.</p>
| 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 the content:</p>
<pre><code>try:
import readline
except:
print ("Module readline is not available.")
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
</code></pre>
<p>Thanks to <a href="http://stevenbamford.com/2010/01/06/python-tab-completion-in-os-x/" rel="nofollow">Steven Bamford</a> for the easy_install tip, and <a href="https://nicolas.perriault.net/code/2010/python-tab-completion/" rel="nofollow">Nicolas</a> for the file content.</p>
| 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 I sometimes have to switch to the standard interpreter due to IPython unicode issues.</p>
<p>Recently I've done some work in OS X. To my discontent, the script doesn't seem to work for OS X's Terminal application. I'm hoping some of you with experience in OS X might be able to help me trouble-shoot it so it can work in Terminal, as well.</p>
<p>I am reproducing the code below</p>
<pre><code>import atexit
import os.path
try:
import readline
except ImportError:
pass
else:
import rlcompleter
class IrlCompleter(rlcompleter.Completer):
"""
This class enables a "tab" insertion if there's no text for
completion.
The default "tab" is four spaces. You can initialize with '\t' as
the tab if you wish to use a genuine tab.
"""
def __init__(self, tab=' '):
self.tab = tab
rlcompleter.Completer.__init__(self)
def complete(self, text, state):
if text == '':
readline.insert_text(self.tab)
return None
else:
return rlcompleter.Completer.complete(self,text,state)
#you could change this line to bind another key instead tab.
readline.parse_and_bind('tab: complete')
readline.set_completer(IrlCompleter('\t').complete)
# Restore our command-line history, and save it when Python exits.
history_path = os.path.expanduser('~/.pyhistory')
if os.path.isfile(history_path):
readline.read_history_file(history_path)
atexit.register(lambda x=history_path: readline.write_history_file(x))
</code></pre>
<p>Note that I have slightly edited it from the version on my blog post so that the <code>IrlCompleter</code> is initialized with a true tab, which seems to be what is output by the Tab key in Terminal.</p>
| 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 tabs, which eneded up revealing the screwed up sections.</p>
<p>yeah - it's a little picky. :)</p>
<p>[/resolved]</p>
<p>I have installed python 3.0 on ubuntu 8.10 along with komodo-edit ide.</p>
<p>I'm just getting into python, and I'm reading through visual quickstart guide python 2nd ed. (the example below is from that book). I'm getting some really frustrating errors and would really appreciate your thoughts. </p>
<p>I've re-typed and checked tabs many times over. </p>
<p>I'm starting to think that something in the install or setup has gone wrong.</p>
<p>I typed the following into komodo-edit:</p>
<pre><code>#!/usr/bin/python3.0
for row in range(1, 10):
for col in range(1, 10):
p = row * col
if p < 10:
print(' ', end = '')
print(row * col, ' ', end = '')
print()
</code></pre>
<p>I can't test this is IDLE with python 3 - can't seem to get that version of IDLE installed. for now, I'm trying to run from the shell.</p>
<p>first, just using "python" to call the program...</p>
<pre><code>PYTHON [1] $ python ktest.py
File "ktest.py", line 6
print(' ', end = '')
^
SyntaxError: invalid syntax
</code></pre>
<p>now trying different ways of calling the python compiler...</p>
<pre><code>PYTHON [1] $ python ktest.py
File "ktest.py", line 6
print(' ', end = '')
^
SyntaxError: invalid syntax
PYTHON [1] $ python3 ktest.py
File "ktest.py", line 4
p = row * col
^
TabError: inconsistent use of tabs and spaces in indentation
PYTHON [1] $ python3.0 ktest.py
File "ktest.py", line 4
p = row * col
^
TabError: inconsistent use of tabs and spaces in indentation
</code></pre>
| 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-- use regular-expression replacement). Python 3.0 is more sensitive about this than 2.x-- you can get the same behavior using <code>python -tt</code> for 2.x .</p>
| 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.sourceforge.net/pySerial</a> for more examples</p>
| 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/whatever you are dealing with.</p>
<p>Specifically, some require some period of silence before and/or after the AT command for it to enter into command mode. I have encountered some which do not like reads of the response without some delay first.</p>
| 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',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.isOpen()
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
# Python 3 users
# input = input(">> ")
if input == 'exit':
ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
ser.write(input + '\r\n')
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + out
</code></pre>
| 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 values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = "/dev/ttyUSB7"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None #block read
ser.timeout = 1 #non-block read
#ser.timeout = 2 #timeout block read
ser.xonxoff = False #disable software flow control
ser.rtscts = False #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2 #timeout for write
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output
#and discard all that is in buffer
#write data
ser.write("AT+CSQ")
print("write data: AT+CSQ")
time.sleep(0.5) #give the serial port sometime to receive the data
numOfLines = 0
while True:
response = ser.readline()
print("read data: " + response)
numOfLines = numOfLines + 1
if (numOfLines >= 5):
break
ser.close()
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "
</code></pre>
| 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 odd values from a for loop </p>
<pre><code>for i in range(0,300):
# where a,b are derived for a range
x = [a,b]
</code></pre>
<p>My question was a bit unclear so please let my clarify.
what I wanted to ask how I can do <code>x =[a,b]</code> generate different values for <code>a,b</code> </p>
| 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 odd values from a for loop </p>
<pre><code>for i in range(0,300):
# where a,b are derived for a range
x = [a,b]
</code></pre>
<p>My question was a bit unclear so please let my clarify.
what I wanted to ask how I can do <code>x =[a,b]</code> generate different values for <code>a,b</code> </p>
| 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']
['0x4c', '0x49']
['0x40', '0x1b']
['0x1f', '0x7']
['0x8', '0x2b']
['0x1e', '0x13']
</code></pre>
| 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 manipulation utilities. Apart from regular expressions in the context of "text manipulation" what language features are more important than others what modules are useful and so on.</p>
| 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 initialized from sequence's items"</p>
<p>What can I do with vec? dir(vec). </p>
<pre><code>vec.sort ()
</code></pre>
<p>etc ...</p>
| 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 manipulation utilities. Apart from regular expressions in the context of "text manipulation" what language features are more important than others what modules are useful and so on.</p>
| 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 recommend looking at the following:</p>
<ul>
<li><p><a href="http://whoosh.ca/">Whoosh</a>, a pure Python search engine that will give you some nice real life examples of parsing text using <a href="http://pyparsing.wikispaces.com/">pyparsing</a> and text processing in Python in general.</p></li>
<li><p>Ned Batcheldor's nice <a href="http://nedbatchelder.com/text/python-parsers.html">reviews of various Python parsing tools</a>.</p></li>
<li><p><a href="http://www.egenix.com/products/python/mxBase/mxTextTools/">mxTextTools</a></p></li>
<li><p><a href="http://docutils.sourceforge.net/">Docutils</a> source code for more advanced text processing in Python, including a sophisticated state machine.</p></li>
</ul>
<p><strong>Edit:</strong> A good links specific to text processing in Python:</p>
<ul>
<li><a href="http://gnosis.cx/TPiP/">Text Processing in Python</a> by David Mertz. I think the book is still available, although it's probably a bit dated now.</li>
</ul>
| 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 manipulation utilities. Apart from regular expressions in the context of "text manipulation" what language features are more important than others what modules are useful and so on.</p>
| 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 manipulation utilities. Apart from regular expressions in the context of "text manipulation" what language features are more important than others what modules are useful and so on.</p>
| 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 application into queue (that stores queue data in Datastore), queue processor that will react to external HTTP heartbeat and your actual crawling logic.</p>
<p>You'd manually have to watch your quota usage and start heartbeat when you have spare quota, and stop if it is used up.</p>
<p>When Google introduces the APIs I've told in the beginning you'd have to rewrite parts that are implemented more effectively via Google API.</p>
<p>UPDATE: Google introduced Task Queue API some time ago. See <a href="http://code.google.com/appengine/docs/python/taskqueue/" rel="nofollow">task queue docs for python</a> and <a href="http://code.google.com/appengine/docs/java/taskqueue/" rel="nofollow">java</a>.</p>
| 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 need to post these events to a single 'logic' thread that translates events safe single-threaded way.</p>
| 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 helpful stuff like Queues, Conditions, Events, Locks and Semaphores that can be used to implement all kind of synchronous and asynchronous communications.</p>
| 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 need to post these events to a single 'logic' thread that translates events safe single-threaded way.</p>
| 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. The logic thread would use queue.get to retrieve events from the queue.</p>
<pre><code>import Queue
# maxsize of 0 means that we can put an unlimited number of events
# on the queue
q = Queue.Queue(maxsize=0)
def network_thread():
while True:
e = get_network_event()
q.put(e)
def logic_thread():
while True:
# This will wait until there are events to process
e = q.get()
process_event(e)
</code></pre>
| 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 program asks me for my email address I just need to type Ctrl-@.</p>
<p>I know such programs already exist, and I am reinventing the wheel... but my goal is just to learn more about low-level keyboard APIs. Moreover, the answer to this question might be useful to other programmers, for example if they want to startup an SSH connection which requires a password, without using pexpect.</p>
<p>Thanks for your help.</p>
<p>Note: there is <a href="http://stackoverflow.com/questions/310576/low-level-keyboard-input-on-windows">a similar question</a> but it is limited to the Windows platform, and does not require python. I am looking for a cross-platform python api. There are also other questions related to keyboard events, but apparently they are not interested in system-wide keyboard events, just application-specific keyboard shortcuts.</p>
<p>Edit: I should probably add a disclaimer here: I do <em>not</em> want to write a keylogger. If I needed a keylogger, I could download one off the web a anyway. ;-)</p>
| 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 OSes protect their users against keyloggers[*]. So here, you will need a root process which watches one of[] the handles in <code>/dev/input/</code>. Your best bet is probably looking for an entry below <code>/dev/input/by-path/</code> which contains the strings <code>"kbd"</code> or <code>"keyboard"</code>. That should work in most cases.</p>
<p>[*]: Jeez, not even my virus/trojan scanner will complain when I start a Python program which hooks into the keyboard events...</p>
| 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 program asks me for my email address I just need to type Ctrl-@.</p>
<p>I know such programs already exist, and I am reinventing the wheel... but my goal is just to learn more about low-level keyboard APIs. Moreover, the answer to this question might be useful to other programmers, for example if they want to startup an SSH connection which requires a password, without using pexpect.</p>
<p>Thanks for your help.</p>
<p>Note: there is <a href="http://stackoverflow.com/questions/310576/low-level-keyboard-input-on-windows">a similar question</a> but it is limited to the Windows platform, and does not require python. I am looking for a cross-platform python api. There are also other questions related to keyboard events, but apparently they are not interested in system-wide keyboard events, just application-specific keyboard shortcuts.</p>
<p>Edit: I should probably add a disclaimer here: I do <em>not</em> want to write a keylogger. If I needed a keylogger, I could download one off the web a anyway. ;-)</p>
| 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"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.