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 |
|---|---|---|---|---|---|---|---|---|---|
"Interfaces" in Python: Yea or Nay?
| 552,058
|
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p>
<p>Just so we're clear, an interface in Python would look something like this:</p>
<pre><code>class ISomething(object):
def some_method():
pass
def some_other_method(some_argument):
pass
</code></pre>
<p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p>
<p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
| 16
|
2009-02-16T02:15:17Z
| 552,087
|
<p>There are some cases where interfaces can be very handy. <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> makes <a href="http://twistedmatrix.com/projects/core/documentation/howto/components.html" rel="nofollow">fairly extensive use</a> of <a href="http://wiki.zope.org/Interfaces/FrontPage" rel="nofollow">Zope interfaces</a>, and in a project I was working on Zope interfaces worked really well. Enthought's traits packaged recently added <a href="http://code.enthought.com/projects/traits/docs/html/traits_user_manual/advanced.html#id15" rel="nofollow">interfaces</a>, but I don't have any experience with them.</p>
<p>Beware overuse though -- duck typing and protocols are a fundamental aspect of Python, only use interfaces if they're absolutely necessary.</p>
| 10
|
2009-02-16T02:40:12Z
|
[
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay?
| 552,058
|
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p>
<p>Just so we're clear, an interface in Python would look something like this:</p>
<pre><code>class ISomething(object):
def some_method():
pass
def some_other_method(some_argument):
pass
</code></pre>
<p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p>
<p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
| 16
|
2009-02-16T02:15:17Z
| 552,093
|
<p>I don't think interfaces would add anything to the code environment.</p>
<ul>
<li>Method definition enforcing happens without them. If an object expected to be have like <code>Foo</code> and have method <code>bar()</code>, and it does't, it will throw an <code>AttributeError</code>.</li>
<li>Simply making sure an interface method gets defined doesn't guarantee its correctness; behavioral unit tests need to be in place anyway. </li>
<li>It's just as effective to write a "read this or die" page describing what methods your object needs to have to be compatible with what you're plugging it in as having elaborate docstrings in an interface class, since you're probably going to have tests for it anyway. One of those tests can be standard for all compatible objects that will check the invocation and return type of each base method.</li>
</ul>
| 6
|
2009-02-16T02:45:25Z
|
[
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay?
| 552,058
|
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p>
<p>Just so we're clear, an interface in Python would look something like this:</p>
<pre><code>class ISomething(object):
def some_method():
pass
def some_other_method(some_argument):
pass
</code></pre>
<p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p>
<p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
| 16
|
2009-02-16T02:15:17Z
| 552,097
|
<p>The pythonic way is to "Ask for forgiveness rather than receive permission". Interfaces are <em>all</em> about receiving permission to perform some operation on an object. Python prefers this:</p>
<pre><code>def quacker(duck):
try:
duck.quack():
except AttributeError:
raise ThisAintADuckException
</code></pre>
| 10
|
2009-02-16T02:46:40Z
|
[
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay?
| 552,058
|
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p>
<p>Just so we're clear, an interface in Python would look something like this:</p>
<pre><code>class ISomething(object):
def some_method():
pass
def some_other_method(some_argument):
pass
</code></pre>
<p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p>
<p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
| 16
|
2009-02-16T02:15:17Z
| 552,112
|
<p>You can create an interface in a dynamically typed language, but there's no enforcement of the interface at compile time. A statically typed language's compiler will warn you if you forget to implement (or mistype!) a method of an interface. Since you receive no such help in a dynamically typed language, your interface declaration serves only as documentation. (Which isn't necessarily bad, it's just that your interface declaration provides no runtime advantage versus writing comments.)</p>
| 4
|
2009-02-16T02:58:27Z
|
[
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay?
| 552,058
|
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p>
<p>Just so we're clear, an interface in Python would look something like this:</p>
<pre><code>class ISomething(object):
def some_method():
pass
def some_other_method(some_argument):
pass
</code></pre>
<p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p>
<p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
| 16
|
2009-02-16T02:15:17Z
| 552,203
|
<p>I'm not sure what the point of that is. Interfaces (of this form, anyway) are largely to work around the lack of multiple inheritance. But Python has MI, so why not just make an abstract class?</p>
<pre><code>class Something(object):
def some_method(self):
raise NotImplementedError()
def some_other_method(self, some_argument):
raise NotImplementedError()
</code></pre>
| 27
|
2009-02-16T03:50:38Z
|
[
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay?
| 552,058
|
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p>
<p>Just so we're clear, an interface in Python would look something like this:</p>
<pre><code>class ISomething(object):
def some_method():
pass
def some_other_method(some_argument):
pass
</code></pre>
<p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p>
<p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
| 16
|
2009-02-16T02:15:17Z
| 552,917
|
<p>In Python 2.6 and later, you can use <a href="http://docs.python.org/library/abc.html">abstract base classes</a> instead. These are useful, because you can then test to see if something implements a given ABC by using "isinstance". As usual in Python, the concept is not as strictly enforced as it would be in a strict language, but it's handy. Moreover there are nice idiomatic ways of declaring abstract methods with decorators - see the link above for examples.</p>
| 11
|
2009-02-16T10:47:32Z
|
[
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay?
| 552,058
|
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p>
<p>Just so we're clear, an interface in Python would look something like this:</p>
<pre><code>class ISomething(object):
def some_method():
pass
def some_other_method(some_argument):
pass
</code></pre>
<p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p>
<p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
| 16
|
2009-02-16T02:15:17Z
| 555,072
|
<p>I personally use interfaces a lot in conjunction with the Zope Component Architecture (ZCA). The advantage is not so much to have interfaces but to be able to use them with adapters and utilities (singletons).</p>
<p>E.g. you could create an adapter which can take a class which implements ISomething but adapts it to the some interface ISomethingElse. Basically it's a wrapper.</p>
<p>The original class would be:</p>
<pre><code>class MyClass(object):
implements(ISomething)
def do_something(self):
return "foo"
</code></pre>
<p>Then imagine interface ISomethingElse has a method do_something_else(). An adapter could look like this:</p>
<pre><code>class SomethingElseAdapter(object):
implements(ISomethingElse)
adapts(ISomething)
def __init__(self, context):
self.context = context
def do_something_else():
return self.context.do_something()+"bar"
</code></pre>
<p>You then would register that adapter with the component registry and you could then use it like this:</p>
<pre><code>>>> obj = MyClass()
>>> print obj.do_something()
"foo"
>>> adapter = ISomethingElse(obj)
>>> print adapter.do_something_else()
"foobar"
</code></pre>
<p>What that gives you is the ability to extend the original class with functionality which the class does not provide directly. You can do that without changing that class (it might be in a different product/library) and you could simply exchange that adapter by a different implementation without changing the code which uses it. It's all done by registration of components in initialization time.</p>
<p>This of course is mainly useful for frameworks/libraries.</p>
<p>I think it takes some time to get used to it but I really don't want to live without it anymore. But as said before it's also true that you need to think exactly where it makes sense and where it doesn't. Of course interfaces on it's own can also already be useful as documentation of the API. It's also useful for unit tests where you can test if your class actually implements that interface. And last but not least I like starting by writing the interface and some doctests to get the idea of what I am actually about to code.</p>
<p>For more information you can check out my <a href="http://mrtopf.de/blog/an-introduction-to-the-zope-component-architecture/" rel="nofollow">little introduction to it</a> and there is a <a href="http://www.muthukadan.net/docs/zca.html" rel="nofollow">quite extensive description of it's API</a>. </p>
| 1
|
2009-02-16T23:48:49Z
|
[
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay?
| 552,058
|
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p>
<p>Just so we're clear, an interface in Python would look something like this:</p>
<pre><code>class ISomething(object):
def some_method():
pass
def some_other_method(some_argument):
pass
</code></pre>
<p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p>
<p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
| 16
|
2009-02-16T02:15:17Z
| 555,960
|
<p>Glyph Lefkowitz (of Twisted fame) just recently <a href="http://glyph.twistedmatrix.com/2009/02/explaining-why-interfaces-are-great.html" rel="nofollow">wrote an article on this topic</a>. Personally I do not feel the need for interfaces, but YMMV.</p>
| 1
|
2009-02-17T08:39:45Z
|
[
"python",
"documentation",
"interface",
"coding-style"
] |
"Interfaces" in Python: Yea or Nay?
| 552,058
|
<p>So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea.</p>
<p>Just so we're clear, an interface in Python would look something like this:</p>
<pre><code>class ISomething(object):
def some_method():
pass
def some_other_method(some_argument):
pass
</code></pre>
<p>Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. </p>
<p>So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?</p>
| 16
|
2009-02-16T02:15:17Z
| 1,209,169
|
<p>Have you looked at <a href="http://peak.telecommunity.com/PyProtocols.html" rel="nofollow">PyProtocols?</a> it has a nice interface implementation that you should look at.</p>
| 1
|
2009-07-30T20:32:01Z
|
[
"python",
"documentation",
"interface",
"coding-style"
] |
What's the best way to make a time from "Today" or "Yesterday" and a time in Python?
| 552,073
|
<p>Python has pretty good date parsing but is the only way to recognize a datetime such as "Today 3:20 PM" or "Yesterday 11:06 AM" by creating a new date today and doing subtractions?</p>
| 9
|
2009-02-16T02:30:50Z
| 552,173
|
<p>I am not yet completely up to speed on Python yet, but your question interested me, so I dug around a bit.</p>
<p>Date subtraction using <a href="http://docs.python.org/library/datetime.html#timedelta-objects" rel="nofollow"><strong><code>timedelta</code></strong></a> is by far the most common solution I found.</p>
<p>Since your question asks if that's the <strong>only</strong> way to do it, I checked out the strftime format codes to see if you could define your own. Unfortunately not. From Python's <a href="http://docs.python.org/library/datetime.html#id1" rel="nofollow">strftime documentation</a>:</p>
<blockquote>
<p>... The full set of format codes supported varies across platforms, because Python calls the platform C libraryâs strftime() function, and platform variations are common.</p>
<p>The following is a list of all the format codes that the C standard (1989 version) requires ...</p>
</blockquote>
<p>Anyhow, this isn't a definitive answer, but maybe It'll save others time barking up the wrong tree.</p>
| -2
|
2009-02-16T03:36:16Z
|
[
"python",
"datetime",
"parsing"
] |
What's the best way to make a time from "Today" or "Yesterday" and a time in Python?
| 552,073
|
<p>Python has pretty good date parsing but is the only way to recognize a datetime such as "Today 3:20 PM" or "Yesterday 11:06 AM" by creating a new date today and doing subtractions?</p>
| 9
|
2009-02-16T02:30:50Z
| 552,229
|
<p>A library that I like a lot, and I'm seeing more and more people use, is <a href="http://labix.org/python-dateutil">python-dateutil</a> but unfortunately neither it nor the other traditional big datetime parser, <a href="http://www.egenix.com/products/python/mxBase/mxDateTime/">mxDateTime from Egenix</a> can parse the word "tomorrow" in spite of both libraries having very strong "fuzzy" parsers.</p>
<p>The only library I've seen that can do this is <a href="http://pypi.python.org/pypi/magicdate/0.1.3">magicdate</a>. Examples:</p>
<pre><code>>>> import magicdate
>>> magicdate.magicdate('today')
datetime.date(2009, 2, 15)
>>> magicdate.magicdate('tomorrow')
datetime.date(2009, 2, 16)
>>> magicdate.magicdate('yesterday')
datetime.date(2009, 2, 14)
</code></pre>
<p>Unfortunately this only returns datetime.date objects, and so won't include time parts and can't handle your example of "Today 3:20 PM".</p>
<p>So, you need mxDateTime for that. Examples:</p>
<pre><code>>>> import mx.DateTime
>>> mx.DateTime.Parser.DateTimeFromString("Today 3:20 PM")
<mx.DateTime.DateTime object for '2009-02-15 15:20:00.00' at 28faa28>
>>> mx.DateTime.Parser.DateTimeFromString("Tomorrow 5:50 PM")
<mx.DateTime.DateTime object for '2009-02-15 17:50:00.00' at 2a86088>
</code></pre>
<p>EDIT: mxDateTime.Parser is only parsing the time in these examples and ignoring the words "today" and "tomorrow". So for this particular case you need to use a combo of magicdate to get the date and mxDateTime to get the time. My recommendation is to just use python-dateutils or mxDateTime and only accept the string formats they can parse.</p>
<hr>
<p>EDIT 2: As noted in the comments it looks python-dateutil can now handle fuzzy parsing. I've also since discovered the <a href="http://code.google.com/p/parsedatetime/">parsedatetime</a> module that was developed for use in Chandler and it works with the queries in this question:</p>
<pre><code>>>> import parsedatetime.parsedatetime as pdt
>>> import parsedatetime.parsedatetime_consts as pdc
>>> c=pdc.Constants()
>>> p=pdt.Calendar(c)
>>> p.parse('Today 3:20 PM')
((2010, 3, 12, 15, 20, 0, 4, 71, -1), 3)
>>> p.parse('Yesterday 11:06 AM')
((2010, 3, 11, 11, 6, 0, 3, 70, -1), 3)
</code></pre>
<p>and for reference here is the current time:</p>
<pre><code>>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2010, 3, 12, 15, 23, 35, 951652)
</code></pre>
| 18
|
2009-02-16T04:03:58Z
|
[
"python",
"datetime",
"parsing"
] |
Missing first line when downloading .rar file using urllib2.urlopen()
| 552,328
|
<p>Okey this is really strange. I have this script which basically downloads bunch of achieve files and extracts them. Usually those files are .zip files. Today I sat down and decided to make it work with rar files and I got stuck. At first I thought that the problem is in my unrar code, but it wasn't there. So I did:</p>
<pre><code>f = urllib2.urlopen(file_location)
data = StringIO(f.read())
print data.getvalue()
</code></pre>
<p>heck I even did:</p>
<pre><code>f = urllib2.urlopen(file_location)
print f.read()
</code></pre>
<p>because I just wanted to see the first chunk and the result is the same - I'm missing first line of the .rar file.</p>
<p>If I use web browser to download the very same file everything is fine, it's not corrupt.</p>
<p>Can anyone please explain me what the hell is going on here? And what does it have to do with file type.</p>
| 0
|
2009-02-16T05:26:27Z
| 552,346
|
<p>Does the data maybe contain a "carriage return" character ("\r") so that the first chunk is overwritten with subsequent data when you try to display it? This would explain why you don't see the first chunk in your output, but not why you aren't able to decode it later on.</p>
| 2
|
2009-02-16T05:36:53Z
|
[
"python",
"urllib2"
] |
Missing first line when downloading .rar file using urllib2.urlopen()
| 552,328
|
<p>Okey this is really strange. I have this script which basically downloads bunch of achieve files and extracts them. Usually those files are .zip files. Today I sat down and decided to make it work with rar files and I got stuck. At first I thought that the problem is in my unrar code, but it wasn't there. So I did:</p>
<pre><code>f = urllib2.urlopen(file_location)
data = StringIO(f.read())
print data.getvalue()
</code></pre>
<p>heck I even did:</p>
<pre><code>f = urllib2.urlopen(file_location)
print f.read()
</code></pre>
<p>because I just wanted to see the first chunk and the result is the same - I'm missing first line of the .rar file.</p>
<p>If I use web browser to download the very same file everything is fine, it's not corrupt.</p>
<p>Can anyone please explain me what the hell is going on here? And what does it have to do with file type.</p>
| 0
|
2009-02-16T05:26:27Z
| 552,390
|
<p>When trying to determine the content of binary data string, use <a href="http://docs.python.org/library/functions.html#repr" rel="nofollow"><code>repr()</code></a> or <a href="http://docs.python.org/library/functions.html#hex" rel="nofollow"><code>hex()</code></a>. For example,</p>
<pre><code>>>> print repr(data)
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t'
>>> print [hex(ord(c)) for c in data]
['0x0', '0x1', '0x2', '0x3', '0x4', '0x5', '0x6', '0x7', '0x8', '0x9']
>>>
</code></pre>
| 3
|
2009-02-16T06:10:34Z
|
[
"python",
"urllib2"
] |
How do python classes work?
| 552,329
|
<p>I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author.</p>
<p>My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The author's code below is under the assumption that 'DefaultDomainName' will exist when an instance of the class is created (e.g. __init__() is called), but this does not seem to be the case, at least in my testing in python 2.5 on OS X. </p>
<p>In the class Manager __init__() method, my print statements show as 'None'. And the print statements in the global function set_domain() further down shows 'None' prior to setting Manager.DefaultDomainName, and shows the expected value of 'test_domain' after the assignment. But when creating an instance of Manager again after calling set_domain(), the __init__() method still shows 'None'.</p>
<p>Can anyone help me out, and explain what is going on here. It would be greatly appreciated. Thank you.</p>
<pre>
<code>
# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import boto
from boto.utils import find_class
class Manager(object):
DefaultDomainName = boto.config.get('Persist', 'default_domain', None)
def __init__(self, domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
self.domain_name = domain_name
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
self.domain = None
self.sdb = None
self.s3 = None
if not self.domain_name:
print "1: %s" % self.DefaultDomainName
print "2: %s" % Manager.DefaultDomainName
self.domain_name = self.DefaultDomainName
#self.domain_name = 'test_domain'
if self.domain_name:
boto.log.info('No SimpleDB domain set, using default_domain: %s' % self.domain_name)
else:
boto.log.warning('No SimpleDB domain set, persistance is disabled')
if self.domain_name:
self.sdb = boto.connect_sdb(aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
debug=debug)
self.domain = self.sdb.lookup(self.domain_name)
if not self.domain:
self.domain = self.sdb.create_domain(self.domain_name)
def get_s3_connection(self):
if not self.s3:
self.s3 = boto.connect_s3(self.aws_access_key_id, self.aws_secret_access_key)
return self.s3
def get_manager(domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
return Manager(domain_name, aws_access_key_id, aws_secret_access_key, debug=debug)
def set_domain(domain_name):
print "3: %s" % Manager.DefaultDomainName
Manager.DefaultDomainName = domain_name
print "4: %s" % Manager.DefaultDomainName
def get_domain():
return Manager.DefaultDomainName
def revive_object_from_id(id, manager):
if not manager.domain:
return None
attrs = manager.domain.get_attributes(id, ['__module__', '__type__', '__lineage__'])
try:
cls = find_class(attrs['__module__'], attrs['__type__'])
return cls(id, manager=manager)
except ImportError:
return None
def object_lister(cls, query_lister, manager):
for item in query_lister:
if cls:
yield cls(item.name)
else:
o = revive_object_from_id(item.name, manager)
if o:
yield o
</code>
</pre>
| 4
|
2009-02-16T05:26:35Z
| 552,363
|
<p><strong>A few python notes</strong></p>
<p>When python executes the <strong>class</strong> block, it creates all of the "attributes" of that class as it encounters them. They are usually class variables as well as functions (methods), and the like.</p>
<p>So the value for "Manager.DefaultDomainName" is set when it is encountered in the class definition. This code is <strong>only ever run once</strong> - never again. The reason for that is that it is just "defining" the class object called "Manager".</p>
<p>When an object of class "Manager" is instantiated, it is an instance of the "Manager" class. (that may sound repetitive). To be perfectly clear, the value:</p>
<pre><code>self.DefaultDomainName
</code></pre>
<p>does not exist. Following the rules of classes, python says "hmm, that does not exist on this object instance, I'll look at the class object(s)". So python actually finds the value at:</p>
<pre><code>Manager.DefaultDomainName
# also referenced by
self.__class__.DefaultDomainName
</code></pre>
<p>All of that to exemplify the point that the class attribute "Manager.DefaultDomainName" is only created once, can only exist once, and can only hold one value at once.</p>
<p><hr /></p>
<p>In the example above, run the builtin function id() on each of the values:</p>
<pre><code>print "1: %s" % id(self.DefaultDomainName)
print "2: %s" % id(Manager.DefaultDomainName)
</code></pre>
<p>You should see that they are referring to exactly the same memory location.</p>
<p><hr /></p>
<p><strong>Now, in (non)answer to the original question...</strong> I don't know from perusing the code above. I would suggest that you try a couple of techniques to find it out:</p>
<pre><code># Debug with pdb. Follow every step of the process to ensure that you are
# setting valeus as you thought, and that the code you thought would be
# called is actually being called. I've had many problems like this where
# the error was in procedure, not in the actual code at hand.
import pdb; pdb.set_trace()
# check to see if id(Manager) is the same as id(self.__class__)
# in the set_domain() function:
# check to see what attributes you can see on Manager,
# and if they match the attributes on Manager and self.__class__ in __init__
</code></pre>
<p>Please update here when you figure it out.</p>
| 9
|
2009-02-16T05:49:13Z
|
[
"python"
] |
How do python classes work?
| 552,329
|
<p>I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author.</p>
<p>My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The author's code below is under the assumption that 'DefaultDomainName' will exist when an instance of the class is created (e.g. __init__() is called), but this does not seem to be the case, at least in my testing in python 2.5 on OS X. </p>
<p>In the class Manager __init__() method, my print statements show as 'None'. And the print statements in the global function set_domain() further down shows 'None' prior to setting Manager.DefaultDomainName, and shows the expected value of 'test_domain' after the assignment. But when creating an instance of Manager again after calling set_domain(), the __init__() method still shows 'None'.</p>
<p>Can anyone help me out, and explain what is going on here. It would be greatly appreciated. Thank you.</p>
<pre>
<code>
# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import boto
from boto.utils import find_class
class Manager(object):
DefaultDomainName = boto.config.get('Persist', 'default_domain', None)
def __init__(self, domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
self.domain_name = domain_name
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
self.domain = None
self.sdb = None
self.s3 = None
if not self.domain_name:
print "1: %s" % self.DefaultDomainName
print "2: %s" % Manager.DefaultDomainName
self.domain_name = self.DefaultDomainName
#self.domain_name = 'test_domain'
if self.domain_name:
boto.log.info('No SimpleDB domain set, using default_domain: %s' % self.domain_name)
else:
boto.log.warning('No SimpleDB domain set, persistance is disabled')
if self.domain_name:
self.sdb = boto.connect_sdb(aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
debug=debug)
self.domain = self.sdb.lookup(self.domain_name)
if not self.domain:
self.domain = self.sdb.create_domain(self.domain_name)
def get_s3_connection(self):
if not self.s3:
self.s3 = boto.connect_s3(self.aws_access_key_id, self.aws_secret_access_key)
return self.s3
def get_manager(domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
return Manager(domain_name, aws_access_key_id, aws_secret_access_key, debug=debug)
def set_domain(domain_name):
print "3: %s" % Manager.DefaultDomainName
Manager.DefaultDomainName = domain_name
print "4: %s" % Manager.DefaultDomainName
def get_domain():
return Manager.DefaultDomainName
def revive_object_from_id(id, manager):
if not manager.domain:
return None
attrs = manager.domain.get_attributes(id, ['__module__', '__type__', '__lineage__'])
try:
cls = find_class(attrs['__module__'], attrs['__type__'])
return cls(id, manager=manager)
except ImportError:
return None
def object_lister(cls, query_lister, manager):
for item in query_lister:
if cls:
yield cls(item.name)
else:
o = revive_object_from_id(item.name, manager)
if o:
yield o
</code>
</pre>
| 4
|
2009-02-16T05:26:35Z
| 552,391
|
<p>What gahooa said. Besides that, I assume that <code>boto.config.get(...)</code> returns <code>None</code>, presumably because the <code>default_domain</code> key is not defined in the <code>Persist</code> section of your config file.</p>
<p><code>boto.config</code> is defined in <code>boto/__init__.py</code> as <code>config = boto.pyami.config.Config()</code> (essentially). <code>boto.pyami.config.Config</code> is a subclass of the standard <a href="http://docs.python.org/library/configparser.html" rel="nofollow"><code>ConfigParser.SafeConfigParser</code></a>, and it looks for config files in the locations specified by <code>boto.pyami.BotoConfigLocations</code>, which defaults to a list containing <code>/etc/boto.cfg</code> and <code>$HOME/.boto</code>. If you don't have a config in either of those locations, you won't have a default domain name.</p>
| 1
|
2009-02-16T06:12:28Z
|
[
"python"
] |
How do python classes work?
| 552,329
|
<p>I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author.</p>
<p>My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The author's code below is under the assumption that 'DefaultDomainName' will exist when an instance of the class is created (e.g. __init__() is called), but this does not seem to be the case, at least in my testing in python 2.5 on OS X. </p>
<p>In the class Manager __init__() method, my print statements show as 'None'. And the print statements in the global function set_domain() further down shows 'None' prior to setting Manager.DefaultDomainName, and shows the expected value of 'test_domain' after the assignment. But when creating an instance of Manager again after calling set_domain(), the __init__() method still shows 'None'.</p>
<p>Can anyone help me out, and explain what is going on here. It would be greatly appreciated. Thank you.</p>
<pre>
<code>
# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import boto
from boto.utils import find_class
class Manager(object):
DefaultDomainName = boto.config.get('Persist', 'default_domain', None)
def __init__(self, domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
self.domain_name = domain_name
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
self.domain = None
self.sdb = None
self.s3 = None
if not self.domain_name:
print "1: %s" % self.DefaultDomainName
print "2: %s" % Manager.DefaultDomainName
self.domain_name = self.DefaultDomainName
#self.domain_name = 'test_domain'
if self.domain_name:
boto.log.info('No SimpleDB domain set, using default_domain: %s' % self.domain_name)
else:
boto.log.warning('No SimpleDB domain set, persistance is disabled')
if self.domain_name:
self.sdb = boto.connect_sdb(aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
debug=debug)
self.domain = self.sdb.lookup(self.domain_name)
if not self.domain:
self.domain = self.sdb.create_domain(self.domain_name)
def get_s3_connection(self):
if not self.s3:
self.s3 = boto.connect_s3(self.aws_access_key_id, self.aws_secret_access_key)
return self.s3
def get_manager(domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
return Manager(domain_name, aws_access_key_id, aws_secret_access_key, debug=debug)
def set_domain(domain_name):
print "3: %s" % Manager.DefaultDomainName
Manager.DefaultDomainName = domain_name
print "4: %s" % Manager.DefaultDomainName
def get_domain():
return Manager.DefaultDomainName
def revive_object_from_id(id, manager):
if not manager.domain:
return None
attrs = manager.domain.get_attributes(id, ['__module__', '__type__', '__lineage__'])
try:
cls = find_class(attrs['__module__'], attrs['__type__'])
return cls(id, manager=manager)
except ImportError:
return None
def object_lister(cls, query_lister, manager):
for item in query_lister:
if cls:
yield cls(item.name)
else:
o = revive_object_from_id(item.name, manager)
if o:
yield o
</code>
</pre>
| 4
|
2009-02-16T05:26:35Z
| 552,432
|
<p>when you load the module, python executes each of the code line by line. Since code is executed, class variables should all be set at load time. Most likely your boto.config.get function was just returned None. In another word, yes, all class variables are allocated before instance variables.</p>
| 0
|
2009-02-16T06:49:19Z
|
[
"python"
] |
How do python classes work?
| 552,329
|
<p>I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author.</p>
<p>My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The author's code below is under the assumption that 'DefaultDomainName' will exist when an instance of the class is created (e.g. __init__() is called), but this does not seem to be the case, at least in my testing in python 2.5 on OS X. </p>
<p>In the class Manager __init__() method, my print statements show as 'None'. And the print statements in the global function set_domain() further down shows 'None' prior to setting Manager.DefaultDomainName, and shows the expected value of 'test_domain' after the assignment. But when creating an instance of Manager again after calling set_domain(), the __init__() method still shows 'None'.</p>
<p>Can anyone help me out, and explain what is going on here. It would be greatly appreciated. Thank you.</p>
<pre>
<code>
# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import boto
from boto.utils import find_class
class Manager(object):
DefaultDomainName = boto.config.get('Persist', 'default_domain', None)
def __init__(self, domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
self.domain_name = domain_name
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
self.domain = None
self.sdb = None
self.s3 = None
if not self.domain_name:
print "1: %s" % self.DefaultDomainName
print "2: %s" % Manager.DefaultDomainName
self.domain_name = self.DefaultDomainName
#self.domain_name = 'test_domain'
if self.domain_name:
boto.log.info('No SimpleDB domain set, using default_domain: %s' % self.domain_name)
else:
boto.log.warning('No SimpleDB domain set, persistance is disabled')
if self.domain_name:
self.sdb = boto.connect_sdb(aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
debug=debug)
self.domain = self.sdb.lookup(self.domain_name)
if not self.domain:
self.domain = self.sdb.create_domain(self.domain_name)
def get_s3_connection(self):
if not self.s3:
self.s3 = boto.connect_s3(self.aws_access_key_id, self.aws_secret_access_key)
return self.s3
def get_manager(domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0):
return Manager(domain_name, aws_access_key_id, aws_secret_access_key, debug=debug)
def set_domain(domain_name):
print "3: %s" % Manager.DefaultDomainName
Manager.DefaultDomainName = domain_name
print "4: %s" % Manager.DefaultDomainName
def get_domain():
return Manager.DefaultDomainName
def revive_object_from_id(id, manager):
if not manager.domain:
return None
attrs = manager.domain.get_attributes(id, ['__module__', '__type__', '__lineage__'])
try:
cls = find_class(attrs['__module__'], attrs['__type__'])
return cls(id, manager=manager)
except ImportError:
return None
def object_lister(cls, query_lister, manager):
for item in query_lister:
if cls:
yield cls(item.name)
else:
o = revive_object_from_id(item.name, manager)
if o:
yield o
</code>
</pre>
| 4
|
2009-02-16T05:26:35Z
| 552,482
|
<p>Thank you all for your help. I figured out what I was missing:</p>
<p>The class definitions of the boto classes I am using contain class variables for Manager, which in turn serve as a default value if no Manager is passed to the <code>__init__()</code> of these classes. I didn't even think about the fact that these class variables would be evaluated with the import statement when importing the modules containing these classes.</p>
<p>So, these class variable Managers' self.domain_name values were set from DefaultDomainName before I even called <code>set_domain()</code>, and since I do not have the config files setup as ruds pointed out, that value was None.</p>
<p>So, I have to rework my code a little, but thank you all for helping out a python newcomer.</p>
| 1
|
2009-02-16T07:23:28Z
|
[
"python"
] |
Use Python 2.6 subprocess module in Python 2.5
| 552,423
|
<p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? Some sort of <code>from __future__ import subprocess_module</code>?</p>
| 9
|
2009-02-16T06:41:55Z
| 552,507
|
<p>Well Python is open source, you are free to take that pthread function from 2.6 and move it into your own code or use it as a reference to implement your own.</p>
<p>For reasons that should be obvious there's no way to have a hybrid of Python that can import portions of newer versions.</p>
| 0
|
2009-02-16T07:38:05Z
|
[
"python",
"subprocess",
"python-2.5"
] |
Use Python 2.6 subprocess module in Python 2.5
| 552,423
|
<p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? Some sort of <code>from __future__ import subprocess_module</code>?</p>
| 9
|
2009-02-16T06:41:55Z
| 552,510
|
<p>There isn't really a great way to do it. subprocess is <a href="http://svn.python.org/view/python/trunk/Lib/subprocess.py?rev=69620&view=markup" rel="nofollow">implemented in python</a> (as opposed to C) so you could conceivably copy the module somewhere and use it (hoping of course that it doesn't use any 2.6 goodness).</p>
<p>On the other hand you could simply implement what subprocess claims to do and write a function that sends SIGTERM on *nix and calls TerminateProcess on Windows. The following implementation has been tested on linux and in a Win XP vm, you'll need the <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">python Windows extensions</a>:</p>
<pre><code>import sys
def terminate(process):
"""
Kills a process, useful on 2.5 where subprocess.Popens don't have a
terminate method.
Used here because we're stuck on 2.5 and don't have Popen.terminate
goodness.
"""
def terminate_win(process):
import win32process
return win32process.TerminateProcess(process._handle, -1)
def terminate_nix(process):
import os
import signal
return os.kill(process.pid, signal.SIGTERM)
terminate_default = terminate_nix
handlers = {
"win32": terminate_win,
"linux2": terminate_nix
}
return handlers.get(sys.platform, terminate_default)(process)
</code></pre>
<p>That way you only have to maintain the <code>terminate</code> code rather than the entire module.</p>
| 6
|
2009-02-16T07:39:07Z
|
[
"python",
"subprocess",
"python-2.5"
] |
Use Python 2.6 subprocess module in Python 2.5
| 552,423
|
<p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? Some sort of <code>from __future__ import subprocess_module</code>?</p>
| 9
|
2009-02-16T06:41:55Z
| 552,543
|
<p>While this doesn't directly answer your question, it may be worth knowing.</p>
<p>Imports from <code>__future__</code> actually only change compiler options, so while it can turn with into a statement or make string literals produce unicodes instead of strs, it can't change the capabilities and features of modules in the Python standard library.</p>
| 2
|
2009-02-16T07:57:50Z
|
[
"python",
"subprocess",
"python-2.5"
] |
Use Python 2.6 subprocess module in Python 2.5
| 552,423
|
<p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? Some sort of <code>from __future__ import subprocess_module</code>?</p>
| 9
|
2009-02-16T06:41:55Z
| 554,881
|
<p>I know this question has already been answered, but for what it's worth, I've used the <code>subprocess.py</code> that ships with Python 2.6 in Python 2.3 and it's worked fine. If you read the comments at the top of the file it says:</p>
<blockquote>
<p><code># This module should remain compatible with Python 2.2, see PEP 291.</code></p>
</blockquote>
| 9
|
2009-02-16T22:43:43Z
|
[
"python",
"subprocess",
"python-2.5"
] |
Use Python 2.6 subprocess module in Python 2.5
| 552,423
|
<p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? Some sort of <code>from __future__ import subprocess_module</code>?</p>
| 9
|
2009-02-16T06:41:55Z
| 668,825
|
<p>Here are some ways to end processes on Windows, taken directly from
<a href="http://code.activestate.com/recipes/347462/" rel="nofollow">http://code.activestate.com/recipes/347462/</a></p>
<pre><code># Create a process that won't end on its own
import subprocess
process = subprocess.Popen(['python.exe', '-c', 'while 1: pass'])
# Kill the process using pywin32
import win32api
win32api.TerminateProcess(int(process._handle), -1)
# Kill the process using ctypes
import ctypes
ctypes.windll.kernel32.TerminateProcess(int(process._handle), -1)
# Kill the proces using pywin32 and pid
import win32api
PROCESS_TERMINATE = 1
handle = win32api.OpenProcess(PROCESS_TERMINATE, False, process.pid)
win32api.TerminateProcess(handle, -1)
win32api.CloseHandle(handle)
# Kill the proces using ctypes and pid
import ctypes
PROCESS_TERMINATE = 1
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, process.pid)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
ctypes.windll.kernel32.CloseHandle(handle)
</code></pre>
| 1
|
2009-03-21T05:57:12Z
|
[
"python",
"subprocess",
"python-2.5"
] |
Use Python 2.6 subprocess module in Python 2.5
| 552,423
|
<p>I would like to use Python 2.6's version of subprocess, because it allows the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate">Popen.terminate()</a> function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? Some sort of <code>from __future__ import subprocess_module</code>?</p>
| 9
|
2009-02-16T06:41:55Z
| 1,449,566
|
<p>I followed Kamil Kisiel suggestion regarding using python 2.6 subprocess.py in python 2.5 and it worked perfectly. To make it easier, I created a distutils package that you can easy_install and/or include in buildout.</p>
<p>To use subprocess from python 2.6 in python 2.5 project:</p>
<pre><code>easy_install taras.python26
</code></pre>
<p>in your code</p>
<pre><code>from taras.python26 import subprocess
</code></pre>
<p>in buildout</p>
<pre><code>[buildout]
parts = subprocess26
[subprocess26]
recipe = zc.recipe.egg
eggs = taras.python26
</code></pre>
| 2
|
2009-09-19T21:21:16Z
|
[
"python",
"subprocess",
"python-2.5"
] |
Django Model returning NoneType
| 552,521
|
<p>I have a model Product</p>
<p>it has two fields size & colours among others</p>
<pre><code>colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
</code></pre>
<p>In my view I have </p>
<pre><code>current_product = Product.objects.get(slug=title)
if len(current_product.size) != 0 :
current_product.size = current_product.size.split(",")
</code></pre>
<p>and get this error:</p>
<p>object of type 'NoneType' has no len()</p>
<p>What is NoneType and how can I test for it?</p>
| 2
|
2009-02-16T07:44:23Z
| 552,530
|
<p><code>NoneType</code> is the type that the <code>None</code> value has. You want to change the second snippet to</p>
<pre><code>if current_product.size: # This will evaluate as false if size is None or len(size) == 0.
blah blah
</code></pre>
| 7
|
2009-02-16T07:50:32Z
|
[
"python",
"django",
"django-views"
] |
Django Model returning NoneType
| 552,521
|
<p>I have a model Product</p>
<p>it has two fields size & colours among others</p>
<pre><code>colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
</code></pre>
<p>In my view I have </p>
<pre><code>current_product = Product.objects.get(slug=title)
if len(current_product.size) != 0 :
current_product.size = current_product.size.split(",")
</code></pre>
<p>and get this error:</p>
<p>object of type 'NoneType' has no len()</p>
<p>What is NoneType and how can I test for it?</p>
| 2
|
2009-02-16T07:44:23Z
| 552,532
|
<p>NoneType is Pythons NULL-Type, meaning "nothing", "undefined". It has only one value: "None". When creating a new model object, its attributes are usually initialized to None, you can check that by comparing:</p>
<pre><code>if someobject.someattr is None:
# Not set yet
</code></pre>
| 1
|
2009-02-16T07:51:15Z
|
[
"python",
"django",
"django-views"
] |
Django Model returning NoneType
| 552,521
|
<p>I have a model Product</p>
<p>it has two fields size & colours among others</p>
<pre><code>colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
</code></pre>
<p>In my view I have </p>
<pre><code>current_product = Product.objects.get(slug=title)
if len(current_product.size) != 0 :
current_product.size = current_product.size.split(",")
</code></pre>
<p>and get this error:</p>
<p>object of type 'NoneType' has no len()</p>
<p>What is NoneType and how can I test for it?</p>
| 2
|
2009-02-16T07:44:23Z
| 552,538
|
<p>I don't know Django, but I assume that some kind of ORM is involved when you do this:</p>
<pre><code>current_product = Product.objects.get(slug=title)
</code></pre>
<p>At that point you should always check whether you get None back ('None' is the same as 'null' in Java or 'nil' in Lisp with the subtle difference that 'None' is an object in Python). This is usually the way ORMs map the empty set to the programming language.</p>
<p><b>EDIT:</b>
Gee, I just see that it's <code>current_product.size</code> that's <code>None</code> not <code>current_product</code>. As said, I'm not familiar with Django's ORM, but this seems strange nevertheless: I'd either expect <code>current_product</code> to be <code>None</code> or <code>size</code> having a numerical value.</p>
| -1
|
2009-02-16T07:54:08Z
|
[
"python",
"django",
"django-views"
] |
Django Model returning NoneType
| 552,521
|
<p>I have a model Product</p>
<p>it has two fields size & colours among others</p>
<pre><code>colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
</code></pre>
<p>In my view I have </p>
<pre><code>current_product = Product.objects.get(slug=title)
if len(current_product.size) != 0 :
current_product.size = current_product.size.split(",")
</code></pre>
<p>and get this error:</p>
<p>object of type 'NoneType' has no len()</p>
<p>What is NoneType and how can I test for it?</p>
| 2
|
2009-02-16T07:44:23Z
| 1,900,255
|
<p>I can best explain the NoneType error with this example of erroneous code: </p>
<pre><code>def test():
s = list([1,'',2,3,4,'',5])
try:
s = s.remove('') # <-- THIS WRONG because it turns s in to a NoneType
except:
pass
print(str(s))
</code></pre>
<p><code>s.remove()</code> returns nothing also known as NoneType. The correct way </p>
<pre><code>def test2()
s = list([1,'',2,3,4,'',5])
try:
s.remove('') # <-- CORRECTED
except:
pass
print(str(s))
</code></pre>
| 0
|
2009-12-14T11:05:55Z
|
[
"python",
"django",
"django-views"
] |
python ide vs cmd line detection?
| 552,627
|
<p>When programming in the two IDEs i used, bad things happen when i use raw_input. However on the command line it works EXACTLY how i expect it to. Typically this app is ran in cmd line but i like to edit and debug it in an IDE. Is there a way to detect if i executed the app in an IDE or not?</p>
| 0
|
2009-02-16T08:35:37Z
| 552,634
|
<pre><code>if sys.stdin.isatty():
# command line (not a pipe, no stdin redirection)
else:
# something else, could be IDE
</code></pre>
| 4
|
2009-02-16T08:39:45Z
|
[
"python"
] |
python ide vs cmd line detection?
| 552,627
|
<p>When programming in the two IDEs i used, bad things happen when i use raw_input. However on the command line it works EXACTLY how i expect it to. Typically this app is ran in cmd line but i like to edit and debug it in an IDE. Is there a way to detect if i executed the app in an IDE or not?</p>
| 0
|
2009-02-16T08:35:37Z
| 553,304
|
<p>I would strongly advise (and you have been previously advised on this) to use a good IDE, and a good debugger instead of hacking around your code to fix something that shouldn't be broken in the first place.</p>
<p>I deserve to be down-voted for not answering the question, but please consider this advice for your future sanity.</p>
<p>I would personally recommend <a href="http://winpdb.org/" rel="nofollow">Winpdb debugger</a> and <a href="http://pida.co.uk" rel="nofollow">PIDA IDE</a></p>
| 0
|
2009-02-16T13:30:24Z
|
[
"python"
] |
How do I profile memory usage in Python?
| 552,744
|
<p>I've recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways.</p>
<p>I'm already familiar with the standard Python module for profiling runtime (for most things I've found the timeit magic function in IPython to be sufficient), but I'm also interested in memory usage so I can explore those tradeoffs as well (e.g. the cost of caching a table of previously computed values versus recomputing them as needed). Is there a module that will profile the memory usage of a given function for me?</p>
| 87
|
2009-02-16T09:34:43Z
| 552,810
|
<p>This one has been answered already here: <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a></p>
<p>Basically you do something like that (cited from <a href="http://guppy-pe.sourceforge.net/#Heapy">Guppy-PE</a>):</p>
<pre><code>>>> from guppy import hpy; h=hpy()
>>> h.heap()
Partition of a set of 48477 objects. Total size = 3265516 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 25773 53 1612820 49 1612820 49 str
1 11699 24 483960 15 2096780 64 tuple
2 174 0 241584 7 2338364 72 dict of module
3 3478 7 222592 7 2560956 78 types.CodeType
4 3296 7 184576 6 2745532 84 function
5 401 1 175112 5 2920644 89 dict of class
6 108 0 81888 3 3002532 92 dict (no owner)
7 114 0 79632 2 3082164 94 dict of type
8 117 0 51336 2 3133500 96 type
9 667 1 24012 1 3157512 97 __builtin__.wrapper_descriptor
<76 more rows. Type e.g. '_.more' to view.>
>>> h.iso(1,[],{})
Partition of a set of 3 objects. Total size = 176 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1 33 136 77 136 77 dict (no owner)
1 1 33 28 16 164 93 list
2 1 33 12 7 176 100 int
>>> x=[]
>>> h.iso(x).sp
0: h.Root.i0_modules['__main__'].__dict__['x']
>>>
</code></pre>
| 66
|
2009-02-16T10:00:24Z
|
[
"python",
"memory",
"profiling"
] |
How do I profile memory usage in Python?
| 552,744
|
<p>I've recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways.</p>
<p>I'm already familiar with the standard Python module for profiling runtime (for most things I've found the timeit magic function in IPython to be sufficient), but I'm also interested in memory usage so I can explore those tradeoffs as well (e.g. the cost of caching a table of previously computed values versus recomputing them as needed). Is there a module that will profile the memory usage of a given function for me?</p>
| 87
|
2009-02-16T09:34:43Z
| 15,448,600
|
<p>For a really simple approach try:</p>
<pre><code>import resource
def using(point=""):
usage=resource.getrusage(resource.RUSAGE_SELF)
return '''%s: usertime=%s systime=%s mem=%s mb
'''%(point,usage[0],usage[1],
(usage[2]*resource.getpagesize())/1000000.0 )
</code></pre>
<p>Just insert <code>using("Label")</code> where you want to see what's going on.</p>
| 11
|
2013-03-16T11:19:27Z
|
[
"python",
"memory",
"profiling"
] |
How do I profile memory usage in Python?
| 552,744
|
<p>I've recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways.</p>
<p>I'm already familiar with the standard Python module for profiling runtime (for most things I've found the timeit magic function in IPython to be sufficient), but I'm also interested in memory usage so I can explore those tradeoffs as well (e.g. the cost of caching a table of previously computed values versus recomputing them as needed). Is there a module that will profile the memory usage of a given function for me?</p>
| 87
|
2009-02-16T09:34:43Z
| 33,631,986
|
<p>I you only want to look at the memory usage of an object, (<a href="http://stackoverflow.com/a/33631772/1587329">answer to other question</a>)</p>
<blockquote>
<p>There is a module called <a href="https://pypi.python.org/pypi/Pympler" rel="nofollow">Pympler</a> which contains the <code>asizeof</code>
module.</p>
<p>Use as follows:</p>
<pre><code>from pympler import asizeof
asizeof.asizeof(my_object)
</code></pre>
<p>Unlike <code>sys.getsizeof</code>, it <strong>works for your self-created objects</strong>.</p>
<pre><code>>>> asizeof.asizeof(tuple('bcd'))
200
>>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'})
400
>>> asizeof.asizeof({})
280
>>> asizeof.asizeof({'foo':'bar'})
360
>>> asizeof.asizeof('foo')
40
>>> asizeof.asizeof(Bar())
352
>>> asizeof.asizeof(Bar().__dict__)
280
</code></pre>
</blockquote>
| 4
|
2015-11-10T14:13:21Z
|
[
"python",
"memory",
"profiling"
] |
python exit a blocking thread?
| 552,996
|
<p>in my code i loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until i enter a key to return from the blocking function raw_input(). Can i do to force raw_input() to return? by maybe sending it fake input? could i terminate the thread its on? (the only data it has is a single var call wantQuit).</p>
| 2
|
2009-02-16T11:22:48Z
| 553,290
|
<p>You might use a non-blocking function to read user input.<br />
This solution is windows-specific:</p>
<pre><code>import msvcrt
import time
while True:
# test if there are keypresses in the input buffer
while msvcrt.kbhit():
# read a character
print msvcrt.getch()
# no keypresses, sleep for a while...
time.sleep(1)
</code></pre>
<p>To do something similar in Unix, which reads a line at a time, unlike the windows version reading char by char (thanks to Aaron Digulla for providing the link to the python user forum):</p>
<pre><code>import sys
import select
i = 0
while i < 10:
i = i + 1
r,w,x = select.select([sys.stdin.fileno()],[],[],2)
if len(r) != 0:
print sys.stdin.readline()
</code></pre>
<p>See also: <a href="http://code.activestate.com/recipes/134892/" rel="nofollow">http://code.activestate.com/recipes/134892/</a></p>
| 2
|
2009-02-16T13:24:52Z
|
[
"python",
"multithreading",
"raw-input"
] |
python exit a blocking thread?
| 552,996
|
<p>in my code i loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until i enter a key to return from the blocking function raw_input(). Can i do to force raw_input() to return? by maybe sending it fake input? could i terminate the thread its on? (the only data it has is a single var call wantQuit).</p>
| 2
|
2009-02-16T11:22:48Z
| 553,333
|
<p>You can use this time out function that wraps your function. Here's the recipe from: <a href="http://code.activestate.com/recipes/473878/" rel="nofollow">http://code.activestate.com/recipes/473878/</a></p>
<pre><code>def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
'''This function will spwan a thread and run the given function using the args, kwargs and
return the given default value if the timeout_duration is exceeded
'''
import threading
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = default
def run(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return it.result
else:
return it.result
</code></pre>
| 3
|
2009-02-16T13:40:38Z
|
[
"python",
"multithreading",
"raw-input"
] |
python exit a blocking thread?
| 552,996
|
<p>in my code i loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until i enter a key to return from the blocking function raw_input(). Can i do to force raw_input() to return? by maybe sending it fake input? could i terminate the thread its on? (the only data it has is a single var call wantQuit).</p>
| 2
|
2009-02-16T11:22:48Z
| 553,438
|
<p>There is a <a href="http://bytes.com/topic/python/answers/36171-need-function-like-raw_input-but-time-limit" rel="nofollow">post on the Python mailing list</a> which explains how to do this for Unix:</p>
<pre><code># this works on some platforms:
import signal, sys
def alarm_handler(*args):
raise Exception("timeout")
def function_xyz(prompt, timeout):
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(timeout)
sys.stdout.write(prompt)
sys.stdout.flush()
try:
text = sys.stdin.readline()
except:
text = ""
signal.alarm(0)
return text
</code></pre>
| 1
|
2009-02-16T14:18:26Z
|
[
"python",
"multithreading",
"raw-input"
] |
python exit a blocking thread?
| 552,996
|
<p>in my code i loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until i enter a key to return from the blocking function raw_input(). Can i do to force raw_input() to return? by maybe sending it fake input? could i terminate the thread its on? (the only data it has is a single var call wantQuit).</p>
| 2
|
2009-02-16T11:22:48Z
| 553,509
|
<p>Why don't you just mark the thread as daemonic?</p>
<p>From the <a href="http://docs.python.org/library/threading.html#id1" rel="nofollow">docs</a>:</p>
<blockquote>
<p>A thread can be flagged as a âdaemon threadâ. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon attribute.</p>
</blockquote>
| 6
|
2009-02-16T14:47:54Z
|
[
"python",
"multithreading",
"raw-input"
] |
python excel making reports
| 553,019
|
<p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need to put some array values in them in a table (formatting doesn't matter), and draw a number of charts from those tables. Is there a way to do this automatically ?
Some library ?</p>
<p>Anyone done something like this in the past ?</p>
| 5
|
2009-02-16T11:30:16Z
| 553,059
|
<p>I believe you have two options:</p>
<ol>
<li>Control Excel from Python (using pywin32, see <a href="http://stackoverflow.com/questions/441758/driving-excel-from-python-in-windows/445961">this question</a>). Requires Windows and Excel.</li>
<li>Use the <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a> pure Python library.</li>
</ol>
<p>I have not tried xlwt, I do not know if it handles charts.</p>
| 2
|
2009-02-16T11:45:42Z
|
[
"python",
"excel"
] |
python excel making reports
| 553,019
|
<p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need to put some array values in them in a table (formatting doesn't matter), and draw a number of charts from those tables. Is there a way to do this automatically ?
Some library ?</p>
<p>Anyone done something like this in the past ?</p>
| 5
|
2009-02-16T11:30:16Z
| 553,069
|
<p>You're simplest approach is to use Python's <a href="http://www.python.org/doc/2.5.2/lib/module-csv.html" rel="nofollow">csv</a> library to create a simple CSV file. Excel imports these effortlessly.</p>
<p>Then you do Excel stuff to make charts out of the pages created from CSV sheets.</p>
<p>There are some recipes for controlling Excel from within Python. See <a href="http://code.activestate.com/recipes/528870/" rel="nofollow">http://code.activestate.com/recipes/528870/</a> for an example. The example has references to other projects.</p>
<p>Also, you can use <a href="http://sourceforge.net/projects/pyexcelerator" rel="nofollow">pyExcelerator</a> or <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a> to create a more complete Excel workbook.</p>
| 3
|
2009-02-16T11:49:52Z
|
[
"python",
"excel"
] |
python excel making reports
| 553,019
|
<p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need to put some array values in them in a table (formatting doesn't matter), and draw a number of charts from those tables. Is there a way to do this automatically ?
Some library ?</p>
<p>Anyone done something like this in the past ?</p>
| 5
|
2009-02-16T11:30:16Z
| 553,091
|
<p><a href="http://sourceforge.net/projects/pyexcelerator" rel="nofollow">PyExcelerator</a> has some quirks that you need to work around (atleast it did when I last used it), but it will do the job quite well.</p>
<p>I haven't tried <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a>, but as it's a fork of PyExcelerator, one might suspect that it has all the same features, and hopefully less quirks.</p>
| 1
|
2009-02-16T11:59:45Z
|
[
"python",
"excel"
] |
python excel making reports
| 553,019
|
<p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need to put some array values in them in a table (formatting doesn't matter), and draw a number of charts from those tables. Is there a way to do this automatically ?
Some library ?</p>
<p>Anyone done something like this in the past ?</p>
| 5
|
2009-02-16T11:30:16Z
| 554,480
|
<p>@S.Lott covered most of the bases. You might also consider generating an HTML <code><table></code>. Here's a sample I found with a quick search: <a href="http://www.developer.com/lang/other/print.php/10942_3727616_2" rel="nofollow">Creating Excel Files with Python and Django</a></p>
| 1
|
2009-02-16T20:41:25Z
|
[
"python",
"excel"
] |
python excel making reports
| 553,019
|
<p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need to put some array values in them in a table (formatting doesn't matter), and draw a number of charts from those tables. Is there a way to do this automatically ?
Some library ?</p>
<p>Anyone done something like this in the past ?</p>
| 5
|
2009-02-16T11:30:16Z
| 555,079
|
<p>There is a package on PyPi call <a href="http://pypi.python.org/pypi/xlutils/" rel="nofollow">xlutils</a> which might help and there is <a href="http://www.simplistix.co.uk/presentations/python_excel_08/python_excel_08.pdf" rel="nofollow">this presentation from Chris Withers</a> (lightning talk from last EuroPython I think) where you can see some example code with xlrd and xlwt. Looks easy ;-)</p>
<p>Hope that helps.</p>
| 1
|
2009-02-16T23:53:40Z
|
[
"python",
"excel"
] |
python excel making reports
| 553,019
|
<p>I've been given the task of connecting my code (fortran) with py (2.5), and generate a number of excel reports if possible. The first part went fine - and is done with, but now I'm working on the second. </p>
<p>What are my choices for making excel (2007 if possible) sheets from python ? In general, I would need to put some array values in them in a table (formatting doesn't matter), and draw a number of charts from those tables. Is there a way to do this automatically ?
Some library ?</p>
<p>Anyone done something like this in the past ?</p>
| 5
|
2009-02-16T11:30:16Z
| 30,660,573
|
<p>XslxWriter is a very good and very feature-complete python package for producing Excel worksheets.</p>
<p><a href="https://github.com/jmcnamara/XlsxWriter" rel="nofollow">https://github.com/jmcnamara/XlsxWriter</a> (docs: <a href="https://xlsxwriter.readthedocs.org/index.html" rel="nofollow">https://xlsxwriter.readthedocs.org/index.html</a>).</p>
| 1
|
2015-06-05T07:16:48Z
|
[
"python",
"excel"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 553,320
|
<p>Convert both strings to timestamps (in your chosen resolution, e.g. milliseconds, seconds, hours, days, whatever), subtract the earlier from the later, multiply your random number (assuming it is distributed in the range [0, 1]) with that difference, and add again to the earlier one. Convert the timestamp back to date string and you have a random time in that range.</p>
<p>Python example (output is almost in the format you specified, other than 0 padding - blame the American time format conventions):</p>
<pre><code>import random
import time
def strTimeProp(start, end, format, prop):
"""Get a time at a proportion of a range of two formatted times.
start and end should be strings specifying times formated in the
given format (strftime-style), giving an interval [start, end].
prop specifies how a proportion of the interval to be taken after
start. The returned time will be in the specified format.
"""
stime = time.mktime(time.strptime(start, format))
etime = time.mktime(time.strptime(end, format))
ptime = stime + prop * (etime - stime)
return time.strftime(format, time.localtime(ptime))
def randomDate(start, end, prop):
return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop)
print randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", random.random())
</code></pre>
| 70
|
2009-02-16T13:35:08Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 553,321
|
<ol>
<li>Convert your input dates to numbers
(int, float, whatever is best for
your usage)</li>
<li>Choose a number between your two date numbers.</li>
<li>Convert this number back to a date.</li>
</ol>
<p>Many algorithms for converting date to and from numbers are already available in many operating systems.</p>
| 1
|
2009-02-16T13:35:26Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 553,323
|
<p>What do you need the random number for? Usually (depending on the language) you can get the number of seconds/milliseconds from the Epoch from a date. So for a randomd date between startDate and endDate you could do:</p>
<ol>
<li>compute the time in ms between
startDate and endDate
(endDate.toMilliseconds() -
startDate.toMilliseconds())</li>
<li>generate a number between 0 and the number you obtained in 1</li>
<li>generate a new Date with time offset = startDate.toMilliseconds() + number obtained in 2</li>
</ol>
| 0
|
2009-02-16T13:36:11Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 553,325
|
<p>Conceptually it's quite simple. Depending on which language you're using you will be able to convert those dates into some reference 32 or 64 bit integer, typically representing seconds since epoch (1 January 1970) otherwise known as "Unix time" or milliseconds since some other arbitrary date. Simply generate a random 32 or 64 bit integer between those two values. This should be a one liner in any language.</p>
<p>On some platforms you can generate a time as a double (date is the integer part, time is the fractional part is one implementation). The same principle applies except you're dealing with single or double precision floating point numbers ("floats" or "doubles" in C, Java and other languages). Subtract the difference, multiply by random number (0 <= r <= 1), add to start time and done.</p>
| 0
|
2009-02-16T13:37:45Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 553,337
|
<p>The easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.</p>
<p>A quick PHP example would be:</p>
<pre><code>// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
// Convert to timetamps
$min = strtotime($start_date);
$max = strtotime($end_date);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}
</code></pre>
<p>This function makes use of <code><a href="http://ie.php.net/strtotime" rel="nofollow" rel="nofollow">strtotime()</a></code> to convert a datetime description into a Unix timestamp, and <code><a href="http://ie.php.net/date" rel="nofollow" rel="nofollow">date()</a></code> to make a valid date out of the random timestamp which has been generated.</p>
| 3
|
2009-02-16T13:42:23Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 553,448
|
<pre><code>from random import randrange
from datetime import timedelta
def random_date(start, end):
"""
This function will return a random datetime between two datetime
objects.
"""
delta = end - start
int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
random_second = randrange(int_delta)
return start + timedelta(seconds=random_second)
</code></pre>
<p>The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last lines calculation.</p>
<p>example run:</p>
<pre><code>d1 = datetime.strptime('1/1/2008 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2009 4:50 AM', '%m/%d/%Y %I:%M %p')
print random_date(d1, d2)
</code></pre>
<p>output:</p>
<pre><code>2008-12-04 01:50:17
</code></pre>
| 67
|
2009-02-16T14:21:56Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 4,155,740
|
<p>In python:</p>
<pre><code>>>> from dateutil.rrule import rrule, DAILY
>>> import datetime, random
>>> random.choice(
list(
rrule(DAILY,
dtstart=datetime.date(2009,8,21),
until=datetime.date(2010,10,12))
)
)
datetime.datetime(2010, 2, 1, 0, 0)
</code></pre>
<p>(need python <code>dateutil</code> library â <code>pip install python-dateutil</code>)</p>
| 0
|
2010-11-11T15:00:59Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 6,127,309
|
<p>Here is an answer to the literal meaning of the title rather than the body of this question:</p>
<pre><code>import time
import datetime
import random
def date_to_timestamp(d) :
return int(time.mktime(d.timetuple()))
def randomDate(start, end):
"""Get a random date between two dates"""
stime = date_to_timestamp(start)
etime = date_to_timestamp(end)
ptime = stime + random.random() * (etime - stime)
return datetime.date.fromtimestamp(ptime)
</code></pre>
<p>This code is based loosely on the accepted answer.</p>
| 2
|
2011-05-25T15:53:16Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 8,170,651
|
<p>A tiny version.</p>
<pre><code>from datetime import timedelta
from random import randint
def random_date(start, end):
return start + timedelta(
seconds=randint(0, int((end - start).total_seconds())))
</code></pre>
<p>Note that both <code>start</code> and <code>end</code> arguments should be <code>datetime</code> objects. If you've got strings instead, it's fairly easy to convert. The other answers point to some ways to do so.</p>
| 43
|
2011-11-17T16:25:52Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 17,127,561
|
<p>Use ApacheCommonUtils to generate a random long within a given range,
and then create Date out of that long. </p>
<p>Example:</p>
<p>import org.apache.commons.math.random.RandomData;</p>
<p>import org.apache.commons.math.random.RandomDataImpl;</p>
<p>public Date nextDate(Date min, Date max) {</p>
<pre><code>RandomData randomData = new RandomDataImpl();
return new Date(randomData.nextLong(min.getTime(), max.getTime()));
</code></pre>
<p>}</p>
| 0
|
2013-06-15T20:22:30Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 17,193,251
|
<p>It's very simple using radar</p>
<h2>Installation</h2>
<p>$ pip install radar</p>
<h2>Usage</h2>
<pre class="lang-python prettyprint-override"><code>import datetime
import radar
# Generate random datetime (parsing dates from str values)
radar.random_datetime(start='2000-05-24', stop='2013-05-24T23:59:59')
# Generate random datetime from datetime.datetime values
radar.random_datetime(
start = datetime.datetime(year=2000, month=5, day=24),
stop = datetime.datetime(year=2013, month=5, day=24)
)
# Just render some random datetime. If no range is given, start defaults to
# 1970-01-01 and stop defaults to datetime.datetime.now()
radar.random_datetime()
</code></pre>
| 12
|
2013-06-19T13:59:56Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 22,222,900
|
<p>To chip in a pandas-based solution I use:</p>
<pre><code>import pandas as pd
import numpy as np
def random_date(start, end, position=None):
start, end = pd.Timestamp(start), pd.Timestamp(end)
delta = (end - start).total_seconds()
if position is None:
offset = np.random.uniform(0., delta)
else:
offset = position * delta
offset = pd.offsets.Second(offset)
t = start + offset
return t
</code></pre>
<p>I like it, because of the nice <code>pd.Timestamp</code> features that allow me to throw different stuff and formats at it. Consider the following few examples...</p>
<p>Your signature.</p>
<pre><code>>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM", position=0.34)
Timestamp('2008-05-04 21:06:48', tz=None)
</code></pre>
<p>Random position.</p>
<pre><code>>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM")
Timestamp('2008-10-21 05:30:10', tz=None)
</code></pre>
<p>Different format.</p>
<pre><code>>>> random_date('2008-01-01 13:30', '2009-01-01 4:50')
Timestamp('2008-11-18 17:20:19', tz=None)
</code></pre>
<p>Passing pandas/datetime objects directly.</p>
<pre><code>>>> random_date(pd.datetime.now(), pd.datetime.now() + pd.offsets.Hour(3))
Timestamp('2014-03-06 14:51:16.035965', tz=None)
</code></pre>
| 2
|
2014-03-06T11:18:51Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 26,819,041
|
<p>Since Python 3 <code>timedelta</code> supports multiplication with floats, so now you can do:</p>
<pre><code>import random
random_date = start + (end - start) * random.random()
</code></pre>
<p>given that <code>start</code> and <code>end</code> are of the type <code>datetime.datetime</code>. For example, to generate a random datetime within the next day:</p>
<pre><code>import random
from datetime import datetime, timedelta
start = datetime.now()
end = start + timedelta(days=1)
random_date = start + (end - start) * random.random()
</code></pre>
| 2
|
2014-11-08T15:56:45Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 26,883,710
|
<p>You can Use <code>Mixer</code>,</p>
<pre><code>pip install mixer
</code></pre>
<p>and,</p>
<pre><code>from mixer import generators as gen
print gen.get_datetime(min_datetime=(1900, 1, 1, 0, 0, 0), max_datetime=(2020, 12, 31, 23, 59, 59))
</code></pre>
| 2
|
2014-11-12T09:42:53Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 35,709,408
|
<p>This is a different approach - that sort of works..</p>
<pre><code>from random import randint
import datetime
date=datetime.date(randint(2005,2025), randint(1,12),randint(1,28))
</code></pre>
<p><strong>WAIITT - BETTER APPROACH</strong></p>
<pre><code>startdate=datetime.date(YYYY,MM,DD)
date=startdate+datetime.timedelta(randint(1,365))
</code></pre>
| 3
|
2016-02-29T20:52:42Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 36,231,794
|
<p>I made this for another project using random and time. I used a general format from time you can view the documentation <a href="https://docs.python.org/2/library/time.html#time.struct_time" rel="nofollow">here</a> for the first argument in strftime(). The second part is a random.randrange function. It returns an integer between the arguments. Change it to the ranges that match the strings you would like. You must have nice arguments in the tuple of the second arugment.</p>
<pre><code>import time
import random
def get_random_date():
return strftime("%Y-%m-%d %H:%M:%S",(random.randrange(2000,2016),random.randrange(1,12),
random.randrange(1,28),random.randrange(1,24),random.randrange(1,60),random.randrange(1,60),random.randrange(1,7),random.randrange(0,366),1))
</code></pre>
| 0
|
2016-03-26T04:58:26Z
|
[
"python",
"datetime",
"random"
] |
Generate a random date between two other dates
| 553,303
|
<p>How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-</p>
<pre><code>randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
to be after this to be before this
</code></pre>
<p>and would return a date such as-
"2/4/2008 7:20 PM"</p>
| 53
|
2009-02-16T13:30:04Z
| 38,039,865
|
<p>Just to add another one:</p>
<pre><code>datestring = datetime.datetime.strftime(datetime.datetime( \
random.randint(2000, 2015), \
random.randint(1, 12), \
random.randint(1, 28), \
random.randrange(23), \
random.randrange(59), \
random.randrange(59), \
random.randrange(1000000)), '%Y-%m-%d %H:%M:%S')
</code></pre>
<p>The day handling needs some considerations. With 28 you are on the secure site.</p>
| 0
|
2016-06-26T15:08:01Z
|
[
"python",
"datetime",
"random"
] |
Windows Server 2008 or Vista?
| 553,372
|
<p>What is an easy (to implement) way to check whether I am on Windows Vista or Windows Server 2008 from a Python script?</p>
<p><code>platform.uname()</code> gives the same result for both versions.</p>
| 1
|
2009-02-16T13:58:23Z
| 553,427
|
<p>As mentioned in the other question the foolproof (I think) way is to use win32api.GetVersionEx(1). The combination of the version number and the product type will give you the current windows platform you're running on. Eg. the combination of version number "6.*" and product type VER_NT_SERVER is Windows Server 2008.</p>
<p>You can find information about the different combinations you can get at <a href="http://msdn.microsoft.com/en-us/library/ms724833(VS.85).aspx" rel="nofollow" title="msdn">msdn</a></p>
| 2
|
2009-02-16T14:13:51Z
|
[
"python",
"windows-vista",
"windows-server-2008",
"windowsversion"
] |
Can you use a string to instantiate a class in python?
| 553,784
|
<p>I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs. So, I'm trying to see if instead of doing something like this:</p>
<pre><code>ProcessDirector = ProcessDirector()
ID12345 = ID12345()
ID01234 = ID01234()
ProcessDirector.construct(ID12345)
ProcessDirector.construct(ID01234)
ID12345.run()
ID01234.run()
</code></pre>
<p>Can I do something like this (I know this doesn't work):</p>
<pre><code>IDS = ["ID12345", "ID01234"]
ProcessDirector = ProcessDirector()
for id in IDS:
builder = id() #some how instantiate class from string
ProcessDirector.construct(builder)
builder.run()
</code></pre>
<p>That way, when I need to add a new one in the future, all I have to do is add the id to the IDS list, rather than peppering the new ID throughout the code. </p>
<h2>EDIT</h2>
<p>Looks like there are some different opinions based on where the data is coming from. These IDs are entered in a file that no one else has access to. I'm not reading the strings from the command line, and I'd like to be able to do as little alteration when adding a new ID in the future. </p>
| 27
|
2009-02-16T16:00:26Z
| 554,034
|
<p>There's some stuff missing from your question, so I'm forced to guess at the omitted stuff. Feel free to edit your question to correct the omissions.</p>
<pre><code>class ProcessDirector( object ):
# does something
class ID12345( SomeKindOfProcess ):
pass
class ID001234( SomeKindOfProcess ):
pass
idList= [ID12345, ID01234]
theProcessDirector = ProcessDirector()
for id in idList:
builder = id() #Instantiate an object from the class object
theProcessDirector.construct(builder)
builder.run()
</code></pre>
<p>This works very nicely. It doesn't instantiate from a string -- in practice you don't often want this. Sometimes, but rarely. More commonly, you a list of class objects from which you want instance objects.</p>
<p>If you actually are getting your class names from the command line, then you'd make the following small change.</p>
<pre><code>validClasses = [ ID12345, ID01234 ]
validMap = dict( ( (c.__name__, c) for c in validClasses ) )
nameStrings = [ "ID12345", "ID01234" ] # from your command-line
idList= [ validMap[s] for s in nameStrings ]
</code></pre>
<p>Everything else remains the same.</p>
<p>[Also, if possible, try to start instance variable names with lowercase letters. Names which start with Uppercase Letters are usually class names.]</p>
<p><strong>Edit</strong></p>
<p>Removed <code>eval</code>. In spite of the fact that <code>eval()</code> is absolutely <strong>not</strong> a security hole. Eval (and <code>exec</code> and <code>execfile</code>) are only a problem if someone specifically grants access to malicious users.</p>
| -1
|
2009-02-16T18:08:37Z
|
[
"python",
"design-patterns",
"reflection"
] |
Can you use a string to instantiate a class in python?
| 553,784
|
<p>I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs. So, I'm trying to see if instead of doing something like this:</p>
<pre><code>ProcessDirector = ProcessDirector()
ID12345 = ID12345()
ID01234 = ID01234()
ProcessDirector.construct(ID12345)
ProcessDirector.construct(ID01234)
ID12345.run()
ID01234.run()
</code></pre>
<p>Can I do something like this (I know this doesn't work):</p>
<pre><code>IDS = ["ID12345", "ID01234"]
ProcessDirector = ProcessDirector()
for id in IDS:
builder = id() #some how instantiate class from string
ProcessDirector.construct(builder)
builder.run()
</code></pre>
<p>That way, when I need to add a new one in the future, all I have to do is add the id to the IDS list, rather than peppering the new ID throughout the code. </p>
<h2>EDIT</h2>
<p>Looks like there are some different opinions based on where the data is coming from. These IDs are entered in a file that no one else has access to. I'm not reading the strings from the command line, and I'd like to be able to do as little alteration when adding a new ID in the future. </p>
| 27
|
2009-02-16T16:00:26Z
| 554,073
|
<p><strong>Never</strong> use <code>eval()</code> if you can help it. Python has <strong>so</strong> many better options (dispatch dictionary, <code>getattr()</code>, etc.) that you should never have to use the security hole known as <code>eval()</code>.</p>
| 12
|
2009-02-16T18:17:22Z
|
[
"python",
"design-patterns",
"reflection"
] |
Can you use a string to instantiate a class in python?
| 553,784
|
<p>I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs. So, I'm trying to see if instead of doing something like this:</p>
<pre><code>ProcessDirector = ProcessDirector()
ID12345 = ID12345()
ID01234 = ID01234()
ProcessDirector.construct(ID12345)
ProcessDirector.construct(ID01234)
ID12345.run()
ID01234.run()
</code></pre>
<p>Can I do something like this (I know this doesn't work):</p>
<pre><code>IDS = ["ID12345", "ID01234"]
ProcessDirector = ProcessDirector()
for id in IDS:
builder = id() #some how instantiate class from string
ProcessDirector.construct(builder)
builder.run()
</code></pre>
<p>That way, when I need to add a new one in the future, all I have to do is add the id to the IDS list, rather than peppering the new ID throughout the code. </p>
<h2>EDIT</h2>
<p>Looks like there are some different opinions based on where the data is coming from. These IDs are entered in a file that no one else has access to. I'm not reading the strings from the command line, and I'd like to be able to do as little alteration when adding a new ID in the future. </p>
| 27
|
2009-02-16T16:00:26Z
| 554,162
|
<p>Simplest way is to just create a dict.</p>
<pre><code>class A(object):
pass
class B(object):
pass
namedclass = {'ID12345': A, 'ID2': A, 'B': B, 'AnotherB': B, 'ID01234': B}
</code></pre>
<p>Then use it (your code example):</p>
<pre><code>IDS = ["ID12345", "ID01234"]
ProcessDirector = ProcessDirector()
for id in IDS:
builder = namedclass[id]()
ProcessDirector.construct(builder)
builder.run()
</code></pre>
| 4
|
2009-02-16T18:46:28Z
|
[
"python",
"design-patterns",
"reflection"
] |
Can you use a string to instantiate a class in python?
| 553,784
|
<p>I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs. So, I'm trying to see if instead of doing something like this:</p>
<pre><code>ProcessDirector = ProcessDirector()
ID12345 = ID12345()
ID01234 = ID01234()
ProcessDirector.construct(ID12345)
ProcessDirector.construct(ID01234)
ID12345.run()
ID01234.run()
</code></pre>
<p>Can I do something like this (I know this doesn't work):</p>
<pre><code>IDS = ["ID12345", "ID01234"]
ProcessDirector = ProcessDirector()
for id in IDS:
builder = id() #some how instantiate class from string
ProcessDirector.construct(builder)
builder.run()
</code></pre>
<p>That way, when I need to add a new one in the future, all I have to do is add the id to the IDS list, rather than peppering the new ID throughout the code. </p>
<h2>EDIT</h2>
<p>Looks like there are some different opinions based on where the data is coming from. These IDs are entered in a file that no one else has access to. I'm not reading the strings from the command line, and I'd like to be able to do as little alteration when adding a new ID in the future. </p>
| 27
|
2009-02-16T16:00:26Z
| 554,462
|
<p>If you wanted to avoid an eval(), you could just do:</p>
<pre><code>id = "1234asdf"
constructor = globals()[id]
instance = constructor()
</code></pre>
<p>Provided that the class is defined in (or imported into) your current scope.</p>
| 39
|
2009-02-16T20:34:50Z
|
[
"python",
"design-patterns",
"reflection"
] |
Can you use a string to instantiate a class in python?
| 553,784
|
<p>I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs. So, I'm trying to see if instead of doing something like this:</p>
<pre><code>ProcessDirector = ProcessDirector()
ID12345 = ID12345()
ID01234 = ID01234()
ProcessDirector.construct(ID12345)
ProcessDirector.construct(ID01234)
ID12345.run()
ID01234.run()
</code></pre>
<p>Can I do something like this (I know this doesn't work):</p>
<pre><code>IDS = ["ID12345", "ID01234"]
ProcessDirector = ProcessDirector()
for id in IDS:
builder = id() #some how instantiate class from string
ProcessDirector.construct(builder)
builder.run()
</code></pre>
<p>That way, when I need to add a new one in the future, all I have to do is add the id to the IDS list, rather than peppering the new ID throughout the code. </p>
<h2>EDIT</h2>
<p>Looks like there are some different opinions based on where the data is coming from. These IDs are entered in a file that no one else has access to. I'm not reading the strings from the command line, and I'd like to be able to do as little alteration when adding a new ID in the future. </p>
| 27
|
2009-02-16T16:00:26Z
| 554,812
|
<p>Not totally sure this is what you want, but it seems like a more Python'y way to instantiate a bunch of classes listed in a string:</p>
<pre><code>class idClasses:
class ID12345:pass
class ID01234:pass
# could also be: import idClasses
class ProcessDirector:
def __init__(self):
self.allClasses = []
def construct(self, builderName):
targetClass = getattr(idClasses, builderName)
instance = targetClass()
self.allClasses.append(instance)
IDS = ["ID12345", "ID01234"]
director = ProcessDirector()
for id in IDS:
director.construct(id)
print director.allClasses
# [<__main__.ID12345 instance at 0x7d850>, <__main__.ID01234 instance at 0x7d918>]
</code></pre>
| 13
|
2009-02-16T22:18:24Z
|
[
"python",
"design-patterns",
"reflection"
] |
Can anyone provide a more pythonic way of generating the morris sequence?
| 553,871
|
<p>I'm trying to generate the <a href="http://www.ocf.berkeley.edu/~stoll/answer.html" rel="nofollow">morris sequence</a> in python. My current solution is below, but I feel like I just wrote c in python. Can anyone provide a more pythonic solution?</p>
<pre><code>def morris(x):
a = ['1', '11']
yield a[0]
yield a[1]
while len(a) <= x:
s = ''
count = 1
al = a[-1]
for i in range(0,len(al)):
if i+1 < len(al) and al[i] == al[i+1]:
count += 1
else:
s += '%s%s' % (count, al[i])
count = 1
a.append(s)
yield s
a = [i for i in morris(30)]
</code></pre>
| 5
|
2009-02-16T16:24:53Z
| 554,002
|
<pre><code>from itertools import groupby, islice
def morris():
morris = '1'
yield morris
while True:
morris = groupby(morris)
morris = ((len(list(group)), key) for key, group in morris)
morris = ((str(l), k) for l, k in morris)
morris = ''.join(''.join(t) for t in morris)
yield morris
print list(islice(morris(), 10))
</code></pre>
<p>First of all I'd make the iterator infinite and let the consumer decide, how much of it he wants. That way he could either get every morris number that is shorter than x or the first x numbers, etc.</p>
<p>Then there is obviously no need to store the whole list of previous morris numbers in a list, since the recursion is only <code>n := f(n-1)</code> anyway.</p>
<p>Lastly, using itertools to give it a functional touch is always worth a geek point or two ;) I split the generator expression into several lines to make it a bit easier on the eye.</p>
<p>The main ugliness in this solution comes from the fact that <code>len()</code> can't be called on an iterator and gives us an int where we need a str. The other hickup is the nested str.join) to flatten the whole thing into a str again.</p>
<p>If you want to start the sequence from arbitrary numbers, define the function like this:</p>
<pre><code>def morris(morris=None):
if morris is None:
morris = '1'
[...]
</code></pre>
<p>If you want to turn around that generator, you can write it like this:</p>
<pre><code>def morris():
morris = '1'
yield morris
while True:
print morris
morris = ''.join(''.join(t)
for t in ((str(len(list(group))), key)
for key, group in groupby(morris)))
yield morris
</code></pre>
<p>I'm not sure i like the splitting into two functions, but this seems to be the most readable solution:</p>
<pre><code>def m_groupby(s):
for key, group in groupby(s):
yield str(len(list(group)))
yield key
def morris():
morris = '1'
yield morris
while True:
morris = ''.join(m_groupby(morris))
yield morris
</code></pre>
<p>Hope you like it!</p>
| 6
|
2009-02-16T18:01:25Z
|
[
"python",
"sequences",
"itertools"
] |
Can anyone provide a more pythonic way of generating the morris sequence?
| 553,871
|
<p>I'm trying to generate the <a href="http://www.ocf.berkeley.edu/~stoll/answer.html" rel="nofollow">morris sequence</a> in python. My current solution is below, but I feel like I just wrote c in python. Can anyone provide a more pythonic solution?</p>
<pre><code>def morris(x):
a = ['1', '11']
yield a[0]
yield a[1]
while len(a) <= x:
s = ''
count = 1
al = a[-1]
for i in range(0,len(al)):
if i+1 < len(al) and al[i] == al[i+1]:
count += 1
else:
s += '%s%s' % (count, al[i])
count = 1
a.append(s)
yield s
a = [i for i in morris(30)]
</code></pre>
| 5
|
2009-02-16T16:24:53Z
| 554,028
|
<p><a href="http://docs.python.org/library/itertools.html#itertools.groupby"><code>itertools.groupby</code></a> seems to fit perfectly! Just define a <code>next_morris</code> function as follows:</p>
<pre><code>def next_morris(number):
return ''.join('%s%s' % (len(list(group)), digit)
for digit, group in itertools.groupby(str(number)))
</code></pre>
<p>That's all!!! Look:</p>
<pre><code>print next_morris(1)
11
print next_morris(111221)
312211
</code></pre>
<p><hr /></p>
<p>I could use that to make a generator:</p>
<pre><code>def morris_generator(maxlen, start=1):
num = str(start)
while len(num) < maxlen:
yield int(num)
num = next_morris(num)
</code></pre>
<p>Usage:</p>
<pre><code>for n in morris_generator(10):
print n
</code></pre>
<p>results:</p>
<pre><code>1
11
21
1211
111221
312211
13112221
</code></pre>
| 23
|
2009-02-16T18:07:12Z
|
[
"python",
"sequences",
"itertools"
] |
How do I prevent Python's urllib(2) from following a redirect
| 554,446
|
<p>I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from following the redirect?</p>
| 40
|
2009-02-16T20:29:30Z
| 554,475
|
<p><code>urllib2.urlopen</code> calls <code>build_opener()</code> which uses this list of handler classes:</p>
<pre><code>handlers = [ProxyHandler, UnknownHandler, HTTPHandler,
HTTPDefaultErrorHandler, HTTPRedirectHandler,
FTPHandler, FileHandler, HTTPErrorProcessor]
</code></pre>
<p>You could try calling <code>urllib2.build_opener(handlers)</code> yourself with a list that omits <code>HTTPRedirectHandler</code>, then call the <code>open()</code> method on the result to open your URL. If you really dislike redirects, you could even call <code>urllib2.install_opener(opener)</code> to your own non-redirecting opener.</p>
<p>It sounds like your real problem is that <code>urllib2</code> isn't doing cookies the way you'd like. See also <a href="http://stackoverflow.com/questions/189555/how-to-use-python-to-login-to-a-webpage-and-retrieve-cookies-for-later-usage">How to use Python to login to a webpage and retrieve cookies for later usage?</a></p>
| 11
|
2009-02-16T20:38:43Z
|
[
"python",
"urllib2"
] |
How do I prevent Python's urllib(2) from following a redirect
| 554,446
|
<p>I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from following the redirect?</p>
| 40
|
2009-02-16T20:29:30Z
| 554,501
|
<p>This question was asked before <a href="http://stackoverflow.com/questions/110498/is-there-an-easy-way-to-request-a-url-in-python-and-not-follow-redirects/110808">here</a>.</p>
<p><b>EDIT:</b> If you have to deal with quirky web applications you should probably try out <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a>. It's a great library that simulates a web browser. You can control redirecting, cookies, page refreshes... If the website doesn't rely [heavily] on JavaScript, you'll get along very nicely with mechanize.</p>
| 3
|
2009-02-16T20:46:59Z
|
[
"python",
"urllib2"
] |
How do I prevent Python's urllib(2) from following a redirect
| 554,446
|
<p>I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from following the redirect?</p>
| 40
|
2009-02-16T20:29:30Z
| 554,580
|
<p>You could do a couple of things:</p>
<ol>
<li>Build your own HTTPRedirectHandler that intercepts each redirect</li>
<li>Create an instance of HTTPCookieProcessor and install that opener so that you have access to the cookiejar.</li>
</ol>
<p>This is a quick little thing that shows both</p>
<pre><code>import urllib2
#redirect_handler = urllib2.HTTPRedirectHandler()
class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
print "Cookie Manip Right Here"
return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
http_error_301 = http_error_303 = http_error_307 = http_error_302
cookieprocessor = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(MyHTTPRedirectHandler, cookieprocessor)
urllib2.install_opener(opener)
response =urllib2.urlopen("WHEREEVER")
print response.read()
print cookieprocessor.cookiejar
</code></pre>
| 33
|
2009-02-16T21:13:43Z
|
[
"python",
"urllib2"
] |
How do I prevent Python's urllib(2) from following a redirect
| 554,446
|
<p>I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from following the redirect?</p>
| 40
|
2009-02-16T20:29:30Z
| 11,744,894
|
<p>If all you need is stopping redirection, then there is a simple way to do it. For example I only want to get cookies and for a better performance I don't want to be redirected to any other page. Also I hope the code is kept as 3xx. let's use 302 for instance.</p>
<pre><code>class MyHTTPErrorProcessor(urllib2.HTTPErrorProcessor):
def http_response(self, request, response):
code, msg, hdrs = response.code, response.msg, response.info()
# only add this line to stop 302 redirection.
if code == 302: return response
if not (200 <= code < 300):
response = self.parent.error(
'http', request, response, code, msg, hdrs)
return response
https_response = http_response
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), MyHTTPErrorProcessor)
</code></pre>
<p>In this way, you don't even need to go into urllib2.HTTPRedirectHandler.http_error_302()</p>
<p><strong>Yet more common case is that we simply want to stop redirection (as required):</strong></p>
<pre><code>class NoRedirection(urllib2.HTTPErrorProcessor):
def http_response(self, request, response):
return response
https_response = http_response
</code></pre>
<p>And normally use it this way:</p>
<pre><code>cj = cookielib.CookieJar()
opener = urllib2.build_opener(NoRedirection, urllib2.HTTPCookieProcessor(cj))
data = {}
response = opener.open('http://www.example.com', urllib.urlencode(data))
if response.code == 302:
redirection_target = response.headers['Location']
</code></pre>
| 27
|
2012-07-31T16:33:51Z
|
[
"python",
"urllib2"
] |
Stackless python network performance degrading over time?
| 554,805
|
<p>So i'm toying around with stackless python, writing a <em>very simple</em> webserver to teach myself programming with microthreads/tasklets. But now to my problem, when I run something like <code>ab -n 100000 -c 50 http://192.168.0.192/</code> (100k requests, 50 concurrency) in apache bench I get something like 6k req/s, the second time I run it I get 5.5k, third time 5k, fourth time, 4.5k, etc. all the way down to 100req/s or something.</p>
<p>The problem goes away when I restart the python script, though.</p>
<p>Now my question is why? Am i forgetting to delete tasklets? I've checked the stackless.getruncount() (and it always seems to return 1, for some reason) so it doesn't seem like there would be any dead tasklets hanging around? I've tried calling .kill() on all tasklets that are done, didn't help. I just can't figure this one out.</p>
<pre><code>import socket
import select
import stackless
import time
class socket_wrapper(object):
def __init__(self, sock, sockets):
super(socket_wrapper, self).__init__()
self.sock = sock
self.fileno = sock.fileno
self.sockets_list = sockets
self.channel = stackless.channel()
self.writable = False
self.error = False
def remove(self):
self.sock.close()
self.sockets_list.remove(self)
def send(self, data):
self.sock.send(data)
def push(self, bytes):
self.channel.send(self.sock.recv(bytes))
def stackless_accept(accept, handler, recv_size=1024, timeout=0):
sockets = [accept]
while True:
read, write, error = select.select(sockets, sockets, sockets, timeout)
for sock in read:
if sock is accept:
# Accept socket and create wrapper
sock = socket_wrapper(sock.accept()[0], sockets)
# Create tasklett for this connection
tasklet = stackless.tasklet(handler)
tasklet.setup(sock)
# Store socket
sockets.append(sock)
else:
# Send data to handler
sock.push(recv_size)
# Tag all writable sockets
for sock in write:
if sock is not accept:
sock.writable = True
# Tag all faulty sockets
for sock in error:
if sock is not accept:
sock.error = True
else:
pass # should do something here if the main socket is faulty
timeout = 0 if socket else 1
stackless.schedule()
def simple_handler(tsock):
data = ""
while data[-4:] != "\r\n\r\n":
data += tsock.channel.receive()
while not tsock.writable and not tsock.error:
stackless.schedule()
if not tsock.error:
tsock.send("HTTP/1.1 200 OK\r\nContent-length: 8\r\n\r\nHi there")
tsock.remove()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("192.168.0.192", 8000))
sock.listen(5)
stackless.tasklet(stackless_accept)(sock, simple_handler)
stackless.run()
</code></pre>
| 8
|
2009-02-16T22:16:06Z
| 554,914
|
<p>Two things.</p>
<p>First, please make Class Name start with an Upper Case Letter. It's more conventional and easier to read.</p>
<p>More importantly, in the <code>stackless_accept</code> function you accumulate a <code>list</code> of <code>Sock</code> objects, named <code>sockets</code>. This list appears to grow endlessly. Yes, you have a <code>remove</code>, but it isn't <em>always</em> invoked. If the socket gets an error, then it appears that it will be left in the collection forever.</p>
| 14
|
2009-02-16T22:52:41Z
|
[
"python",
"performance",
"networking",
"io",
"python-stackless"
] |
Parameterised regular expression in Python
| 554,957
|
<p>In Python, is there a better way to <strong>parameterise strings into regular expressions</strong> than doing it manually like this:</p>
<pre><code>test = 'flobalob'
names = ['a', 'b', 'c']
for name in names:
regexp = "%s" % (name)
print regexp, re.search(regexp, test)
</code></pre>
<p><em>This noddy example tries to match each name in turn. I know there's better ways of doing that, but its a simple example purely to illustrate the point.</em></p>
<p><hr /></p>
<p><strong>The answer appears to be no, there's no real alternative. The best way to paramaterise regular expressions in python is as above or with derivatives such as <code>str.format()</code>.</strong> I tried to write a generic question, rather than <em>'fix ma codez, kthxbye'</em>. For those still interested, I've fleshed out an example closer to my needs here:</p>
<pre><code>for diskfilename in os.listdir(''):
filenames = ['bob.txt', 'fred.txt', 'paul.txt']
for filename in filenames:
name, ext = filename.split('.')
regexp = "%s.*\.%s" % (name, ext)
m = re.search(regexp, diskfilename)
if m:
print diskfilename, regexp, re.search(regexp, diskfilename)
# ...
</code></pre>
<p>I'm trying to figure out the 'type' of a file based on its filename, of the form <code><filename>_<date>.<extension></code>. In my real code, the <code>filenames</code> array is a dict, containing a function to call once a match is found.</p>
<p>Other ways I've considered doing it:</p>
<ul>
<li><p><strong>Have a regular expression in the array.</strong> I already have an array of filenames without any regular expression magic, so I am loathe to do this. I have done this elsewhere in my code and its a mess (though necessary there).</p></li>
<li><p><strong>Match only on the start of the filename.</strong> This would work, but would break with .bak copies of files, etc. At some point I'll probably want to extract the date from the filename so would need to use a regular expression anyway.</p></li>
</ul>
<p><hr /></p>
<p>Thanks for the responses suggesting alternatives to regular expressions to achieve the same end result. I was more interested in parameterising regular expressions for now and for the future. I never come across <em>fnmatch</em>, so its all useful in the long run.</p>
| 3
|
2009-02-16T23:07:59Z
| 554,989
|
<p>Well, as you build a regexp from a string, I see no other way. But you could <em>parameterise the string itself</em> with a dictionary:</p>
<pre><code>d = {'bar': 'a', 'foo': 'b'}
regexp = '%(foo)s|%(bar)s' % d
</code></pre>
<p>Or, depending on the problem, you could use list comprehensions:</p>
<pre><code>vlist = ['a', 'b', 'c']
regexp = '|'.join([s for s in vlist])
</code></pre>
<p><b>EDIT:</b> Mat clarified his question, this makes things different and the above mentioned is totally irrelevant.</p>
<p>I'd probably go with an approach like this:</p>
<pre><code>filename = 'bob_20090216.txt'
regexps = {'bob': 'bob_[0-9]+.txt',
'fred': 'fred_[0-9]+.txt',
'paul': 'paul_[0-9]+.txt'}
for filetype, regexp in regexps.items():
m = re.match(regexp, filename)
if m != None:
print '%s is of type %s' % (filename, filetype)
</code></pre>
| 6
|
2009-02-16T23:15:59Z
|
[
"python",
"regex"
] |
Parameterised regular expression in Python
| 554,957
|
<p>In Python, is there a better way to <strong>parameterise strings into regular expressions</strong> than doing it manually like this:</p>
<pre><code>test = 'flobalob'
names = ['a', 'b', 'c']
for name in names:
regexp = "%s" % (name)
print regexp, re.search(regexp, test)
</code></pre>
<p><em>This noddy example tries to match each name in turn. I know there's better ways of doing that, but its a simple example purely to illustrate the point.</em></p>
<p><hr /></p>
<p><strong>The answer appears to be no, there's no real alternative. The best way to paramaterise regular expressions in python is as above or with derivatives such as <code>str.format()</code>.</strong> I tried to write a generic question, rather than <em>'fix ma codez, kthxbye'</em>. For those still interested, I've fleshed out an example closer to my needs here:</p>
<pre><code>for diskfilename in os.listdir(''):
filenames = ['bob.txt', 'fred.txt', 'paul.txt']
for filename in filenames:
name, ext = filename.split('.')
regexp = "%s.*\.%s" % (name, ext)
m = re.search(regexp, diskfilename)
if m:
print diskfilename, regexp, re.search(regexp, diskfilename)
# ...
</code></pre>
<p>I'm trying to figure out the 'type' of a file based on its filename, of the form <code><filename>_<date>.<extension></code>. In my real code, the <code>filenames</code> array is a dict, containing a function to call once a match is found.</p>
<p>Other ways I've considered doing it:</p>
<ul>
<li><p><strong>Have a regular expression in the array.</strong> I already have an array of filenames without any regular expression magic, so I am loathe to do this. I have done this elsewhere in my code and its a mess (though necessary there).</p></li>
<li><p><strong>Match only on the start of the filename.</strong> This would work, but would break with .bak copies of files, etc. At some point I'll probably want to extract the date from the filename so would need to use a regular expression anyway.</p></li>
</ul>
<p><hr /></p>
<p>Thanks for the responses suggesting alternatives to regular expressions to achieve the same end result. I was more interested in parameterising regular expressions for now and for the future. I never come across <em>fnmatch</em>, so its all useful in the long run.</p>
| 3
|
2009-02-16T23:07:59Z
| 555,052
|
<pre><code>import fnmatch, os
filenames = ['bob.txt', 'fred.txt', 'paul.txt']
# 'b.txt.b' -> 'b.txt*.b'
filepatterns = ((f, '*'.join(os.path.splitext(f))) for f in filenames)
diskfilenames = filter(os.path.isfile, os.listdir(''))
pattern2filenames = dict((fn, fnmatch.filter(diskfilenames, pat))
for fn, pat in filepatterns)
print pattern2filenames
</code></pre>
<p>Output:</p>
<pre><code>{'bob.txt': ['bob20090217.txt'], 'paul.txt': [], 'fred.txt': []}
</code></pre>
<p>Answers to previous revisions of your question follow:</p>
<p><hr /></p>
<p>I don't understand your updated question but <code>filename.startswith(prefix)</code> might be sufficient in your specific case.</p>
<p>After you've updated your question the old answer below is less relevant.</p>
<p><hr /></p>
<ol>
<li><p>Use <code>re.escape(name)</code> if you'd like to match a <code>name</code> literally.</p></li>
<li><p>Any tool available for string parametrization is applicable here. For example:</p>
<pre><code>import string
print string.Template("$a $b").substitute(a=1, b="B")
# 1 B
</code></pre>
<p>Or using <a href="http://docs.python.org/library/string.html#format-string-syntax" rel="nofollow"><code>str.format()</code></a> in Python 2.6+:</p>
<pre><code>print "{0.imag}".format(1j+2)
# 1.0
</code></pre></li>
</ol>
| 2
|
2009-02-16T23:40:00Z
|
[
"python",
"regex"
] |
Parameterised regular expression in Python
| 554,957
|
<p>In Python, is there a better way to <strong>parameterise strings into regular expressions</strong> than doing it manually like this:</p>
<pre><code>test = 'flobalob'
names = ['a', 'b', 'c']
for name in names:
regexp = "%s" % (name)
print regexp, re.search(regexp, test)
</code></pre>
<p><em>This noddy example tries to match each name in turn. I know there's better ways of doing that, but its a simple example purely to illustrate the point.</em></p>
<p><hr /></p>
<p><strong>The answer appears to be no, there's no real alternative. The best way to paramaterise regular expressions in python is as above or with derivatives such as <code>str.format()</code>.</strong> I tried to write a generic question, rather than <em>'fix ma codez, kthxbye'</em>. For those still interested, I've fleshed out an example closer to my needs here:</p>
<pre><code>for diskfilename in os.listdir(''):
filenames = ['bob.txt', 'fred.txt', 'paul.txt']
for filename in filenames:
name, ext = filename.split('.')
regexp = "%s.*\.%s" % (name, ext)
m = re.search(regexp, diskfilename)
if m:
print diskfilename, regexp, re.search(regexp, diskfilename)
# ...
</code></pre>
<p>I'm trying to figure out the 'type' of a file based on its filename, of the form <code><filename>_<date>.<extension></code>. In my real code, the <code>filenames</code> array is a dict, containing a function to call once a match is found.</p>
<p>Other ways I've considered doing it:</p>
<ul>
<li><p><strong>Have a regular expression in the array.</strong> I already have an array of filenames without any regular expression magic, so I am loathe to do this. I have done this elsewhere in my code and its a mess (though necessary there).</p></li>
<li><p><strong>Match only on the start of the filename.</strong> This would work, but would break with .bak copies of files, etc. At some point I'll probably want to extract the date from the filename so would need to use a regular expression anyway.</p></li>
</ul>
<p><hr /></p>
<p>Thanks for the responses suggesting alternatives to regular expressions to achieve the same end result. I was more interested in parameterising regular expressions for now and for the future. I never come across <em>fnmatch</em>, so its all useful in the long run.</p>
| 3
|
2009-02-16T23:07:59Z
| 555,055
|
<p>may be <a href="http://docs.python.org/library/glob.html" rel="nofollow">glob</a> and <a href="http://docs.python.org/library/fnmatch.html" rel="nofollow">fnmatch</a> modules can be of some help for you?</p>
| 2
|
2009-02-16T23:41:48Z
|
[
"python",
"regex"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 555,020
|
<p>Try computing x from the product of z and y rather than checking every number from 1 to a million. Think about it: if you were asked to calculate 500*240, which is more efficient - multiplying them, or counting up from 1 until you find the right answer?</p>
| 9
|
2009-02-16T23:25:00Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 555,023
|
<p>comparing string with an integer in</p>
<pre><code>x == z*y
</code></pre>
<p>there are also logical errors</p>
<p>start in reverse order <code>range(999, 99, -1)</code>. that'll be more efficient. remove third loop and second comparison altogether.</p>
| 1
|
2009-02-16T23:25:30Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 555,098
|
<p>The question states:</p>
<pre><code>What is the largest prime factor of the number 600851475143?
</code></pre>
<p>I solved this using C#, but the algorithm itself is language-agnostic.</p>
<ol>
<li>Create a method for determining if a number is prime or not. This can be brute-force (rather than using a much more efficient sieving algorithm) and looks like this:</li>
</ol>
<p><hr /></p>
<pre><code>private static long IsPrime(long input)
{
if ((input % 2) == 0)
{
return 2;
}
else if ((input == 1))
{
return 1;
}
else
{
long threshold = (Convert.ToInt64(Math.Sqrt(input)));
long tryDivide = 3;
while (tryDivide < threshold)
{
if ((input % tryDivide) == 0)
{
Console.WriteLine("Found a factor: " + tryDivide);
return tryDivide;
}
tryDivide += 2;
}
Console.WriteLine("Found a factor: " + input);
return -1;
}
}
</code></pre>
<ol>
<li>Once I have a function to determine primality, I can use this function to find the highest prime factor</li>
</ol>
<p><hr /></p>
<pre><code>private static long HighestPrimeFactor(long input)
{
bool searching = true;
long highestFactor = 0;
while (searching)
{
long factor = IsPrime(input);
if (factor != -1)
{
theFactors.Add(factor);
input = input / factor;
}
if (factor == -1)
{
theFactors.Add(input);
highestFactor = theFactors.Max();
searching = false;
}
}
return highestFactor;
}
</code></pre>
<p>I hope this helps without giving too much away.</p>
| 0
|
2009-02-17T00:04:09Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 555,107
|
<p>Some efficiency issues:</p>
<ol>
<li>start at the top (since we can use this in skipping a lot of calculations)</li>
<li>don't double-calculate</li>
</ol>
<blockquote>
<pre><code>def is_palindrome(n):
s = str(n)
return s == s[::-1]
def biggest():
big_x, big_y, max_seen = 0,0, 0
for x in xrange(999,99,-1):
for y in xrange(x, 99,-1): # so we don't double count
if x*y < max_seen: continue # since we're decreasing,
# nothing else in the row can be bigger
if is_palindrome(x*y):
big_x, big_y, max_seen = x,y, x*y
return big_x,big_y,max_seen
biggest()
# (993, 913, 906609)
</code></pre>
</blockquote>
| 9
|
2009-02-17T00:08:11Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 555,135
|
<p>rather than enumerating all products of 3-digit numbers (~900^2 iterations),
enumerate all 6- and 5-digit palyndromes (this takes ~1000 iterations);
then for each palyndrome decide whether it can be represented by a product
of two 3-digit numbers (if it can't, it should have a 4-digit prime factor,
so this is kind of easy to test).</p>
<p>also, you are asking about problem #4, not #3.</p>
| 1
|
2009-02-17T00:20:51Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 555,167
|
<p>If your program is running slow, and you have nested loops like this:</p>
<pre><code>for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
</code></pre>
<p>Then a question you should ask yourself is: "How many times will the body of the innermost loop execute?" (the body of your innermost loop is the code that starts with: <code>x = str(x)</code>)</p>
<p>In this case, it's easy to figure out. The outer loop will execute 900 times. <em>For each iteration</em> the middle loop will also execute 900 times â that makes 900Ã900, or 810,000, times. Then, for each of those 810,000 iterations, the inner loop will itself execute 999,999 times. I think I need a long to calculate that:</p>
<pre><code>>>> 900*900*999999
809999190000L
</code></pre>
<p>In other words, you're doing your palindrome check almost <em>810 billion</em> times. If you want to make it into the Project Euler recommended limit of 1 minute per problem, you might want to optimise a little :-) (see David's comment)</p>
| -1
|
2009-02-17T00:36:52Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 555,217
|
<p>This is what I did in Java:</p>
<pre><code>public class Euler0004
{
//assumes positive int
static boolean palindrome(int p)
{
//if there's only one char, then it's
// automagically a palindrome
if(p < 10)
return true;
char[] c = String.valueOf(p).toCharArray();
//loop over the char array to check that
// the chars are an in a palindromic manner
for(int i = 0; i < c.length / 2; i++)
if(c[i] != c[c.length-1 - i])
return false;
return true;
}
public static void main(String args[]) throws Exception
{
int num;
int max = 0;
//testing all multiples of two 3 digit numbers.
// we want the biggest palindrome, so we
// iterate backwards
for(int i = 999; i > 99; i--)
{
// start at j == i, so that we
// don't calc 999 * 998 as well as
// 998 * 999...
for(int j = i; j > 99; j--)
{
num = i*j;
//if the number we calculate is smaller
// than the current max, then it can't
// be a solution, so we start again
if(num < max)
break;
//if the number is a palindrome, and it's
// bigger than our previous max, it
// could be the answer
if(palindrome(num) && num > max)
max = num;
}
}
//once we've gone over all of the numbers
// the number remaining is our answer
System.out.println(max);
}
}
</code></pre>
| -1
|
2009-02-17T01:10:10Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 555,218
|
<p>Here's some general optimizations to keep in mind. The posted code handles all of this, but these are general rules to learn that might help with future problems:</p>
<p>1) if you've already checked z = 995, y = 990, you don't need to check z = 990, y = 995. Greg Lind handles this properly</p>
<p>2) You calculate the product of z*y and then you run x over a huge range and compare that value to y*z. For instance, you just calculated 900*950, and then you run x from 1000 to 1M and see if x = 900*950. DO you see the problem with this?</p>
<p>3) Also, what happens to the following code? (this is why your code is returning nothing, but you shouldn't be doing this anyway)</p>
<pre><code>x = str(100)
y = 100
print x == y
</code></pre>
<p>4) If you figure out (3), you're going to be printing a lot of information there. You need to figure out a way to store the max value, and only return that value at the end. </p>
<p>5) Here's a nice way to time your Euler problems:</p>
<pre><code>if __name__ == "__main__":
import time
tStart = time.time()
print "Answer = " + main()
print "Run time = " + str(time.time() - tStart)
</code></pre>
| 3
|
2009-02-17T01:10:59Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 2,129,160
|
<p>The other advice here is great. This code also works. I start with 999 because we know the largest combination possible is 999*999. Not python, but some quickly done pseudo code. </p>
<pre><code>public static int problem4()
{
int biggestSoFar=0;
for(int i = 999; i>99;i--){
for(int j=999; j>99;j--){
if(isPaladrome(i*j))
if(i*j>biggestSoFar)
biggestSoFar=i*j;
}
}
return biggestSoFar;
}
</code></pre>
| 0
|
2010-01-24T22:27:31Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 6,397,877
|
<p>Here is my solution:</p>
<pre><code>polindroms = [(x, y, x * y) for x in range(100, 999) for y in range(100, 999) if str(x * y) == str(x * y)[::-1]]
print max(polindroms, key = lambda item : item[2])
</code></pre>
| -1
|
2011-06-18T18:03:15Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 14,146,888
|
<p>This adds a couple of optimizations to @GreggLind's good solution, cutting the run time in half:</p>
<pre><code>def is_palindrome(n):
s = str(n)
return s == s[::-1]
def biggest():
big_x, big_y, max_seen = 0,0, 0
for x in xrange(999,99,-1):
# Optim. 1: Nothing in any row from here on can be bigger.
if x*x < max_seen: break
for y in xrange(x, 99,-1): # so we don't double count
# Optim. 2: break, not continue
if x*y < max_seen: break # since we're decreasing,
# nothing else in the row can be bigger
if is_palindrome(x*y):
big_x, big_y, max_seen = x,y, x*y
return big_x,big_y,max_seen
biggest()
# (993, 913, 906609)
</code></pre>
<p>The line</p>
<pre><code>if x*x < max_seen: break
</code></pre>
<p>means that once we get to the point where x is less than sqrt of largest palindrome yet seen, not only do we not need to investigate any more factors on that row; we don't even need to investigate any more rows at all, since all remaining rows would start from a number less than the current value of x.</p>
<p>This doesn't reduce the number of times we call <code>is_palindrome()</code>, but it means many fewer iterations of the outer loop. The value of <code>x</code> that it breaks on is 952, so we've eliminated the checking of 853 rows (albeit the "smaller" ones, thanks to the other <code>break</code>).</p>
<p>I also noticed that </p>
<pre><code>if x*y < max_seen: continue
</code></pre>
<p>should be</p>
<pre><code>if x*y < max_seen: break
</code></pre>
<p>We are trying to short-circuit the whole row, not just the current iteration of the inner loop.</p>
<p>When I ran this script using <a href="http://docs.python.org/2/library/profile.html#module-cProfile" rel="nofollow">cProfile</a>, the cumulative time for <code>biggest()</code> was about 56 msec on average, before the optimizations. The optimizations shrank it to about 23 msec. Either optimization alone would deliver most of that improvement, but the first one is slightly more helpful than the second.</p>
| 0
|
2013-01-03T20:39:36Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 14,148,086
|
<p>Wow, this approach improves quite a bit over other implementations on this page, including <a href="http://stackoverflow.com/a/14146888/423105">mine</a>.</p>
<p>Instead of</p>
<ul>
<li>walking down the three-digit factors row by row (first do all y for x = 999, then all y for x = 998, etc.),</li>
</ul>
<p>we</p>
<ul>
<li>walk down the diagonals: first do all x, y such that x + y = 999 + 999; then do all x, y such that x + y = 999 + 998; etc.</li>
</ul>
<p>It's not hard to prove that on each diagonal, the closer x and y are to each other, the higher the product. So we can start from the middle, <code>x = y</code> (or <code>x = y + 1</code> for odd diagonals) and still do the same short-circuit optimizations as before. And because we can start from the highest diagonals, which are the shortest ones, we are likely to find the highest qualifying palindrome much sooner.</p>
<pre><code>maxFactor = 999
minFactor = 100
def biggest():
big_x, big_y, max_seen, prod = 0, 0, 0, 0
for r in xrange(maxFactor, minFactor-1, -1):
if r * r < max_seen: break
# Iterate along diagonals ("ribs"):
# Do rib x + y = r + r
for i in xrange(0, maxFactor - r + 1):
prod = (r + i) * (r - i)
if prod < max_seen: break
if is_palindrome(prod):
big_x, big_y, max_seen = r+i, r-i, prod
# Do rib x + y = r + r - 1
for i in xrange(0, maxFactor - r + 1):
prod = (r + i) * (r - i - 1)
if prod < max_seen: break
if is_palindrome(prod):
big_x, big_y, max_seen = r+i,r-i-1, prod
return big_x, big_y, max_seen
# biggest()
# (993, 913, 906609)
</code></pre>
<h2>A factor-of-almost-3 improvement</h2>
<p>Instead of calling is_palindrome() 6124 times, we now only call it 2228 times. And the total accumulated time has gone from about 23 msec down to about 9!</p>
<p>I'm still wondering if there is a perfectly linear (O(n)) way to generate a list of products of two sets of numbers in descending order. But I'm pretty happy with the above algorithm.</p>
| 1
|
2013-01-03T22:11:23Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 14,149,395
|
<p>Here is a solution that you might consider. It could be far more efficient but only takes a little time to run.</p>
<pre><code>largest = 0
for a in range(100, 1000):
for b in range(100, 1000):
c = a * b
if str(c) == ''.join(reversed(str(c))):
largest = max(largest, c)
print(largest)
</code></pre>
| 0
|
2013-01-04T00:19:00Z
|
[
"python",
"palindrome"
] |
Euler problem number #4
| 555,009
|
<p>Using Python, I am trying to solve <a href="http://projecteuler.net/index.php?section=problems&id=4" rel="nofollow">problem #4</a> of the <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> problems. Can someone please tell me what I am doing incorrectly? The problem is to <strong>Find the largest palindrome made from the product of two 3-digit numbers</strong>. Here is what I have thus far.</p>
<pre><code>import math
def main():
for z in range(100, 1000):
for y in range(100, 1000):
for x in range(1, 1000000):
x = str(x)
if x == x[::-1] and x == z*y:
print x
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2009-02-16T23:21:46Z
| 16,471,389
|
<p>Here is an efficient general solution (~5x faster than others I have seen):</p>
<pre><code>def pgen(factor):
''' Generates stream of palindromes smaller than factor**2
starting with largest possible palindrome '''
pmax = str(factor**2)
half_palindrome = int(pmax[0:len(pmax)/2]) - 1
for x in xrange(half_palindrome, 0, -1):
yield int(str(x) + str(x)[::-1])
def biggest(factor):
''' Returns largest palindrome and factors '''
for palindrome in pgen(factor):
for f1 in xrange(factor/11*11, factor/10, -11):
f2 = palindrome/f1
if f2 > factor:
break
if f2*f1 == palindrome:
return palindrome, f1, f2
>>> biggest(99)
(9009, 99, 91)
>>> biggest(999)
(906609, 993, 913)
>>> biggest(9999)
(99000099, 9999, 9901)
>>> biggest(99999)
(9966006699L, 99979, 99681L)
>>> biggest(9999999)
(99956644665999L, 9998017, 9997647L)
>>> biggest(99999999)
(9999000000009999L, 99999999, 99990001L)
>>> biggest(999999999)
(999900665566009999L, 999920317, 999980347L)
</code></pre>
| 0
|
2013-05-09T21:24:48Z
|
[
"python",
"palindrome"
] |
Multiple output files
| 555,146
|
<p>edit: Initially I was trying to be general but it came out vague. I've included more detail below. </p>
<p>I'm writing a script that pulls in data from two large CSV files, one of people's schedules and the other of information about their schedules. The data is mined and combined to eventually create pajek format graphs for Monday-Sat of peoples connections, with a seventh graph representing all connections over the week with a string of 1's and 0's to indicate which days of the week the connections are made. This last graph is a break from the pajek format and is used by a seperate program written by another researcher.</p>
<p>Pajek format has a large header, and then lists connections as (vertex1 vertex2) unordered pairs. It's difficult to store these pairs in a dictionary, because there are often multiple connections on the same day between two pairs.</p>
<p>I'm wondering what the best way to output to these graphs are. Should I make the large single graph and have a second script deconstruct it into several smaller graphs? Should I keep seven streams open and as I determine a connection write to them, or should I keep some other data structure for each and output them when I can (like a queue)?</p>
| 0
|
2009-02-17T00:29:18Z
| 555,159
|
<p>I would open seven file streams as accumulating them might be quite memory extensive if it's a lot of data. Of course that is only an option if you can sort them live and don't first need all data read to do the sorting.</p>
| 2
|
2009-02-17T00:34:36Z
|
[
"python",
"file-io"
] |
Multiple output files
| 555,146
|
<p>edit: Initially I was trying to be general but it came out vague. I've included more detail below. </p>
<p>I'm writing a script that pulls in data from two large CSV files, one of people's schedules and the other of information about their schedules. The data is mined and combined to eventually create pajek format graphs for Monday-Sat of peoples connections, with a seventh graph representing all connections over the week with a string of 1's and 0's to indicate which days of the week the connections are made. This last graph is a break from the pajek format and is used by a seperate program written by another researcher.</p>
<p>Pajek format has a large header, and then lists connections as (vertex1 vertex2) unordered pairs. It's difficult to store these pairs in a dictionary, because there are often multiple connections on the same day between two pairs.</p>
<p>I'm wondering what the best way to output to these graphs are. Should I make the large single graph and have a second script deconstruct it into several smaller graphs? Should I keep seven streams open and as I determine a connection write to them, or should I keep some other data structure for each and output them when I can (like a queue)?</p>
| 0
|
2009-02-17T00:29:18Z
| 555,396
|
<p><strong>"...pulls in data from two large CSV files, one of people's schedules and the other of information about their schedules."</strong> Vague, but I think I get it.</p>
<p><strong>"The data is mined and combined to eventually create pajek format graphs for Monday-Sat of peoples connections,"</strong> Mined and combined. Cool. Where? In this script? In another application? By some 3rd-party module? By some web service?</p>
<p>Is this row-at-a-time algorithm? Does one row of input produce one connection that gets sent to one or more daily graphs? </p>
<p>Is this an algorithm that has to see an entire schedule before it can produce anything? [If so, it's probably wrong, but I don't really know and your question is pretty vague on this central detail.]</p>
<p><strong>"... a seventh graph representing all connections over the week with a string of 1's and 0's to indicate which days of the week the connections are made."</strong> Incomplete, but probably good enough.</p>
<pre><code>def makeKey2( row2 ):
return ( row2[1], row2[2] ) # Whatever the lookup key is for source2
def makeKey1( row1 ):
return ( row1[3], row1[0] ) # Whatever the lookup key is for source1
dayFile = [ open("day%d.pajek","w") for i in range(6) ]
combined = open("combined.dat","w")
source1 = open( schedules, "r" )
rdr1= csv.reader( source1 )
source2 = open( aboutSchedules, "r" )
rdr2= csv.reader( source2 )
# "Combine" usually means a relational join between source 1 and source 2.
# We'll assume that source2 is a small-ish dimension and the
# source1 is largish facts
aboutDim = dict( (makeKey2(row),row) for row in rdr2 )
for row in rdr1:
connection, dayList = mine_and_combine( row, aboutDim[ makeKey1(row) ] )
for d in dayList:
dayFile[d].write( connection )
flags = [ 1 if d is in dayList else 0 for d in range(6) ]
combined.write( connection, flags )
</code></pre>
<p>Something like that.</p>
<p>The points are:</p>
<ol>
<li><p>One pass through each data source. No nested loops. <strong>O</strong>(<em>n</em>) processing.</p></li>
<li><p>Keep as little in memory as you need to create a useful result.</p></li>
</ol>
| 2
|
2009-02-17T02:56:04Z
|
[
"python",
"file-io"
] |
Match series of (non-nested) balanced parentheses at end of string
| 555,344
|
<p>How can I match one or more parenthetical expressions appearing at the end of string?</p>
<p>Input:</p>
<pre><code>'hello (i) (m:foo)'
</code></pre>
<p>Desired output:</p>
<pre><code>['i', 'm:foo']
</code></pre>
<p>Intended for a python script. Paren marks cannot appear inside of each other (<a href="http://i89.photobucket.com/albums/k220/kipper_308/fran_web.jpg" rel="nofollow">no nesting</a>), and the parenthetical expressions may be separated by whitespace.</p>
<p>It's harder than it might seem at first glance, at least so it seems to me.</p>
| 3
|
2009-02-17T02:29:03Z
| 555,370
|
<p>You don't <em>need</em> to use regex:</p>
<pre><code>def splitter(input):
return [ s.rstrip(" \t)") for s in input.split("(") ][1:]
print splitter('hello (i) (m:foo)')
</code></pre>
<p><strong>Note:</strong> this solution only works if your input is already known to be valid. See MizardX's solution that will work on any input.</p>
| 5
|
2009-02-17T02:40:33Z
|
[
"python",
"regex"
] |
Match series of (non-nested) balanced parentheses at end of string
| 555,344
|
<p>How can I match one or more parenthetical expressions appearing at the end of string?</p>
<p>Input:</p>
<pre><code>'hello (i) (m:foo)'
</code></pre>
<p>Desired output:</p>
<pre><code>['i', 'm:foo']
</code></pre>
<p>Intended for a python script. Paren marks cannot appear inside of each other (<a href="http://i89.photobucket.com/albums/k220/kipper_308/fran_web.jpg" rel="nofollow">no nesting</a>), and the parenthetical expressions may be separated by whitespace.</p>
<p>It's harder than it might seem at first glance, at least so it seems to me.</p>
| 3
|
2009-02-17T02:29:03Z
| 555,404
|
<pre><code>paren_pattern = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)")
def getParens(s):
return paren_pattern.findall(s)
</code></pre>
<p>or even shorter:</p>
<pre><code>getParens = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)").findall
</code></pre>
<p>explaination:</p>
<pre><code>\( # opening paren
([^()]*) # content, captured into group 1
\) # closing paren
(?= # look ahead for...
(?:\s*\([^()]*\))* # a series of parens, separated by whitespace
\s* # possibly more whitespace after
$ # end of string
) # end of look ahead
</code></pre>
| 7
|
2009-02-17T03:02:58Z
|
[
"python",
"regex"
] |
Getting a list of all modules in the current package
| 555,571
|
<p>Here's what I want to do: I want to build a test suite that's organized into packages like tests.ui, tests.text, tests.fileio, etc. In each <code>__</code>init<code>__</code>.py in these packages, I want to make a test suite consisting of all the tests in all the modules in that package. Of course, getting all the tests can be done with unittest.TestLoader, but it seems that I have to add each module individually. So supposing that test.ui has editor<code>_</code>window<code>_</code>test.py and preview<code>_</code>window<code>_</code>test.py, I want the <code>__</code>init<code>__</code>.py to import these two files and get a list of the two module objects. The idea is that I want to automate making the test suites so that I can't forget to include something in the test suite.</p>
<p>What's the best way to do this? It seems like it would be an easy thing to do, but I'm not finding anything.</p>
<p>I'm using Python 2.5 btw.</p>
| 0
|
2009-02-17T05:02:44Z
| 555,682
|
<p>You can use os.listdir to find all files in the test.* directory and then filter out .py files:</p>
<pre><code># Place this code to your __init__.py in test.* directory
import os
modules = []
for name in os.listdir(os.path.dirname(os.path.abspath(__file__))):
m, ext = os.path.splitext()
if ext == '.py':
modules.append(__import__(m))
__all__ = modules
</code></pre>
<p>The magic variable <code>__file__</code> contains filepath of the current module. Try</p>
<pre><code>print __file__
</code></pre>
<p>to check.</p>
| 1
|
2009-02-17T06:20:25Z
|
[
"python",
"unit-testing",
"module",
"packages",
"python-2.5"
] |
Getting a list of all modules in the current package
| 555,571
|
<p>Here's what I want to do: I want to build a test suite that's organized into packages like tests.ui, tests.text, tests.fileio, etc. In each <code>__</code>init<code>__</code>.py in these packages, I want to make a test suite consisting of all the tests in all the modules in that package. Of course, getting all the tests can be done with unittest.TestLoader, but it seems that I have to add each module individually. So supposing that test.ui has editor<code>_</code>window<code>_</code>test.py and preview<code>_</code>window<code>_</code>test.py, I want the <code>__</code>init<code>__</code>.py to import these two files and get a list of the two module objects. The idea is that I want to automate making the test suites so that I can't forget to include something in the test suite.</p>
<p>What's the best way to do this? It seems like it would be an easy thing to do, but I'm not finding anything.</p>
<p>I'm using Python 2.5 btw.</p>
| 0
|
2009-02-17T05:02:44Z
| 555,717
|
<p>Solution to exactly this problem from our django project:</p>
<pre><code>"""Test loader for all module tests
"""
import unittest
import re, os, imp, sys
def find_modules(package):
files = [re.sub('\.py$', '', f) for f in os.listdir(os.path.dirname(package.__file__))
if f.endswith(".py")]
return [imp.load_module(file, *imp.find_module(file, package.__path__)) for file in files]
def suite(package=None):
"""Assemble test suite for Django default test loader"""
if not package: package = myapp.tests # Default argument required for Django test runner
return unittest.TestSuite([unittest.TestLoader().loadTestsFromModule(m)
for m in find_modules(package)])
if __name__ == '__main__':
unittest.TextTestRunner().run(suite(myapp.tests))
</code></pre>
<p>EDIT: The benefit compared to bialix's solution is that you can place this loader anytwhere in the project tree, there's no need to modify <strong>init</strong>.py in every test directory.</p>
| 2
|
2009-02-17T06:37:56Z
|
[
"python",
"unit-testing",
"module",
"packages",
"python-2.5"
] |
Getting a list of all modules in the current package
| 555,571
|
<p>Here's what I want to do: I want to build a test suite that's organized into packages like tests.ui, tests.text, tests.fileio, etc. In each <code>__</code>init<code>__</code>.py in these packages, I want to make a test suite consisting of all the tests in all the modules in that package. Of course, getting all the tests can be done with unittest.TestLoader, but it seems that I have to add each module individually. So supposing that test.ui has editor<code>_</code>window<code>_</code>test.py and preview<code>_</code>window<code>_</code>test.py, I want the <code>__</code>init<code>__</code>.py to import these two files and get a list of the two module objects. The idea is that I want to automate making the test suites so that I can't forget to include something in the test suite.</p>
<p>What's the best way to do this? It seems like it would be an easy thing to do, but I'm not finding anything.</p>
<p>I'm using Python 2.5 btw.</p>
| 0
|
2009-02-17T05:02:44Z
| 555,942
|
<p>Good answers here, but the <strong>best</strong> thing to do would be to use a 3rd party test discovery and runner like:</p>
<ul>
<li><a href="http://somethingaboutorange.com/mrl/projects/nose/" rel="nofollow">Nose</a> (my favourite)</li>
<li><a href="http://twistedmatrix.com/trac/wiki/TwistedTrial" rel="nofollow">Trial</a> (pretty nice, especially when testing async stuff)</li>
<li><a href="http://codespeak.net/py/dist/test.html" rel="nofollow">py.test</a> (less good, in my opinion)</li>
</ul>
<p>They are all compatible with plain unittest.TestCase and you won't have to modify your tests in any way, neither would you have to use the advanced features in any of them. Just use as a suite discovery.</p>
<p>Is there a specific reason you want to reinvent the nasty stuff in these libs?</p>
| 2
|
2009-02-17T08:36:55Z
|
[
"python",
"unit-testing",
"module",
"packages",
"python-2.5"
] |
SQLAlchemy/Elixir validation rules?
| 555,578
|
<p>I just found out how to validate my database input before saving it, but I'm kinda bummed to find there are no premade rules (like validate email, length, etc) that are found in some web based frameworks. Are there any validation libraries laying around anywhere or somewhere that some premade validation lists are hiding that I haven't found yet?</p>
| 1
|
2009-02-17T05:06:35Z
| 555,893
|
<p>Yes. There are. But keep your validation separate from your data layer. (As all the web frameworks do.)</p>
<p>Now the libraries you can use for validation are the exact form libraries from the web frameworks. Start with:</p>
<ul>
<li><a href="http://formencode.org/" rel="nofollow">Formencode</a></li>
</ul>
<p>And a lot of others have sprung up recently, but most of them also deal with some degree of form generation. My personal favourite is <a href="http://wtforms.simplecodes.com/" rel="nofollow">WTForms</a>.</p>
<p>On an interesting note, Formencode actually came from being the validation library for the (now) lesser-used SQLObject library, so it certainly has some traction and usage in this exact domain.</p>
| 3
|
2009-02-17T08:18:18Z
|
[
"python",
"validation",
"sqlalchemy",
"python-elixir"
] |
Character Translation using Python (like the tr command)
| 555,705
|
<p>Is there a way to do character translation (kind of like the tr command) using python</p>
| 28
|
2009-02-17T06:33:06Z
| 555,724
|
<p>See <a href="http://docs.python.org/library/stdtypes.html#str.translate"><code>string.translate</code></a></p>
<pre><code>import string
"abc".translate(string.maketrans("abc", "def")) # => "def"
</code></pre>
<p>Note the doc's comments about subtleties in the translation of unicode strings.</p>
<p>Edit: Since <code>tr</code> is a bit more advanced, also consider using <code>re.sub</code>.</p>
| 29
|
2009-02-17T06:40:10Z
|
[
"python"
] |
Character Translation using Python (like the tr command)
| 555,705
|
<p>Is there a way to do character translation (kind of like the tr command) using python</p>
| 28
|
2009-02-17T06:33:06Z
| 1,385,542
|
<p>If you're using python3 translate is less verbose:</p>
<pre><code>>>> 'abc'.translate(str.maketrans('ac','xy'))
'xby'
</code></pre>
<p>Ahh.. and there is also equivalent to <code>tr -d</code>:</p>
<pre><code>>>> "abc".translate(str.maketrans('','','b'))
'ac'
</code></pre>
<p>For <code>tr -d</code> with python2.x use an additional argument to translate function:</p>
<pre><code>>>> "abc".translate(None, 'b')
'ac'
</code></pre>
| 14
|
2009-09-06T12:17:56Z
|
[
"python"
] |
Character Translation using Python (like the tr command)
| 555,705
|
<p>Is there a way to do character translation (kind of like the tr command) using python</p>
| 28
|
2009-02-17T06:33:06Z
| 19,165,983
|
<p>A simpler approach may be to use replace. e.g.</p>
<pre><code> "abc".replace("abc", "def")
'def'
</code></pre>
<p>No need to import anything. Works in Python 2.x</p>
| -4
|
2013-10-03T18:00:24Z
|
[
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.