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 |
---|---|---|---|---|---|---|---|---|---|
No module named MySQLdb
| 454,854 |
<p>I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.</p>
| 211 |
2009-01-18T09:13:38Z
| 36,183,193 |
<p>In CMD </p>
<pre><code>pip install wheel
pip install pymysql
</code></pre>
<p>in settings.py</p>
<pre><code>import pymysql
pymysql.install_as_MySQLdb()
</code></pre>
<p>It worked with me </p>
| 6 |
2016-03-23T16:08:57Z
|
[
"python",
"django"
] |
No module named MySQLdb
| 454,854 |
<p>I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.</p>
| 211 |
2009-01-18T09:13:38Z
| 36,697,579 |
<p>I have tried methods above, but still no module named 'MySQLdb', finally, I succeed with </p>
<pre><code>easy_install mysql-python
</code></pre>
<p>my env is unbuntu 14.04</p>
| 1 |
2016-04-18T14:57:53Z
|
[
"python",
"django"
] |
No module named MySQLdb
| 454,854 |
<p>I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.</p>
| 211 |
2009-01-18T09:13:38Z
| 38,310,817 |
<p>if your python version is <code>3.5</code>, do a <code>pip install mysqlclient</code>, other things didn't work for me</p>
| 2 |
2016-07-11T15:31:02Z
|
[
"python",
"django"
] |
What's the most efficient way to share large amounts of data between Python and C++
| 454,931 |
<p>I'm writing a system that allows python scripts to be executed within a C++ application. </p>
<p>The python scripts are used to modify values within arrays of data (typically 2048x2048x4 arrays of floats)</p>
<p>I'm currently using numpy arrays created using the array API and registered with Python. </p>
<p>In the python scripts I'm accessing the arrays like</p>
<pre><code>for all x in range(0,Width):
for all y in range(0,Height)
Array[x][y][0] = blah
Array[x][y][1] = blah
Array[x][y][2] = blah
Array[x][y][3] = blah
</code></pre>
<p>This seems to be pretty slow. Is there a quicker way to set this up?</p>
| 2 |
2009-01-18T10:30:46Z
| 454,983 |
<p>You should probably see if you can set several values in the array in one step rather than in four (or more) steps.</p>
<p>I believe the ellipsis syntax may be useful here:</p>
<p><a href="http://stackoverflow.com/questions/118370/how-do-you-use-the-ellipsis-slicing-syntax-in-python">http://stackoverflow.com/questions/118370/how-do-you-use-the-ellipsis-slicing-syntax-in-python</a></p>
<p>Or else something like:</p>
<p><code>Array[x,y,:]=blah</code></p>
<p>or</p>
<p><code>Array[x,y,:]=blah1,blah2,blah3,blah4</code></p>
<p>if you have different values for each element.</p>
<p>That's assuming that the bottle-neck in your code is due to the number of assignments you are doing. It's probably worth doing some profiling to see exactly what's being slow. Try the same code, but without actually storing the results to see if it's much faster. If not then it's probably not the assignment that's slow...</p>
| 0 |
2009-01-18T11:29:14Z
|
[
"c++",
"python",
"optimization"
] |
What's the most efficient way to share large amounts of data between Python and C++
| 454,931 |
<p>I'm writing a system that allows python scripts to be executed within a C++ application. </p>
<p>The python scripts are used to modify values within arrays of data (typically 2048x2048x4 arrays of floats)</p>
<p>I'm currently using numpy arrays created using the array API and registered with Python. </p>
<p>In the python scripts I'm accessing the arrays like</p>
<pre><code>for all x in range(0,Width):
for all y in range(0,Height)
Array[x][y][0] = blah
Array[x][y][1] = blah
Array[x][y][2] = blah
Array[x][y][3] = blah
</code></pre>
<p>This seems to be pretty slow. Is there a quicker way to set this up?</p>
| 2 |
2009-01-18T10:30:46Z
| 455,006 |
<p>You might want to have a look at <a href="http://www.boost.org/doc/libs/1_37_0/libs/python/doc/index.html" rel="nofollow">Boost.Python</a>. It focuses on making C++ code available in Python, but it also provides <a href="http://www.boost.org/doc/libs/1_37_0/libs/python/doc/v2/exec.html" rel="nofollow">exec and eval functions</a> that should allow you to efficiently interact with python code.</p>
| 1 |
2009-01-18T11:43:28Z
|
[
"c++",
"python",
"optimization"
] |
What's the most efficient way to share large amounts of data between Python and C++
| 454,931 |
<p>I'm writing a system that allows python scripts to be executed within a C++ application. </p>
<p>The python scripts are used to modify values within arrays of data (typically 2048x2048x4 arrays of floats)</p>
<p>I'm currently using numpy arrays created using the array API and registered with Python. </p>
<p>In the python scripts I'm accessing the arrays like</p>
<pre><code>for all x in range(0,Width):
for all y in range(0,Height)
Array[x][y][0] = blah
Array[x][y][1] = blah
Array[x][y][2] = blah
Array[x][y][3] = blah
</code></pre>
<p>This seems to be pretty slow. Is there a quicker way to set this up?</p>
| 2 |
2009-01-18T10:30:46Z
| 455,145 |
<p>I thought I would suggest numpy, but you're already using it. I'm afraid that leaves domain-specific changes to do less work. As John Montgomery mentions, you'll need to figure out what is taking the time in the Python code, and determine if you can avoid some of it.</p>
<p>Are there patterns to the work being done in Python? Perhaps you can provide domain-specific helper functions (written in C) that can be called from the Python code. </p>
| 1 |
2009-01-18T13:42:24Z
|
[
"c++",
"python",
"optimization"
] |
Advice on Python/Django and message queues
| 454,944 |
<p>I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons.</p>
<p>Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django project? The rest of my stack is Apache, mod_python, MySQL.</p>
| 40 |
2009-01-18T10:42:53Z
| 454,996 |
<p>If you already have MySQL installed, you could create a table to use as a "todo list" of sorts.</p>
<p>Threads synchronously add jobs to the table, and a batched task removes jobs as they're completed.</p>
<p>That way, there's no need to install and learn more software, and it should work fine as a persistent job store so long as you're not sending <em>lots</em> of email (like >10/sec).</p>
| 0 |
2009-01-18T11:34:32Z
|
[
"python",
"django",
"message-queue"
] |
Advice on Python/Django and message queues
| 454,944 |
<p>I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons.</p>
<p>Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django project? The rest of my stack is Apache, mod_python, MySQL.</p>
| 40 |
2009-01-18T10:42:53Z
| 455,024 |
<p>So far I have found no "nice" solution for this. I have some more strict soft realtime requirements (taking a picture from a cardboard box being labeled) so probably one of the approaches is fast enough for you. I assume emails can wait for a few minutes.</p>
<ul>
<li>A "todo list" in the database processed by a cron job.</li>
<li>A "todo list" in the database processed permanently beeing polled by a daemon.</li>
<li>Using a custom daemon which gets notified by the webserver via an UDP packet (in Production today). Basically my own Queing system with the IP stack for handling the queue.</li>
<li><a href="http://blogs.23.nu/c0re/2007/08/antville-15655/">Using ActiveMQ as a message broker</a> - this didn't work out because of stability issues. Also to me Java Daemons are generally somewhat plump</li>
<li>Using Update Triggers in CouchDB. Nice but Update Triggers are not meant to do heavy image processing, so no good fit for my problem.</li>
</ul>
<p>So far I haven't tried RabbitMQ and XMPP/ejabebrd for handling the problem but they are on my list of next things to try. RabbitMQ got decent Python connectivity during 2008 and there are tons of XMPP libraries.</p>
<p>But perhaps all you need is a correctly configured mailserver on the local machine. This probably would allow you to dump mails synchronously into the local mailserver and thus make your whole software stack much more simple.</p>
| 13 |
2009-01-18T11:54:03Z
|
[
"python",
"django",
"message-queue"
] |
Advice on Python/Django and message queues
| 454,944 |
<p>I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons.</p>
<p>Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django project? The rest of my stack is Apache, mod_python, MySQL.</p>
| 40 |
2009-01-18T10:42:53Z
| 456,024 |
<p>You can also use Twisted for this. But it won't play with django in all cases, it's very dependant on deployment scenarios. The most important thing is every request has to be served by one python process, so you need apache compiled in threaded mode.</p>
| -2 |
2009-01-18T22:21:53Z
|
[
"python",
"django",
"message-queue"
] |
Advice on Python/Django and message queues
| 454,944 |
<p>I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons.</p>
<p>Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django project? The rest of my stack is Apache, mod_python, MySQL.</p>
| 40 |
2009-01-18T10:42:53Z
| 456,389 |
<p>Just add the emails to a database, and then write another script ran by some task scheduler utility (cron comes to mind) to send the emails.</p>
| 1 |
2009-01-19T02:45:50Z
|
[
"python",
"django",
"message-queue"
] |
Advice on Python/Django and message queues
| 454,944 |
<p>I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons.</p>
<p>Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django project? The rest of my stack is Apache, mod_python, MySQL.</p>
| 40 |
2009-01-18T10:42:53Z
| 456,593 |
<p>In your specific case, where it's just an email queue, I wold take the easy way out and use <a href="http://code.google.com/p/django-mailer/" rel="nofollow">django-mailer</a>. As a nice side bonues there are other pluggable projects that are smart enough to take advantage of django-mailer when they see it in the stack.</p>
<p>As for more general queue solutions, I haven't been able to try any of these yet, but here's a list of ones that look more interesting to me:</p>
<ol>
<li><a href="http://parand.com/say/index.php/2008/10/12/beanstalkd-python-basic-tutorial/" rel="nofollow">pybeanstalk/beanstalkd</a></li>
<li><a href="http://code.sixapart.com/trac/gearman/browser/trunk/api/python/lib/gearman" rel="nofollow">python interface to gearman</a> (which is probably much more interesting now with the release of the <a href="http://www.gearmanproject.org/doku.php" rel="nofollow">C version of gearman</a>)</li>
<li><a href="http://memcachedb.org/memcacheq/" rel="nofollow">memcacheQ</a></li>
<li><a href="http://morethanseven.net/2008/09/14/using-python-and-stompserver-get-started-message-q/" rel="nofollow">stomp</a></li>
<li><a href="http://docs.celeryproject.org/en/latest/getting-started/introduction.html" rel="nofollow">Celery</a></li>
</ol>
| 23 |
2009-01-19T05:16:07Z
|
[
"python",
"django",
"message-queue"
] |
Advice on Python/Django and message queues
| 454,944 |
<p>I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons.</p>
<p>Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django project? The rest of my stack is Apache, mod_python, MySQL.</p>
| 40 |
2009-01-18T10:42:53Z
| 714,637 |
<p>Stompserver is a good option. It's lightweight, easy to install and easy to use from Django/python.</p>
<p>We have a system using stompserver in production for sending out emails and processing other jobs asynchronously.</p>
<p>Django saves the emails to the database, a model.post_save handler in Django sends an event to stompserver and stompserver passes the event to a consumer process which does the asynchronous task (sends the email).</p>
<p>It scales up quite nicely because you can add consumer processes at runtime - two consumers can send twice as many emails, and the consumers can be on seperate machines. One slight complication is that each consumer needs its own named queue so Django needs to know how many consumers are available and send events to each queue in a round-robin way. (Two consumers listening on the same queue will both get each message = duplication). If you only want one consumer process then this isn't an issue.</p>
<p>We previously had processes which polled the database continuously for jobs but found that it was adding a lot of load to the system, even when nothing needed to be processed.</p>
| 6 |
2009-04-03T16:15:16Z
|
[
"python",
"django",
"message-queue"
] |
Advice on Python/Django and message queues
| 454,944 |
<p>I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons.</p>
<p>Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django project? The rest of my stack is Apache, mod_python, MySQL.</p>
| 40 |
2009-01-18T10:42:53Z
| 2,661,381 |
<p>You might want to have a look at <a href="http://code.google.com/p/pymq/" rel="nofollow">pymq</a>. It's written in python, talks HTTP with it's clients and allows a host of monitoring and management options for queues.</p>
| 1 |
2010-04-18T06:48:39Z
|
[
"python",
"django",
"message-queue"
] |
Advice on Python/Django and message queues
| 454,944 |
<p>I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons.</p>
<p>Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django project? The rest of my stack is Apache, mod_python, MySQL.</p>
| 40 |
2009-01-18T10:42:53Z
| 3,696,792 |
<p>Is there anything wrong is solving this using the mail infrastructure? Like, every app server running their own mail daemons which will queue any locally submitted mail, which forward to a centralized mail server which can do the mail heavy lifting?</p>
| 1 |
2010-09-12T21:46:40Z
|
[
"python",
"django",
"message-queue"
] |
Advice on Python/Django and message queues
| 454,944 |
<p>I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons.</p>
<p>Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django project? The rest of my stack is Apache, mod_python, MySQL.</p>
| 40 |
2009-01-18T10:42:53Z
| 6,068,702 |
<p><a href="http://www.snakemq.net/" rel="nofollow">http://www.snakemq.net/</a> might work as well</p>
| 1 |
2011-05-20T07:21:04Z
|
[
"python",
"django",
"message-queue"
] |
Advice on Python/Django and message queues
| 454,944 |
<p>I have an application in Django, that needs to send a large number of emails to users in various use cases. I don't want to handle this synchronously within the application for obvious reasons.</p>
<p>Has anyone any recommendations for a message queuing server which integrates well with Python, or they have used on a Django project? The rest of my stack is Apache, mod_python, MySQL.</p>
| 40 |
2009-01-18T10:42:53Z
| 9,856,825 |
<p>Here's a lazy but correct and adequate solution. Use the following database table as a queue. </p>
<pre><code>drop table if exists mailqueue;
create table mailqueue (
id bigint primary key,
subject text not null,
body mediumtext not null,
from varchar(255) not null,
to varchar(255) not null
);
</code></pre>
<p>Senders should insert new rows to the end of this table. </p>
<p>Setup worker threads to pop mails one at a time from the other end (lowest id) and try to send them.</p>
| 0 |
2012-03-25T00:08:09Z
|
[
"python",
"django",
"message-queue"
] |
Using an ordered dict as object dictionary in python
| 455,059 |
<p>I don't know why this doesn't work:</p>
<p>I'm using the <a href="http://dev.pocoo.org/hg/sandbox/raw-file/tip/odict.py">odict</a> class from <a href="http://www.python.org/dev/peps/pep-0372/">PEP 372</a>, but I want to use it as a <code>__dict__</code> member, i.e.:</p>
<pre><code>class Bag(object):
def __init__(self):
self.__dict__ = odict()
</code></pre>
<p>But for some reason I'm getting weird results. This works:</p>
<pre><code>>>> b = Bag()
>>> b.apple = 1
>>> b.apple
1
>>> b.banana = 2
>>> b.banana
2
</code></pre>
<p>But trying to access the actual dictionary doesn't work:</p>
<pre><code>>>> b.__dict__.items()
[]
>>> b.__dict__
odict.odict([])
</code></pre>
<p>And it gets weirder:</p>
<pre><code>>>> b.__dict__['tomato'] = 3
>>> b.tomato
3
>>> b.__dict__
odict.odict([('tomato', 3)])
</code></pre>
<p>I'm feeling very stupid. Can you help me out?</p>
| 8 |
2009-01-18T12:33:03Z
| 455,087 |
<p>The closest answer to your question that I can find is at <a href="http://mail.python.org/pipermail/python-bugs-list/2006-April/033155.html">http://mail.python.org/pipermail/python-bugs-list/2006-April/033155.html</a>.</p>
<p>Basically, if <code>__dict__</code> is not an actual <code>dict()</code>, then it is ignored, and attribute lookup fails.</p>
<p>The alternative for this is to use the odict as a member, and override the getitem and setitem methods accordingly.</p>
<pre><code>>>> class A(object) :
... def __init__(self) :
... self.__dict__['_odict'] = odict()
... def __getattr__(self, value) :
... return self.__dict__['_odict'][value]
... def __setattr__(self, key, value) :
... self.__dict__['_odict'][key] = value
...
>>> a = A()
>>> a
<__main__.A object at 0xb7bce34c>
>>> a.x = 1
>>> a.x
1
>>> a.y = 2
>>> a.y
2
>>> a.odict
odict.odict([('x', 1), ('y', 2)])
</code></pre>
| 8 |
2009-01-18T12:59:34Z
|
[
"python",
"ordereddictionary"
] |
Using an ordered dict as object dictionary in python
| 455,059 |
<p>I don't know why this doesn't work:</p>
<p>I'm using the <a href="http://dev.pocoo.org/hg/sandbox/raw-file/tip/odict.py">odict</a> class from <a href="http://www.python.org/dev/peps/pep-0372/">PEP 372</a>, but I want to use it as a <code>__dict__</code> member, i.e.:</p>
<pre><code>class Bag(object):
def __init__(self):
self.__dict__ = odict()
</code></pre>
<p>But for some reason I'm getting weird results. This works:</p>
<pre><code>>>> b = Bag()
>>> b.apple = 1
>>> b.apple
1
>>> b.banana = 2
>>> b.banana
2
</code></pre>
<p>But trying to access the actual dictionary doesn't work:</p>
<pre><code>>>> b.__dict__.items()
[]
>>> b.__dict__
odict.odict([])
</code></pre>
<p>And it gets weirder:</p>
<pre><code>>>> b.__dict__['tomato'] = 3
>>> b.tomato
3
>>> b.__dict__
odict.odict([('tomato', 3)])
</code></pre>
<p>I'm feeling very stupid. Can you help me out?</p>
| 8 |
2009-01-18T12:33:03Z
| 14,048,352 |
<p>Everything in sykora's answer is correct. Here's an updated solution with the following improvements:</p>
<ol>
<li>works even in the special case of accessing <code>a.__dict__</code> directly</li>
<li>supports copy.copy()</li>
<li>supports the <code>==</code> and <code>!=</code> operators</li>
<li>uses <a href="http://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow"><code>collections.OrderedDict</code></a> from Python 2.7.</li>
</ol>
<p>...</p>
<pre><code>from collections import OrderedDict
class OrderedNamespace(object):
def __init__(self):
super(OrderedNamespace, self).__setattr__( '_odict', OrderedDict() )
def __getattr__(self, key):
odict = super(OrderedNamespace, self).__getattribute__('_odict')
if key in odict:
return odict[key]
return super(OrderedNamespace, self).__getattribute__(key)
def __setattr__(self, key, val):
self._odict[key] = val
@property
def __dict__(self):
return self._odict
def __setstate__(self, state): # Support copy.copy
super(OrderedNamespace, self).__setattr__( '_odict', OrderedDict() )
self._odict.update( state )
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self.__eq__(other)
</code></pre>
| 3 |
2012-12-27T01:30:16Z
|
[
"python",
"ordereddictionary"
] |
Using an ordered dict as object dictionary in python
| 455,059 |
<p>I don't know why this doesn't work:</p>
<p>I'm using the <a href="http://dev.pocoo.org/hg/sandbox/raw-file/tip/odict.py">odict</a> class from <a href="http://www.python.org/dev/peps/pep-0372/">PEP 372</a>, but I want to use it as a <code>__dict__</code> member, i.e.:</p>
<pre><code>class Bag(object):
def __init__(self):
self.__dict__ = odict()
</code></pre>
<p>But for some reason I'm getting weird results. This works:</p>
<pre><code>>>> b = Bag()
>>> b.apple = 1
>>> b.apple
1
>>> b.banana = 2
>>> b.banana
2
</code></pre>
<p>But trying to access the actual dictionary doesn't work:</p>
<pre><code>>>> b.__dict__.items()
[]
>>> b.__dict__
odict.odict([])
</code></pre>
<p>And it gets weirder:</p>
<pre><code>>>> b.__dict__['tomato'] = 3
>>> b.tomato
3
>>> b.__dict__
odict.odict([('tomato', 3)])
</code></pre>
<p>I'm feeling very stupid. Can you help me out?</p>
| 8 |
2009-01-18T12:33:03Z
| 32,377,941 |
<p>If you're looking for a library with attribute access to OrderedDict, the <a href="https://pypi.python.org/pypi/orderedattrdict" rel="nofollow">orderedattrdict</a> package provides this.</p>
<pre><code>>>> from orderedattrdict import AttrDict
>>> conf = AttrDict()
>>> conf['z'] = 1
>>> assert conf.z == 1
>>> conf.y = 2
>>> assert conf['y'] == 2
>>> conf.x = 3
>>> assert conf.keys() == ['z', 'y', 'x']
</code></pre>
<p>Disclosure: I authored this library. Thought it might help future searchers.</p>
| 1 |
2015-09-03T14:07:06Z
|
[
"python",
"ordereddictionary"
] |
Break on exception in pydev
| 455,552 |
<p>Is it possible to get the pydev debugger to break on exception?</p>
| 40 |
2009-01-18T17:39:09Z
| 455,556 |
<p><del>On <strong>any</strong> exception?</p>
<p>If my memory serves me right, in PyDev (in Eclipse) this is possible.</del></p>
<p><hr>
<strong>EDIT:</strong> went through it again, checked <a href="http://docs.python.org/library/pdb.html">pdb documentation</a>, can't find a way to set an exception breakpoint.</p>
<p>If I may suggest a really crude workaround, but if you must, you can call your program from within a <code>try-except</code> block, set a breakpoint there, and once it breaks in the <code>except</code> block just go up the stack and debug your error. </p>
<p><strong>Another edit</strong> This functionality <a href="http://stackoverflow.com/a/6655894/17523">has been added to PyDev</a> </p>
| 16 |
2009-01-18T17:43:29Z
|
[
"python",
"eclipse",
"debugging",
"exception",
"pydev"
] |
Break on exception in pydev
| 455,552 |
<p>Is it possible to get the pydev debugger to break on exception?</p>
| 40 |
2009-01-18T17:39:09Z
| 3,089,496 |
<p>Long since over, but feature requests go <a href="http://sourceforge.net/tracker/?group_id=85796&atid=577332" rel="nofollow">on sourceforge</a>.</p>
| 2 |
2010-06-22T00:52:41Z
|
[
"python",
"eclipse",
"debugging",
"exception",
"pydev"
] |
Break on exception in pydev
| 455,552 |
<p>Is it possible to get the pydev debugger to break on exception?</p>
| 40 |
2009-01-18T17:39:09Z
| 4,545,851 |
<p>I've tried the big try-except trick but it didn't work as expected, you got the stack where it breaks, that is in the except: block, you can't get to the stack where the exception was raised from there, that's pointless.</p>
<p>update: pydev does have break-on-exception facility since 1.6.0, but no UI yet, need some code:
<a href="https://sourceforge.net/tracker/?func=detail&aid=2970886&group_id=85796&atid=577332" rel="nofollow">https://sourceforge.net/tracker/?func=detail&aid=2970886&group_id=85796&atid=577332</a></p>
| 4 |
2010-12-28T11:57:27Z
|
[
"python",
"eclipse",
"debugging",
"exception",
"pydev"
] |
Break on exception in pydev
| 455,552 |
<p>Is it possible to get the pydev debugger to break on exception?</p>
| 40 |
2009-01-18T17:39:09Z
| 6,655,894 |
<p>This was added by the PyDev author, under Run > Manage Python Exception Breakpoints</p>
| 35 |
2011-07-11T20:09:05Z
|
[
"python",
"eclipse",
"debugging",
"exception",
"pydev"
] |
JSON datetime between Python and JavaScript
| 455,580 |
<p>I want to send a datetime.datetime object in serialized form from Python using <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> and de-serialize in JavaScript using JSON. What is the best way to do this?</p>
| 331 |
2009-01-18T17:51:11Z
| 455,863 |
<p>If you're certain that only Javascript will be consuming the JSON, I prefer to pass Javascript <code>Date</code> objects directly.</p>
<p>The <code>ctime()</code> method on <code>datetime</code> objects will return a string that the Javascript Date object can understand.</p>
<pre><code>import datetime
date = datetime.datetime.today()
json = '{"mydate":new Date("%s")}' % date.ctime()
</code></pre>
<p>Javascript will happily use that as an object literal, and you've got your Date object built right in.</p>
| 21 |
2009-01-18T20:51:42Z
|
[
"javascript",
"python",
"json"
] |
JSON datetime between Python and JavaScript
| 455,580 |
<p>I want to send a datetime.datetime object in serialized form from Python using <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> and de-serialize in JavaScript using JSON. What is the best way to do this?</p>
| 331 |
2009-01-18T17:51:11Z
| 456,032 |
<p>For cross language projects I found out that strings containing <a href="http://www.ietf.org/rfc/rfc3339.txt">RfC 3339</a> dates are the best way to go. A RfC 3339 date looks like this:</p>
<pre><code> 1985-04-12T23:20:50.52Z
</code></pre>
<p>I think most of the format is obvious. The only somewhat unusual thing may be the "Z" at the end. It stands for GMT/UTC. You could also add a timezone offset like +02:00 for CEST (Germany in summer). I personally prefer to keep everything in UTC until it is displayed.</p>
<p>For displaying, comparisons and storage you can leave it in string format across all languages. If you need the date for calculations easy to convert it back to a native date object in most language.</p>
<p>So generate the JSON like this:</p>
<pre><code> json.dump(datetime.now().strftime('%Y-%m-%dT%H:%M:%S'))
</code></pre>
<p>Unfortunately Javascripts Date constructor doesn't accept RfC 3339 strings but there are many <a href="http://blog.dansnetwork.com/2008/11/01/javascript-iso8601rfc3339-date-parser/">parsers</a> available on the Internet.</p>
<p><a href="https://github.com/hudora/huTools/blob/master/huTools/hujson.py">huTools.hujson</a> tries to handle the most common encoding issues you might come across in Python code including date/datetime objects while handling timezones correctly.</p>
| 66 |
2009-01-18T22:26:56Z
|
[
"javascript",
"python",
"json"
] |
JSON datetime between Python and JavaScript
| 455,580 |
<p>I want to send a datetime.datetime object in serialized form from Python using <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> and de-serialize in JavaScript using JSON. What is the best way to do this?</p>
| 331 |
2009-01-18T17:51:11Z
| 2,680,060 |
<p>You can add the 'default' parameter to json.dumps to handle this:</p>
<pre><code>date_handler = lambda obj: (
obj.isoformat()
if isinstance(obj, datetime.datetime)
or isinstance(obj, datetime.date)
else None
)
json.dumps(datetime.datetime.now(), default=date_handler)
'"2010-04-20T20:08:21.634121"'
</code></pre>
<p>Which is <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> format. </p>
<p>A more comprehensive default handler function:</p>
<pre><code>def handler(obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
elif isinstance(obj, ...):
return ...
else:
raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj))
</code></pre>
<p>Update: Added output of type as well as value.<br>
Update: Also handle date </p>
| 347 |
2010-04-21T03:09:43Z
|
[
"javascript",
"python",
"json"
] |
JSON datetime between Python and JavaScript
| 455,580 |
<p>I want to send a datetime.datetime object in serialized form from Python using <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> and de-serialize in JavaScript using JSON. What is the best way to do this?</p>
| 331 |
2009-01-18T17:51:11Z
| 3,049,307 |
<p>Using <code>json</code>, you can subclass JSONEncoder and override the default() method to provide your own custom serializers:</p>
<pre><code>import json
import datetime
class DateTimeJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
else:
return super(DateTimeJSONEncoder, self).default(obj)
</code></pre>
<p>Then, you can call it like this:</p>
<pre><code>>>> DateTimeJSONEncoder().encode([datetime.datetime.now()])
'["2010-06-15T14:42:28"]'
</code></pre>
| 46 |
2010-06-15T21:45:25Z
|
[
"javascript",
"python",
"json"
] |
JSON datetime between Python and JavaScript
| 455,580 |
<p>I want to send a datetime.datetime object in serialized form from Python using <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> and de-serialize in JavaScript using JSON. What is the best way to do this?</p>
| 331 |
2009-01-18T17:51:11Z
| 3,235,787 |
<p>Here's a fairly complete solution for recursively encoding and decoding datetime.datetime and datetime.date objects using the standard library <code>json</code> module. This needs Python >= 2.6 since the <code>%f</code> format code in the datetime.datetime.strptime() format string is only supported in since then. For Python 2.5 support, drop the <code>%f</code> and strip the microseconds from the ISO date string before trying to convert it, but you'll loose microseconds precision, of course. For interoperability with ISO date strings from other sources, which may include a time zone name or UTC offset, you may also need to strip some parts of the date string before the conversion. For a complete parser for ISO date strings (and many other date formats) see the third-party <a href="http://labix.org/python-dateutil">dateutil</a> module.</p>
<p>Decoding only works when the ISO date strings are values in a JavaScript
literal object notation or in nested structures within an object. ISO date
strings, which are items of a top-level array will <em>not</em> be decoded.</p>
<p>I.e. this works:</p>
<pre><code>date = datetime.datetime.now()
>>> json = dumps(dict(foo='bar', innerdict=dict(date=date)))
>>> json
'{"innerdict": {"date": "2010-07-15T13:16:38.365579"}, "foo": "bar"}'
>>> loads(json)
{u'innerdict': {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)},
u'foo': u'bar'}
</code></pre>
<p>And this too:</p>
<pre><code>>>> json = dumps(['foo', 'bar', dict(date=date)])
>>> json
'["foo", "bar", {"date": "2010-07-15T13:16:38.365579"}]'
>>> loads(json)
[u'foo', u'bar', {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)}]
</code></pre>
<p>But this doesn't work as expected:</p>
<pre><code>>>> json = dumps(['foo', 'bar', date])
>>> json
'["foo", "bar", "2010-07-15T13:16:38.365579"]'
>>> loads(json)
[u'foo', u'bar', u'2010-07-15T13:16:38.365579']
</code></pre>
<p>Here's the code:</p>
<pre><code>__all__ = ['dumps', 'loads']
import datetime
try:
import json
except ImportError:
import simplejson as json
class JSONDateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime.date, datetime.datetime)):
return obj.isoformat()
else:
return json.JSONEncoder.default(self, obj)
def datetime_decoder(d):
if isinstance(d, list):
pairs = enumerate(d)
elif isinstance(d, dict):
pairs = d.items()
result = []
for k,v in pairs:
if isinstance(v, basestring):
try:
# The %f format code is only supported in Python >= 2.6.
# For Python <= 2.5 strip off microseconds
# v = datetime.datetime.strptime(v.rsplit('.', 1)[0],
# '%Y-%m-%dT%H:%M:%S')
v = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%f')
except ValueError:
try:
v = datetime.datetime.strptime(v, '%Y-%m-%d').date()
except ValueError:
pass
elif isinstance(v, (dict, list)):
v = datetime_decoder(v)
result.append((k, v))
if isinstance(d, list):
return [x[1] for x in result]
elif isinstance(d, dict):
return dict(result)
def dumps(obj):
return json.dumps(obj, cls=JSONDateTimeEncoder)
def loads(obj):
return json.loads(obj, object_hook=datetime_decoder)
if __name__ == '__main__':
mytimestamp = datetime.datetime.utcnow()
mydate = datetime.date.today()
data = dict(
foo = 42,
bar = [mytimestamp, mydate],
date = mydate,
timestamp = mytimestamp,
struct = dict(
date2 = mydate,
timestamp2 = mytimestamp
)
)
print repr(data)
jsonstring = dumps(data)
print jsonstring
print repr(loads(jsonstring))
</code></pre>
| 29 |
2010-07-13T09:26:57Z
|
[
"javascript",
"python",
"json"
] |
JSON datetime between Python and JavaScript
| 455,580 |
<p>I want to send a datetime.datetime object in serialized form from Python using <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> and de-serialize in JavaScript using JSON. What is the best way to do this?</p>
| 331 |
2009-01-18T17:51:11Z
| 6,130,825 |
<p>I've worked it out.</p>
<p>Let's say you have a Python datetime object, <em>d</em>, created with datetime.now(). Its value is:</p>
<pre><code>datetime.datetime(2011, 5, 25, 13, 34, 5, 787000)
</code></pre>
<p>You can serialize it to JSON as an ISO 8601 datetime string:</p>
<pre><code>import json
json.dumps(d.isoformat())
</code></pre>
<p>The example datetime object would be serialized as:</p>
<pre><code>'"2011-05-25T13:34:05.787000"'
</code></pre>
<p>This value, once received in the Javascript layer, can construct a Date object:</p>
<pre><code>var d = new Date("2011-05-25T13:34:05.787000");
</code></pre>
<p>As of Javascript 1.8.5, Date objects have a toJSON method, which returns a string in a standard format. To serialize the above Javascript object back to JSON, therefore, the command would be:</p>
<pre><code>d.toJSON()
</code></pre>
<p>Which would give you:</p>
<pre><code>'2011-05-25T20:34:05.787Z'
</code></pre>
<p>This string, once received in Python, could be deserialized back to a datetime object:</p>
<pre><code>datetime.strptime('2011-05-25T20:34:05.787Z', '%Y-%m-%dT%H:%M:%S.%fZ')
</code></pre>
<p>This results in the following datetime object, which is the same one you started with and therefore correct:</p>
<pre><code>datetime.datetime(2011, 5, 25, 20, 34, 5, 787000)
</code></pre>
| 52 |
2011-05-25T20:55:37Z
|
[
"javascript",
"python",
"json"
] |
JSON datetime between Python and JavaScript
| 455,580 |
<p>I want to send a datetime.datetime object in serialized form from Python using <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> and de-serialize in JavaScript using JSON. What is the best way to do this?</p>
| 331 |
2009-01-18T17:51:11Z
| 20,602,937 |
<p>On python side:</p>
<pre><code>import time, json
from datetime import datetime as dt
your_date = dt.now()
data = json.dumps(time.mktime(your_date.timetuple())*1000)
return data # data send to javascript
</code></pre>
<p>On javascript side:</p>
<pre><code>var your_date = new Date(data)
</code></pre>
<p>where data is result from python</p>
| 4 |
2013-12-16T03:22:24Z
|
[
"javascript",
"python",
"json"
] |
JSON datetime between Python and JavaScript
| 455,580 |
<p>I want to send a datetime.datetime object in serialized form from Python using <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> and de-serialize in JavaScript using JSON. What is the best way to do this?</p>
| 331 |
2009-01-18T17:51:11Z
| 29,744,771 |
<p>My advice is to use a library. There are several available at pypi.org.</p>
<p>I use this one, it it works good: <a href="https://pypi.python.org/pypi/asjson" rel="nofollow">https://pypi.python.org/pypi/asjson</a></p>
| 3 |
2015-04-20T10:01:34Z
|
[
"javascript",
"python",
"json"
] |
JSON datetime between Python and JavaScript
| 455,580 |
<p>I want to send a datetime.datetime object in serialized form from Python using <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> and de-serialize in JavaScript using JSON. What is the best way to do this?</p>
| 331 |
2009-01-18T17:51:11Z
| 32,224,522 |
<p>Late in the game... :) </p>
<p>A very simple solution is to patch the json module default.
For example:</p>
<pre><code>import json
import datetime
json.JSONEncoder.default = lambda self,obj: (obj.isoformat() if isinstance(obj, datetime.datetime) else None)
</code></pre>
<p>Now, you can use <strong>json.dumps()</strong> as if it had always supported datetime...</p>
<pre><code>json.dumps({'created':datetime.datetime.now()})
</code></pre>
<p>This makes sense if you require this extension to the json module to always kick in and wish to not change the way you or others use json serialization (either in existing code or not). </p>
<p>Note that some may consider patching libraries in that way as bad practice.
Special care need to be taken in case you may wish to extend your application in more than one way - is such a case, I suggest to use the solution by ramen or JT and choose the proper json extension in each case. </p>
| 7 |
2015-08-26T10:45:12Z
|
[
"javascript",
"python",
"json"
] |
JSON datetime between Python and JavaScript
| 455,580 |
<p>I want to send a datetime.datetime object in serialized form from Python using <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> and de-serialize in JavaScript using JSON. What is the best way to do this?</p>
| 331 |
2009-01-18T17:51:11Z
| 34,685,105 |
<p>Not much to add to the community wiki answer, except for <strong>timestamp</strong>!</p>
<p>Javascript uses the following format:</p>
<pre><code>new Date().toJSON() // "2016-01-08T19:00:00.123Z"
</code></pre>
<p>Python side (for the <code>json.dumps</code> handler, see the other answers):</p>
<pre><code>>>> from datetime import datetime
>>> d = datetime.strptime('2016-01-08T19:00:00.123Z', '%Y-%m-%dT%H:%M:%S.%fZ')
>>> d
datetime.datetime(2016, 1, 8, 19, 0, 0, 123000)
>>> d.isoformat() + 'Z'
'2016-01-08T19:00:00.123000Z'
</code></pre>
<p>If you leave that Z out, frontend frameworks like angular can not display the date in browser-local timezone:</p>
<pre><code>> $filter('date')('2016-01-08T19:00:00.123000Z', 'yyyy-MM-dd HH:mm:ss')
"2016-01-08 20:00:00"
> $filter('date')('2016-01-08T19:00:00.123000', 'yyyy-MM-dd HH:mm:ss')
"2016-01-08 19:00:00"
</code></pre>
| 2 |
2016-01-08T19:58:55Z
|
[
"javascript",
"python",
"json"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 455,634 |
<p>You are running into the old problem with floating point numbers that all numbers cannot be represented. The command line is just showing you the full floating point form from memory. In floating point your rounded version is the same number. Since computers are binary they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53). Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The <a href="http://docs.python.org/tutorial/floatingpoint.html">floating point in python uses double precision</a> to store the values.</p>
<p>for example</p>
<pre><code> >>> 125650429603636838/(2**53)
13.949999999999999
>>> 234042163/(2**24)
13.949999988079071
>>> a=13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a,2))
13.95
>>> print("{0:.2f}".format(a))
13.95
>>> print("{0:.2f}".format(round(a,2)))
13.95
>>> print("{0:.15f}".format(round(a,2)))
13.949999999999999
</code></pre>
<p>If you are after only two decimal places as in currency then you have a couple of better choices use integers and store values in cents not dollars and then divide by 100 to convert to dollars. Or use a fixed point number like <a href="http://docs.python.org/library/decimal.html">decimal</a></p>
| 687 |
2009-01-18T18:23:53Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 455,658 |
<p>What you can do is modify the output format:</p>
<pre><code>>>> a = 13.95
>>> a
13.949999999999999
>>> print "%.2f" % a
13.95
</code></pre>
| 36 |
2009-01-18T18:31:50Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 455,662 |
<p>It's doing exactly what you told it to do, and working correctly. Read more about <a href="http://www.lahey.com/float.htm">floating point confusion</a> and maybe try <a href="http://docs.python.org/library/decimal.html">Decimal</a> objects instead.</p>
| 8 |
2009-01-18T18:33:45Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 455,678 |
<p>Most numbers cannot be exactly represented in floats. If you want to round the number because that's what your mathematical formula or algorithm requires, then you want to use round. If you just want to restrict the display to a certain precision, then don't even use round and just format it as that string. (If you want to display it with some alternate rounding method, and there are tons, then you need to mix the two approaches.)</p>
<pre><code>>>> "%.2f" % 3.14159
'3.14'
>>> "%.2f" % 13.9499999
'13.95'
</code></pre>
<p>And lastly, though perhaps most importantly, if you want <em>exact</em> math then you don't want floats at all. The usual example is dealing with money and to store 'cents' as an integer.</p>
| 71 |
2009-01-18T18:40:03Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 456,343 |
<p>The python tutorial has an appendix called: <a href="http://docs.python.org/tutorial/floatingpoint.html">Floating Point Arithmetic: Issues and Limitations</a>. Read it. It explains what is happening and why python is doing its best. It has even an example that matches yours. Let me quote a bit:</p>
<blockquote>
<pre><code>>>> 0.1
0.10000000000000001
</code></pre>
<p>you may be tempted to use the <code>round()</code>
function to chop it back to the single
digit you expect. But that makes no
difference:</p>
<pre><code>>>> round(0.1, 1)
0.10000000000000001
</code></pre>
<p>The problem is that the binary
floating-point value stored for <code>â0.1â</code>
was already the best possible binary
approximation to <code>1/10</code>, so trying to
round it again canât make it better:
it was already as good as it gets.</p>
<p>Another consequence is that since <code>0.1</code>
is not exactly <code>1/10</code>, summing ten
values of <code>0.1</code> may not yield exactly
<code>1.0</code>, either:</p>
<pre><code>>>> sum = 0.0
>>> for i in range(10):
... sum += 0.1
...
>>> sum
0.99999999999999989
</code></pre>
</blockquote>
<p>One alternative and solution to your problems would be using the <a href="http://docs.python.org/library/decimal.html"><code>decimal</code></a> module.</p>
| 13 |
2009-01-19T02:05:53Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 6,539,677 |
<p>There are new format specifications, here:</p>
<p><a href="http://docs.python.org/library/string.html#format-specification-mini-language">http://docs.python.org/library/string.html#format-specification-mini-language</a></p>
<p>You can do the same as:</p>
<pre><code>"{0:.2f}".format(13.949999999999999)
</code></pre>
<p><strong>Note</strong> that the above returns a string. in order to get as float, simply wrap with <code>float(...)</code></p>
<pre><code>float("{0:.2f}".format(13.949999999999999))
</code></pre>
<p><strong>Note</strong> that wrapping with <code>float()</code> doesn't change anything:</p>
<pre><code>>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{0:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True
</code></pre>
| 249 |
2011-06-30T18:53:13Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 18,438,167 |
<p>Try codes below:</p>
<pre><code>>>> a = 0.99334
>>> a = int((a * 100) + 0.5) / 100.0 # Adding 0.5 rounds it up
>>> print a
0.99
</code></pre>
| 62 |
2013-08-26T06:46:25Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 20,512,207 |
<p>With python < 3 (e.g. 2.6 or 2.7), there are two ways to do so.</p>
<pre><code># Option one
older_method_string = "%.9f" % numvar
# Option two (note ':' before the '.9f')
newer_method_string = "{:.9f}".format(numvar)
</code></pre>
<p>But note that for python versions above 3 (e.g. 3.2 or 3.3), option two is <a href="http://docs.python.org/2/library/stdtypes.html#str.format">prefered</a></p>
<p>For more info on option two, I suggest this link on <a href="http://docs.python.org/2/library/string.html#formatstrings">string formatting from the python docs</a>.</p>
<p>And for more info on option one, <a href="http://docs.python.org/2/library/stdtypes.html#string-formatting">this link will suffice and has info on the various flags.</a></p>
<p>Refrence: <a href="http://stackoverflow.com/questions/15263597/python-convert-floating-point-number-to-certain-precision-then-copy-to-string">Convert floating point number to certain precision, then copy to String</a></p>
| 22 |
2013-12-11T06:37:46Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 22,821,930 |
<p>for fix the floating point in type dynamic languages such as Python and Javascript I use this technique</p>
<pre><code># for example:
a=70000
b=0.14
c=a*b
print c # prints 980.0000000002
#try to fix
c=int(c * 10000)/100000
print c # prints 980
</code></pre>
| 3 |
2014-04-02T20:08:01Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 28,142,318 |
<p>I feel that the simplest approach is to use the <code>format()</code> function.</p>
<p>For example:</p>
<pre><code>a = 13.949999999999999
format(a, '.2f')
13.95
</code></pre>
<p>This produces a float number as a string rounded to two decimal points.</p>
| 50 |
2015-01-25T22:26:58Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 30,571,233 |
<pre><code>>>> int(0.999991*100)/100.0
>>> 0.99
</code></pre>
| -4 |
2015-06-01T10:32:30Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 32,222,599 |
<p>To round a number to a resolution, the best way is the following one, which can work with any resolution (0.01 for 2 decimals or even other steps)</p>
<pre><code>>>> import numpy as np
>>> value = 13.949999999999999
>>> resolution = 0.01
>>> newValue = int(np.round(value/resolution))*resolution
>>> print newValue
13.95
>>> resolution = 0.5
>>> newValue = int(np.round(value/resolution))*resolution
>>> print newValue
14.0
</code></pre>
| 2 |
2015-08-26T09:17:52Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 34,543,213 |
<p>The method I use is that of string slicing. It's relatively quick and simple.</p>
<p>First, convert the float to a string, the choose the length you would like it to be.</p>
<pre><code>float = str(float)[:5]
</code></pre>
<p>In the single line above, we've converted the value to a string, then kept the string only to its first four digits or characters (inclusive).</p>
<p>Hope that helps!</p>
| -6 |
2015-12-31T08:05:56Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 35,117,668 |
<h2><strong>tldr;)</strong></h2>
<p>The rounding problem at input / output has been <strong>solved by Python 2.7.0</strong> definitively.</p>
<pre><code> import random
for x in iter(random.random, None): # verify FOREVER fixed :-)
assert float(repr(x)) == x # Reversible repr() conversion
assert len(repr(round(x, 10))) <= 12 # Smart decimal places in repr() after round
if x >= 0.1: # Implicit rounding to 12 significant digits
assert str(x) == repr(round(x, 12)) # by str() is good enough for small errors
y = 1000 * x # Decimal type is excessive for shopping
assert str(x) == repr(round(x, 12 - 3)) # in the supermaket with Python 2.7+ :-)
</code></pre>
<h2>docs</h2>
<p>See the <a href="https://docs.python.org/2.7/whatsnew/2.7.html#other-language-changes" rel="nofollow">Release notes Python 2.7 - Other Language Changes</a> the fourth paragraph:</p>
<blockquote>
<p><strong>Conversions</strong> between floating-point numbers and strings are now <strong>correctly rounded</strong> on most platforms. These conversions occur in many different places: str() on floats and complex numbers; the float and complex constructors; numeric formatting; serializing and de-serializing floats and complex numbers using the marshal, pickle and json modules; parsing of float and imaginary literals in Python code; and Decimal-to-float conversion.</p>
<p>Related to this, the <strong>repr()</strong> of a floating-point number x now returns a result based on the <strong>shortest decimal string thatâs guaranteed to round back to x</strong> under correct rounding (with round-half-to-even rounding mode). Previously it gave a string based on rounding x to 17 decimal digits.</p>
</blockquote>
<p><a href="https://bugs.python.org/issue7117" rel="nofollow">The related issue</a></p>
<hr>
<p><strong>EDIT - more info:</strong>: The formatting of <code>float</code> before Python 2.7 was similar to the current <code>numpy.float64</code>. Both types use the same 64 bit <a href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format" rel="nofollow">IEEE 754</a> double precision with 52 bit mantisa. A big difference is that <code>np.float64.__repr__</code> is formated frequently with an excessive decimal number so that no bit can be lost, but no valid IEEE 754 number exists between 13.949999999999999 and 3.950000000000001, the result is not nice and the conversion <code>repr(float(number_as_string))</code> is not reversible. On the other side: <code>float.__repr__</code> is formatted so that every digit is important, the sequence is without gaps and the conversion is reversible. Simply: If you perhaps have a numpy.float64 number, convert it to normal float in order to be formatted for humans not for numeric processors, otherwise nothing more is necessary with Python 2.7+.</p>
| 8 |
2016-01-31T18:33:53Z
|
[
"python",
"floating-point",
"precision"
] |
Limiting floats to two decimal points
| 455,612 |
<p>I want <code>a</code> to be rounded to <em>13.95</em>.</p>
<pre><code>>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
</code></pre>
<p>The <a href="https://docs.python.org/2/library/functions.html#round"><code>round</code></a> function does not work the way I expected.</p>
| 610 |
2009-01-18T18:16:41Z
| 36,455,037 |
<pre><code>def limit_float(num,len):
return float(str(num)[:len-1])
</code></pre>
| -9 |
2016-04-06T15:03:42Z
|
[
"python",
"floating-point",
"precision"
] |
Python 3 development and distribution challenges
| 455,717 |
<p>Suppose I've developed a general-purpose end user utility written in Python. Previously, I had just one version available which was suitable for Python later than version 2.3 or so. It was sufficient to say, "download Python if you need to, then run this script". There was just one version of the script in source control (I'm using Git) to keep track of.</p>
<p>With Python 3, this is no longer necessarily true. For the foreseeable future, I will need to simultaneously develop two different versions, one suitable for Python 2.x and one suitable for Python 3.x. From a development perspective, I can think of a few options:</p>
<ol>
<li>Maintain two different scripts in the same branch, making improvements to both simultaneously.</li>
<li>Maintain two separate branches, and merge common changes back and forth as development proceeds.</li>
<li>Maintain just one version of the script, plus check in a patch file that converts the script from one version to the other. When enough changes have been made that the patch no longer applies cleanly, resolve the conflicts and create a new patch.</li>
</ol>
<p>I am currently leaning toward option 3, as the first two would involve a lot of error-prone tedium. But option 3 seems messy and my source control system is supposed to be managing patches for me.</p>
<p>For distribution packaging, there are more options to choose from:</p>
<ol>
<li>Offer two different download packages, one suitable for Python 2 and one suitable for Python 3 (the user will have to know to download the correct one for whatever version of Python they have).</li>
<li>Offer one download package, with two different scripts inside (and then the user has to know to run the correct one).</li>
<li>One download package with two version-specific scripts, and a small stub loader that can run in both Python versions, that runs the correct script for the Python version installed.</li>
</ol>
<p>Again I am currently leaning toward option 3 here, although I haven't tried to develop such a stub loader yet.</p>
<p>Any other ideas?</p>
| 8 |
2009-01-18T19:01:08Z
| 455,725 |
<p>For developement, option 3 is too cumbersome. Maintaining two branches is the easiest way although the way to do that will vary between VCSes. Many DVCS will be happier with separate repos (with a common ancestry to help merging) and centralized VCS will probably easier to work with with two branches. Option 1 is possible but you may miss something to merge and a bit more error-prone IMO.</p>
<p>For distribution, I'd use option 3 as well if possible. All 3 options are valid anyway and I have seen variations on these models from times to times.</p>
| 2 |
2009-01-18T19:06:36Z
|
[
"python",
"version-control",
"python-3.x"
] |
Python 3 development and distribution challenges
| 455,717 |
<p>Suppose I've developed a general-purpose end user utility written in Python. Previously, I had just one version available which was suitable for Python later than version 2.3 or so. It was sufficient to say, "download Python if you need to, then run this script". There was just one version of the script in source control (I'm using Git) to keep track of.</p>
<p>With Python 3, this is no longer necessarily true. For the foreseeable future, I will need to simultaneously develop two different versions, one suitable for Python 2.x and one suitable for Python 3.x. From a development perspective, I can think of a few options:</p>
<ol>
<li>Maintain two different scripts in the same branch, making improvements to both simultaneously.</li>
<li>Maintain two separate branches, and merge common changes back and forth as development proceeds.</li>
<li>Maintain just one version of the script, plus check in a patch file that converts the script from one version to the other. When enough changes have been made that the patch no longer applies cleanly, resolve the conflicts and create a new patch.</li>
</ol>
<p>I am currently leaning toward option 3, as the first two would involve a lot of error-prone tedium. But option 3 seems messy and my source control system is supposed to be managing patches for me.</p>
<p>For distribution packaging, there are more options to choose from:</p>
<ol>
<li>Offer two different download packages, one suitable for Python 2 and one suitable for Python 3 (the user will have to know to download the correct one for whatever version of Python they have).</li>
<li>Offer one download package, with two different scripts inside (and then the user has to know to run the correct one).</li>
<li>One download package with two version-specific scripts, and a small stub loader that can run in both Python versions, that runs the correct script for the Python version installed.</li>
</ol>
<p>Again I am currently leaning toward option 3 here, although I haven't tried to develop such a stub loader yet.</p>
<p>Any other ideas?</p>
| 8 |
2009-01-18T19:01:08Z
| 455,763 |
<p>Whichever option for development is chosen, most potential issues could be alleviated with thorough unit testing to ensure that the two versions produce matching output. That said, option 2 seems most natural to me: applying changes from one source tree to another source tree is a task (most) version control systems were designed for--why not take advantages of the tools they provide to ease this.</p>
<p>For development, it is difficult to say without 'knowing your audience'. Power Python users would probably appreciate not having to download two copies of your software yet for a more general user-base it should probably 'just work'.</p>
| 0 |
2009-01-18T19:37:11Z
|
[
"python",
"version-control",
"python-3.x"
] |
Python 3 development and distribution challenges
| 455,717 |
<p>Suppose I've developed a general-purpose end user utility written in Python. Previously, I had just one version available which was suitable for Python later than version 2.3 or so. It was sufficient to say, "download Python if you need to, then run this script". There was just one version of the script in source control (I'm using Git) to keep track of.</p>
<p>With Python 3, this is no longer necessarily true. For the foreseeable future, I will need to simultaneously develop two different versions, one suitable for Python 2.x and one suitable for Python 3.x. From a development perspective, I can think of a few options:</p>
<ol>
<li>Maintain two different scripts in the same branch, making improvements to both simultaneously.</li>
<li>Maintain two separate branches, and merge common changes back and forth as development proceeds.</li>
<li>Maintain just one version of the script, plus check in a patch file that converts the script from one version to the other. When enough changes have been made that the patch no longer applies cleanly, resolve the conflicts and create a new patch.</li>
</ol>
<p>I am currently leaning toward option 3, as the first two would involve a lot of error-prone tedium. But option 3 seems messy and my source control system is supposed to be managing patches for me.</p>
<p>For distribution packaging, there are more options to choose from:</p>
<ol>
<li>Offer two different download packages, one suitable for Python 2 and one suitable for Python 3 (the user will have to know to download the correct one for whatever version of Python they have).</li>
<li>Offer one download package, with two different scripts inside (and then the user has to know to run the correct one).</li>
<li>One download package with two version-specific scripts, and a small stub loader that can run in both Python versions, that runs the correct script for the Python version installed.</li>
</ol>
<p>Again I am currently leaning toward option 3 here, although I haven't tried to develop such a stub loader yet.</p>
<p>Any other ideas?</p>
| 8 |
2009-01-18T19:01:08Z
| 455,770 |
<p>I would start by migrating to 2.6, which is very close to python 3.0. You might even want to wait for 2.7, which will be even closer to python 3.0.</p>
<p>And then, once you have migrated to 2.6 (or 2.7), I suggest you simply keep just one version of the script, with things like "if PY3K:... else:..." in the rare places where it will be mandatory. Of course it's not the kind of code we developers like to write, but then you don't have to worry about managing multiple scripts or branches or patches or distributions, which will be a nightmare.</p>
<p>Whatever you choose, make sure you have thorough tests with 100% code coverage.</p>
<p>Good luck!</p>
| 1 |
2009-01-18T19:44:26Z
|
[
"python",
"version-control",
"python-3.x"
] |
Python 3 development and distribution challenges
| 455,717 |
<p>Suppose I've developed a general-purpose end user utility written in Python. Previously, I had just one version available which was suitable for Python later than version 2.3 or so. It was sufficient to say, "download Python if you need to, then run this script". There was just one version of the script in source control (I'm using Git) to keep track of.</p>
<p>With Python 3, this is no longer necessarily true. For the foreseeable future, I will need to simultaneously develop two different versions, one suitable for Python 2.x and one suitable for Python 3.x. From a development perspective, I can think of a few options:</p>
<ol>
<li>Maintain two different scripts in the same branch, making improvements to both simultaneously.</li>
<li>Maintain two separate branches, and merge common changes back and forth as development proceeds.</li>
<li>Maintain just one version of the script, plus check in a patch file that converts the script from one version to the other. When enough changes have been made that the patch no longer applies cleanly, resolve the conflicts and create a new patch.</li>
</ol>
<p>I am currently leaning toward option 3, as the first two would involve a lot of error-prone tedium. But option 3 seems messy and my source control system is supposed to be managing patches for me.</p>
<p>For distribution packaging, there are more options to choose from:</p>
<ol>
<li>Offer two different download packages, one suitable for Python 2 and one suitable for Python 3 (the user will have to know to download the correct one for whatever version of Python they have).</li>
<li>Offer one download package, with two different scripts inside (and then the user has to know to run the correct one).</li>
<li>One download package with two version-specific scripts, and a small stub loader that can run in both Python versions, that runs the correct script for the Python version installed.</li>
</ol>
<p>Again I am currently leaning toward option 3 here, although I haven't tried to develop such a stub loader yet.</p>
<p>Any other ideas?</p>
| 8 |
2009-01-18T19:01:08Z
| 455,831 |
<p>I don't think I'd take this path at all. It's painful whichever way you look at it. Really, unless there's strong commercial interest in keeping both versions simultaneously, this is more headache than gain. </p>
<p>I think it makes more sense to just keep developing for 2.x for now, at least for a few months, up to a year. At some point in time it will be just time to declare on a final, stable version for 2.x and develop the next ones for 3.x+ </p>
<p>For example, I won't switch to 3.x until some of the major frameworks go that way: PyQt, matplotlib, numpy, and some others. And I don't really mind if at some point they stop 2.x support and just start developing for 3.x, because I'll know that in a short time I'll be able to switch to 3.x too.</p>
| 2 |
2009-01-18T20:31:32Z
|
[
"python",
"version-control",
"python-3.x"
] |
Python 3 development and distribution challenges
| 455,717 |
<p>Suppose I've developed a general-purpose end user utility written in Python. Previously, I had just one version available which was suitable for Python later than version 2.3 or so. It was sufficient to say, "download Python if you need to, then run this script". There was just one version of the script in source control (I'm using Git) to keep track of.</p>
<p>With Python 3, this is no longer necessarily true. For the foreseeable future, I will need to simultaneously develop two different versions, one suitable for Python 2.x and one suitable for Python 3.x. From a development perspective, I can think of a few options:</p>
<ol>
<li>Maintain two different scripts in the same branch, making improvements to both simultaneously.</li>
<li>Maintain two separate branches, and merge common changes back and forth as development proceeds.</li>
<li>Maintain just one version of the script, plus check in a patch file that converts the script from one version to the other. When enough changes have been made that the patch no longer applies cleanly, resolve the conflicts and create a new patch.</li>
</ol>
<p>I am currently leaning toward option 3, as the first two would involve a lot of error-prone tedium. But option 3 seems messy and my source control system is supposed to be managing patches for me.</p>
<p>For distribution packaging, there are more options to choose from:</p>
<ol>
<li>Offer two different download packages, one suitable for Python 2 and one suitable for Python 3 (the user will have to know to download the correct one for whatever version of Python they have).</li>
<li>Offer one download package, with two different scripts inside (and then the user has to know to run the correct one).</li>
<li>One download package with two version-specific scripts, and a small stub loader that can run in both Python versions, that runs the correct script for the Python version installed.</li>
</ol>
<p>Again I am currently leaning toward option 3 here, although I haven't tried to develop such a stub loader yet.</p>
<p>Any other ideas?</p>
| 8 |
2009-01-18T19:01:08Z
| 455,840 |
<p><strong>Edit:</strong> my original answer was based on the state of 2009, with Python 2.6 and 3.0 as the current versions. Now, with Python 2.7 and 3.3, there are other options. In particular, it is now quite feasible to use a single code base for Python 2 and Python 3.</p>
<p>See <a href="http://docs.python.org/3/howto/pyporting.html" rel="nofollow">Porting Python 2 Code to Python 3</a></p>
<p><strong>Original answer:</strong></p>
<p>The <a href="http://docs.python.org/3.0/whatsnew/3.0.html#porting-to-python-3-0" rel="nofollow">official recommendation</a> says:</p>
<blockquote>
<p>For porting existing Python 2.5 or 2.6
source code to Python 3.0, the best
strategy is the following:</p>
<ol>
<li><p>(Prerequisite:) Start with excellent test coverage.</p></li>
<li><p>Port to Python 2.6. This should be no more work than the average port
from Python 2.x to Python 2.(x+1).
Make sure all your tests pass.</p></li>
<li><p>(Still using 2.6:) Turn on the -3 command line switch. This enables
warnings about features that will be
removed (or change) in 3.0. Run your
test suite again, and fix code that
you get warnings about until there are
no warnings left, and all your tests
still pass.</p></li>
<li><p>Run the 2to3 source-to-source translator over your source code tree.
(See 2to3 - Automated Python 2 to 3
code translation for more on this
tool.) Run the result of the
translation under Python 3.0. Manually
fix up any remaining issues, fixing
problems until all tests pass again.</p></li>
</ol>
<p>It is not recommended to try to write
source code that runs unchanged under
both Python 2.6 and 3.0; youâd have to
use a very contorted coding style,
e.g. avoiding print statements,
metaclasses, and much more. If you are
maintaining a library that needs to
support both Python 2.6 and Python
3.0, the best approach is to modify step 3 above by editing the 2.6
version of the source code and running
the 2to3 translator again, rather than
editing the 3.0 version of the source
code.</p>
</blockquote>
<p>Ideally, you would end up with a single version, that is 2.6 compatible and can be translated to 3.0 using 2to3. In practice, you might not be able to achieve this goal completely. So you might need some manual modifications to get it to work under 3.0.</p>
<p>I would maintain these modifications in a branch, like your option 2. However, rather than maintaining the final 3.0-compatible version in this branch, I would consider to apply the manual modifications <em>before</em> the 2to3 translations, and put this modified 2.6 code into your branch. The advantage of this method would be that the difference between this branch and the 2.6 trunk would be rather small, and would only consist of manual changes, not the changes made by 2to3. This way, the separate branches should be easier to maintain and merge, and you should be able to benefit from future improvements in 2to3.</p>
<p>Alternatively, take a bit of a "wait and see" approach. Proceed with your porting only so far as you can go with a single 2.6 version plus 2to3 translation, and postpone the remaining manual modification until you really need a 3.0 version. Maybe by this time, you don't need any manual tweaks anymore...</p>
| 9 |
2009-01-18T20:38:22Z
|
[
"python",
"version-control",
"python-3.x"
] |
Is there any advantage in using a Python class?
| 456,001 |
<p>I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?</p>
| 15 |
2009-01-18T22:09:07Z
| 456,008 |
<p>There are none. This is what modules are for: grouping related functions. Using a class full of static methods makes me cringe from Javaitis. The only time I would use a static function is if the function is an integral part of the class. (In fact, I'd probably want to use a class method anyway.)</p>
| 29 |
2009-01-18T22:12:04Z
|
[
"python",
"class",
"static-methods"
] |
Is there any advantage in using a Python class?
| 456,001 |
<p>I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?</p>
| 15 |
2009-01-18T22:09:07Z
| 456,013 |
<p>I agree with Benjamin. Rather than having a bunch of static methods, you should probably have a bunch of functions. And if you want to organize them, you should think about using modules rather than classes. However, if you want to refactor your code to be OO, that's another matter.</p>
| 0 |
2009-01-18T22:15:47Z
|
[
"python",
"class",
"static-methods"
] |
Is there any advantage in using a Python class?
| 456,001 |
<p>I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?</p>
| 15 |
2009-01-18T22:09:07Z
| 456,016 |
<p>Not only are there no advantages, but it makes things slower than using a module full of methods. There's much less need for static methods in python than there is for them in java or c#, they are used in very special cases.</p>
| 0 |
2009-01-18T22:16:26Z
|
[
"python",
"class",
"static-methods"
] |
Is there any advantage in using a Python class?
| 456,001 |
<p>I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?</p>
| 15 |
2009-01-18T22:09:07Z
| 456,018 |
<p>No. It would be better to make them functions and if they are related, place them into their own module. For instance, if you have a class like this:</p>
<pre><code>class Something(object):
@staticmethod
def foo(x):
return x + 5
@staticmethod
def bar(x, y):
return y + 5 * x
</code></pre>
<p>Then it would be better to have a module like,</p>
<pre><code># something.py
def foo(x):
return x + 5
def bar(x, y):
return y + 5 * x
</code></pre>
<p>That way, you use them in the following way:</p>
<pre><code>import something
print something.foo(10)
print something.bar(12, 14)
</code></pre>
<p>Don't be afraid of namespaces. <code>;-)</code></p>
| 11 |
2009-01-18T22:17:46Z
|
[
"python",
"class",
"static-methods"
] |
Is there any advantage in using a Python class?
| 456,001 |
<p>I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?</p>
| 15 |
2009-01-18T22:09:07Z
| 456,081 |
<p>Classes are only useful when you have a set of functionality than interacts with a set of data (instance properties) that needs to be persisted between function calls and referenced in a discrete fashion.</p>
<p>If your class contains nothing other than static methods, then your class is just syntactic cruft, and straight functions are much clearer and all that you need.</p>
| 1 |
2009-01-18T23:02:28Z
|
[
"python",
"class",
"static-methods"
] |
Is there any advantage in using a Python class?
| 456,001 |
<p>I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?</p>
| 15 |
2009-01-18T22:09:07Z
| 456,194 |
<p>If your functions are dependent on each other or global state, consider also the third approach:</p>
<pre><code>class Something(object):
def foo(self, x):
return x + 5
def bar(self, x, y):
return y + 5 * self.foo(x)
something = Something()
</code></pre>
<p>Using this solution you can test a function in isolation, because you can override behavior of another function or inject dependencies using constructor. </p>
| 5 |
2009-01-19T00:16:32Z
|
[
"python",
"class",
"static-methods"
] |
Is there any advantage in using a Python class?
| 456,001 |
<p>I have a Python class full of static methods. What are the advantages and disadvantages of packaging these in a class rather than raw functions?</p>
| 15 |
2009-01-18T22:09:07Z
| 456,222 |
<p>Depends on the nature of the functions. If they're not strongly unrelated (minimal amount of calls between them) and they don't have any state then yes I'd say dump them into a module. However, you could be shooting yourself in the foot if you ever need to modify the behavior as you're throwing inheritance out the window. So my answer is <strong>maybe</strong>, and be sure you look at your particular scenario rather then always assuming a module is the best way to collect a set of methods.</p>
| 0 |
2009-01-19T00:31:36Z
|
[
"python",
"class",
"static-methods"
] |
How do I do what strtok() does in C, in Python?
| 456,084 |
<p>I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much.</p>
<p>If I have this:</p>
<pre><code>A = '1,2,3,4'
B = [int(x) for x in A.split(',')]
B results in [1, 2, 3, 4]
</code></pre>
<p>which is what I expect, but if the string is something more like</p>
<pre><code>A = '1,,2,3,4,'
</code></pre>
<p>if I'm using the same list comprehension expression for B as above, I get an exception. I think I understand why (because some of the "x" string values are not integers), but I'm thinking that there would be a way to parse this still quite elegantly such that tokenization of the string a works a bit more directly like <strong><em>strtok(A,",\n\t")</em></strong> would have done when called iteratively in C.</p>
<p>To be clear what I am asking; I am looking for an elegant/efficient/typical way in Python to have all of the following example cases of strings:</p>
<pre><code>A='1,,2,3,\n,4,\n'
A='1,2,3,4'
A=',1,2,3,4,\t\n'
A='\n\t,1,2,3,,4\n'
</code></pre>
<p>return with the same list of:</p>
<pre><code>B=[1,2,3,4]
</code></pre>
<p>via some sort of compact expression.</p>
| 7 |
2009-01-18T23:03:45Z
| 456,089 |
<p>How about this:</p>
<pre><code>A = '1, 2,,3,4 '
B = [int(x) for x in A.split(',') if x.strip()]
</code></pre>
<p>x.strip() trims whitespace from the string, which will make it empty if the string is all whitespace. An empty string is "false" in a boolean context, so it's filtered by the if part of the list comprehension.</p>
| 26 |
2009-01-18T23:09:34Z
|
[
"python"
] |
How do I do what strtok() does in C, in Python?
| 456,084 |
<p>I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much.</p>
<p>If I have this:</p>
<pre><code>A = '1,2,3,4'
B = [int(x) for x in A.split(',')]
B results in [1, 2, 3, 4]
</code></pre>
<p>which is what I expect, but if the string is something more like</p>
<pre><code>A = '1,,2,3,4,'
</code></pre>
<p>if I'm using the same list comprehension expression for B as above, I get an exception. I think I understand why (because some of the "x" string values are not integers), but I'm thinking that there would be a way to parse this still quite elegantly such that tokenization of the string a works a bit more directly like <strong><em>strtok(A,",\n\t")</em></strong> would have done when called iteratively in C.</p>
<p>To be clear what I am asking; I am looking for an elegant/efficient/typical way in Python to have all of the following example cases of strings:</p>
<pre><code>A='1,,2,3,\n,4,\n'
A='1,2,3,4'
A=',1,2,3,4,\t\n'
A='\n\t,1,2,3,,4\n'
</code></pre>
<p>return with the same list of:</p>
<pre><code>B=[1,2,3,4]
</code></pre>
<p>via some sort of compact expression.</p>
| 7 |
2009-01-18T23:03:45Z
| 456,095 |
<p>I'd guess regular expressions are the way to go: <a href="http://docs.python.org/library/re.html" rel="nofollow">http://docs.python.org/library/re.html</a></p>
| -1 |
2009-01-18T23:12:18Z
|
[
"python"
] |
How do I do what strtok() does in C, in Python?
| 456,084 |
<p>I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much.</p>
<p>If I have this:</p>
<pre><code>A = '1,2,3,4'
B = [int(x) for x in A.split(',')]
B results in [1, 2, 3, 4]
</code></pre>
<p>which is what I expect, but if the string is something more like</p>
<pre><code>A = '1,,2,3,4,'
</code></pre>
<p>if I'm using the same list comprehension expression for B as above, I get an exception. I think I understand why (because some of the "x" string values are not integers), but I'm thinking that there would be a way to parse this still quite elegantly such that tokenization of the string a works a bit more directly like <strong><em>strtok(A,",\n\t")</em></strong> would have done when called iteratively in C.</p>
<p>To be clear what I am asking; I am looking for an elegant/efficient/typical way in Python to have all of the following example cases of strings:</p>
<pre><code>A='1,,2,3,\n,4,\n'
A='1,2,3,4'
A=',1,2,3,4,\t\n'
A='\n\t,1,2,3,,4\n'
</code></pre>
<p>return with the same list of:</p>
<pre><code>B=[1,2,3,4]
</code></pre>
<p>via some sort of compact expression.</p>
| 7 |
2009-01-18T23:03:45Z
| 456,138 |
<p>This will work, and never raise an exception, if all the numbers are ints. The <code>isdigit()</code> call is false if there's a decimal point in the string.</p>
<pre><code>>>> nums = ['1,,2,3,\n,4\n', '1,2,3,4', ',1,2,3,4,\t\n', '\n\t,1,2,3,,4\n']
>>> for n in nums:
... [ int(i.strip()) for i in n if i.strip() and i.strip().isdigit() ]
...
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
</code></pre>
| 0 |
2009-01-18T23:41:52Z
|
[
"python"
] |
How do I do what strtok() does in C, in Python?
| 456,084 |
<p>I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much.</p>
<p>If I have this:</p>
<pre><code>A = '1,2,3,4'
B = [int(x) for x in A.split(',')]
B results in [1, 2, 3, 4]
</code></pre>
<p>which is what I expect, but if the string is something more like</p>
<pre><code>A = '1,,2,3,4,'
</code></pre>
<p>if I'm using the same list comprehension expression for B as above, I get an exception. I think I understand why (because some of the "x" string values are not integers), but I'm thinking that there would be a way to parse this still quite elegantly such that tokenization of the string a works a bit more directly like <strong><em>strtok(A,",\n\t")</em></strong> would have done when called iteratively in C.</p>
<p>To be clear what I am asking; I am looking for an elegant/efficient/typical way in Python to have all of the following example cases of strings:</p>
<pre><code>A='1,,2,3,\n,4,\n'
A='1,2,3,4'
A=',1,2,3,4,\t\n'
A='\n\t,1,2,3,,4\n'
</code></pre>
<p>return with the same list of:</p>
<pre><code>B=[1,2,3,4]
</code></pre>
<p>via some sort of compact expression.</p>
| 7 |
2009-01-18T23:03:45Z
| 456,319 |
<p>How about this?</p>
<pre><code>>>> a = "1,2,,3,4,"
>>> map(int,filter(None,a.split(",")))
[1, 2, 3, 4]
</code></pre>
<p>filter will remove all false values (i.e. empty strings), which are then mapped to int.</p>
<p>EDIT: Just tested this against the above posted versions, and it seems to be significantly faster, 15% or so compared to the strip() one and more than twice as fast as the isdigit() one</p>
| 1 |
2009-01-19T01:49:23Z
|
[
"python"
] |
How do I do what strtok() does in C, in Python?
| 456,084 |
<p>I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much.</p>
<p>If I have this:</p>
<pre><code>A = '1,2,3,4'
B = [int(x) for x in A.split(',')]
B results in [1, 2, 3, 4]
</code></pre>
<p>which is what I expect, but if the string is something more like</p>
<pre><code>A = '1,,2,3,4,'
</code></pre>
<p>if I'm using the same list comprehension expression for B as above, I get an exception. I think I understand why (because some of the "x" string values are not integers), but I'm thinking that there would be a way to parse this still quite elegantly such that tokenization of the string a works a bit more directly like <strong><em>strtok(A,",\n\t")</em></strong> would have done when called iteratively in C.</p>
<p>To be clear what I am asking; I am looking for an elegant/efficient/typical way in Python to have all of the following example cases of strings:</p>
<pre><code>A='1,,2,3,\n,4,\n'
A='1,2,3,4'
A=',1,2,3,4,\t\n'
A='\n\t,1,2,3,,4\n'
</code></pre>
<p>return with the same list of:</p>
<pre><code>B=[1,2,3,4]
</code></pre>
<p>via some sort of compact expression.</p>
| 7 |
2009-01-18T23:03:45Z
| 456,330 |
<p>Generally, I try to avoid regular expressions, but if you want to split on a bunch of different things, they work. Try this:</p>
<pre><code>import re
result = [int(x) for x in filter(None, re.split('[,\n,\t]', A))]
</code></pre>
| 3 |
2009-01-19T01:54:24Z
|
[
"python"
] |
How do I do what strtok() does in C, in Python?
| 456,084 |
<p>I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much.</p>
<p>If I have this:</p>
<pre><code>A = '1,2,3,4'
B = [int(x) for x in A.split(',')]
B results in [1, 2, 3, 4]
</code></pre>
<p>which is what I expect, but if the string is something more like</p>
<pre><code>A = '1,,2,3,4,'
</code></pre>
<p>if I'm using the same list comprehension expression for B as above, I get an exception. I think I understand why (because some of the "x" string values are not integers), but I'm thinking that there would be a way to parse this still quite elegantly such that tokenization of the string a works a bit more directly like <strong><em>strtok(A,",\n\t")</em></strong> would have done when called iteratively in C.</p>
<p>To be clear what I am asking; I am looking for an elegant/efficient/typical way in Python to have all of the following example cases of strings:</p>
<pre><code>A='1,,2,3,\n,4,\n'
A='1,2,3,4'
A=',1,2,3,4,\t\n'
A='\n\t,1,2,3,,4\n'
</code></pre>
<p>return with the same list of:</p>
<pre><code>B=[1,2,3,4]
</code></pre>
<p>via some sort of compact expression.</p>
| 7 |
2009-01-18T23:03:45Z
| 456,401 |
<p>Why not just wrap in a try except block which catches anything not an integer?</p>
| 0 |
2009-01-19T02:50:52Z
|
[
"python"
] |
How do I do what strtok() does in C, in Python?
| 456,084 |
<p>I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much.</p>
<p>If I have this:</p>
<pre><code>A = '1,2,3,4'
B = [int(x) for x in A.split(',')]
B results in [1, 2, 3, 4]
</code></pre>
<p>which is what I expect, but if the string is something more like</p>
<pre><code>A = '1,,2,3,4,'
</code></pre>
<p>if I'm using the same list comprehension expression for B as above, I get an exception. I think I understand why (because some of the "x" string values are not integers), but I'm thinking that there would be a way to parse this still quite elegantly such that tokenization of the string a works a bit more directly like <strong><em>strtok(A,",\n\t")</em></strong> would have done when called iteratively in C.</p>
<p>To be clear what I am asking; I am looking for an elegant/efficient/typical way in Python to have all of the following example cases of strings:</p>
<pre><code>A='1,,2,3,\n,4,\n'
A='1,2,3,4'
A=',1,2,3,4,\t\n'
A='\n\t,1,2,3,,4\n'
</code></pre>
<p>return with the same list of:</p>
<pre><code>B=[1,2,3,4]
</code></pre>
<p>via some sort of compact expression.</p>
| 7 |
2009-01-18T23:03:45Z
| 456,408 |
<p>Mmm, functional goodness (with a bit of generator expression thrown in):</p>
<pre><code>a = "1,2,,3,4,"
print map(int, filter(None, (i.strip() for i in a.split(','))))
</code></pre>
<p>For full functional joy:</p>
<pre><code>import string
a = "1,2,,3,4,"
print map(int, filter(None, map(string.strip, a.split(','))))
</code></pre>
| 4 |
2009-01-19T02:54:49Z
|
[
"python"
] |
How do I do what strtok() does in C, in Python?
| 456,084 |
<p>I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much.</p>
<p>If I have this:</p>
<pre><code>A = '1,2,3,4'
B = [int(x) for x in A.split(',')]
B results in [1, 2, 3, 4]
</code></pre>
<p>which is what I expect, but if the string is something more like</p>
<pre><code>A = '1,,2,3,4,'
</code></pre>
<p>if I'm using the same list comprehension expression for B as above, I get an exception. I think I understand why (because some of the "x" string values are not integers), but I'm thinking that there would be a way to parse this still quite elegantly such that tokenization of the string a works a bit more directly like <strong><em>strtok(A,",\n\t")</em></strong> would have done when called iteratively in C.</p>
<p>To be clear what I am asking; I am looking for an elegant/efficient/typical way in Python to have all of the following example cases of strings:</p>
<pre><code>A='1,,2,3,\n,4,\n'
A='1,2,3,4'
A=',1,2,3,4,\t\n'
A='\n\t,1,2,3,,4\n'
</code></pre>
<p>return with the same list of:</p>
<pre><code>B=[1,2,3,4]
</code></pre>
<p>via some sort of compact expression.</p>
| 7 |
2009-01-18T23:03:45Z
| 458,259 |
<p>Why accept inferior substitutes that cannot segfault your interpreter? With ctypes you can just call the real thing! :-)</p>
<pre><code># strtok in Python
from ctypes import c_char_p, cdll
try: libc = cdll.LoadLibrary('libc.so.6')
except WindowsError:
libc = cdll.LoadLibrary('msvcrt.dll')
libc.strtok.restype = c_char_p
dat = c_char_p("1,,2,3,4")
sep = c_char_p(",\n\t")
result = [libc.strtok(dat, sep)] + list(iter(lambda: libc.strtok(None, sep), None))
print(result)
</code></pre>
| 0 |
2009-01-19T16:43:40Z
|
[
"python"
] |
How do I do what strtok() does in C, in Python?
| 456,084 |
<p>I am learning Python and trying to figure out an efficient way to tokenize a string of numbers separated by commas into a list. Well formed cases work as I expect, but less well formed cases not so much.</p>
<p>If I have this:</p>
<pre><code>A = '1,2,3,4'
B = [int(x) for x in A.split(',')]
B results in [1, 2, 3, 4]
</code></pre>
<p>which is what I expect, but if the string is something more like</p>
<pre><code>A = '1,,2,3,4,'
</code></pre>
<p>if I'm using the same list comprehension expression for B as above, I get an exception. I think I understand why (because some of the "x" string values are not integers), but I'm thinking that there would be a way to parse this still quite elegantly such that tokenization of the string a works a bit more directly like <strong><em>strtok(A,",\n\t")</em></strong> would have done when called iteratively in C.</p>
<p>To be clear what I am asking; I am looking for an elegant/efficient/typical way in Python to have all of the following example cases of strings:</p>
<pre><code>A='1,,2,3,\n,4,\n'
A='1,2,3,4'
A=',1,2,3,4,\t\n'
A='\n\t,1,2,3,,4\n'
</code></pre>
<p>return with the same list of:</p>
<pre><code>B=[1,2,3,4]
</code></pre>
<p>via some sort of compact expression.</p>
| 7 |
2009-01-18T23:03:45Z
| 40,071,673 |
<p>For the sake of completeness, I will answer this seven year old question:
The C program that uses strtok:</p>
<pre><code>int main()
{
char myLine[]="This is;a-line,with pieces";
char *p;
for(p=strtok(myLine, " ;-,"); p != NULL; p=strtok(NULL, " ;-,"))
{
printf("piece=%s\n", p);
}
}
</code></pre>
<p>can be accomplished in python with re.split as:</p>
<pre><code>import re
myLine="This is;a-line,with pieces"
for p in re.split("[ ;\-,]",myLine):
print("piece="+p)
</code></pre>
| 0 |
2016-10-16T14:55:10Z
|
[
"python"
] |
SCons problem - dont understand Variables class
| 456,100 |
<p>I'm working on an SConstruct build file for a project and I'm trying to update from Options to Variables, since Options is being deprecated. I don't understand how to use Variables though. I have 0 python experience which is probably contributing to this.</p>
<p>For example, I have this:</p>
<pre><code>opts = Variables()
opts.Add('fcgi',0)
print opts['fcgi']
</code></pre>
<p>But I get an error:</p>
<pre><code>AttributeError: Variables instance has no attribute '__getitem__':
</code></pre>
<p>Not sure how this is supposed to work</p>
| 3 |
2009-01-18T23:13:16Z
| 476,395 |
<p>That specific error tells you that class <code>Variables</code> hasn't implemented python's <code>__getitem__</code> <a href="http://docs.python.org/reference/datamodel.html#object.__getitem__" rel="nofollow">interface</a> which would allow you to use <code>[ ...]</code> on <code>opts</code>. If all you want to do is print out your keys, the <code>Variables</code> <a href="http://www.scons.org/doc/1.2.0.d20090113/HTML/scons-api/SCons.Variables.Variables-class.html" rel="nofollow">documentation</a> seems to indicate that you can iterate over your keys:</p>
<pre><code>for key in opts.keys():
print key
</code></pre>
<p>Or you can print out the help text:</p>
<pre><code>print opts.GenerateHelpText()
</code></pre>
| 1 |
2009-01-24T17:47:47Z
|
[
"python",
"variables",
"scons"
] |
SCons problem - dont understand Variables class
| 456,100 |
<p>I'm working on an SConstruct build file for a project and I'm trying to update from Options to Variables, since Options is being deprecated. I don't understand how to use Variables though. I have 0 python experience which is probably contributing to this.</p>
<p>For example, I have this:</p>
<pre><code>opts = Variables()
opts.Add('fcgi',0)
print opts['fcgi']
</code></pre>
<p>But I get an error:</p>
<pre><code>AttributeError: Variables instance has no attribute '__getitem__':
</code></pre>
<p>Not sure how this is supposed to work</p>
| 3 |
2009-01-18T23:13:16Z
| 542,096 |
<p>Typically you would store the variables in your environment for later testing.</p>
<pre><code>opts = Variables()
opts.Add('fcgi',0)
env = Environment(variables=opts, ...)
</code></pre>
<p>Then later you can test:</p>
<pre><code>if env['fcgi'] == 0:
# do something
</code></pre>
| 5 |
2009-02-12T16:18:08Z
|
[
"python",
"variables",
"scons"
] |
How to use cvxopt with DSDP?
| 456,224 |
<p>I'm trying to use DSDP (semidefinite programming package) with cvxopt. I have both of them installed (matlab version for DSDP). I have Python 2.5.2.</p>
<p>When trying to use </p>
<pre><code>dsp(..., solver='dsdp')
</code></pre>
<p>I get an errors mentioning solvers.dsdp is not installed.</p>
<p>How to I make them work together?</p>
| 0 |
2009-01-19T00:33:12Z
| 456,627 |
<p>I would suggest asking this question on the <a href="http://groups.google.com/group/cvxopt" rel="nofollow">cvxopt</a> group.</p>
| 0 |
2009-01-19T05:39:24Z
|
[
"python",
"convex-optimization"
] |
Can't get Python to import from a different folder
| 456,481 |
<p>I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:</p>
<pre><code>Server
-server.py
-Models
--user.py
</code></pre>
<p>Here's the contents of server.py:</p>
<pre><code>from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user
u=user.User() #error on this line
</code></pre>
<p>And user.py:</p>
<pre><code>class User(Entity):
using_options(tablename='users')
username = Field(String(15))
password = Field(String(64))
email = Field(String(50))
status = Field(Integer)
created = Field(DateTime)
</code></pre>
<p>The error is:
AttributeError: 'module' object has no attribute 'User'</p>
| 40 |
2009-01-19T03:53:35Z
| 456,491 |
<p>I believe you need to create a file called <code>__init__.py</code> in the Models directory so that python treats it as a module.</p>
<p>Then you can do:</p>
<pre><code>from Models.user import User
</code></pre>
<p>You can include code in the <code>__init__.py</code> (for instance initialization code that a few different classes need) or leave it blank. But it must be there.</p>
| 64 |
2009-01-19T04:00:15Z
|
[
"python"
] |
Can't get Python to import from a different folder
| 456,481 |
<p>I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:</p>
<pre><code>Server
-server.py
-Models
--user.py
</code></pre>
<p>Here's the contents of server.py:</p>
<pre><code>from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user
u=user.User() #error on this line
</code></pre>
<p>And user.py:</p>
<pre><code>class User(Entity):
using_options(tablename='users')
username = Field(String(15))
password = Field(String(64))
email = Field(String(50))
status = Field(Integer)
created = Field(DateTime)
</code></pre>
<p>The error is:
AttributeError: 'module' object has no attribute 'User'</p>
| 40 |
2009-01-19T03:53:35Z
| 456,494 |
<p>You have to create <code>__init__.py</code> on the <code>Models</code> subfolder. The file may be empty. It defines a package.</p>
<p>Then you can do:</p>
<pre><code>from Models.user import User
</code></pre>
<p>Read all about it in python tutorial, <a href="http://docs.python.org/tutorial/modules.html#packages">here</a>.</p>
<p>There is also a good article about file organization of python projects <a href="http://jcalderone.livejournal.com/39794.html">here</a>.</p>
| 18 |
2009-01-19T04:02:22Z
|
[
"python"
] |
Can't get Python to import from a different folder
| 456,481 |
<p>I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:</p>
<pre><code>Server
-server.py
-Models
--user.py
</code></pre>
<p>Here's the contents of server.py:</p>
<pre><code>from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user
u=user.User() #error on this line
</code></pre>
<p>And user.py:</p>
<pre><code>class User(Entity):
using_options(tablename='users')
username = Field(String(15))
password = Field(String(64))
email = Field(String(50))
status = Field(Integer)
created = Field(DateTime)
</code></pre>
<p>The error is:
AttributeError: 'module' object has no attribute 'User'</p>
| 40 |
2009-01-19T03:53:35Z
| 456,495 |
<p>You're missing __init__.py. From the Python tutorial:</p>
<blockquote>
<p>The __init__.py files are required to
make Python treat the directories as
containing packages; this is done to
prevent directories with a common
name, such as string, from
unintentionally hiding valid modules
that occur later on the module search
path. In the simplest case,
__init__.py can just be an empty file, but it can also execute initialization
code for the package or set the
__all__ variable, described later.</p>
</blockquote>
<p>Put an empty file named __init__.py in your Models directory, and all should be golden.</p>
| 7 |
2009-01-19T04:02:31Z
|
[
"python"
] |
Can't get Python to import from a different folder
| 456,481 |
<p>I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:</p>
<pre><code>Server
-server.py
-Models
--user.py
</code></pre>
<p>Here's the contents of server.py:</p>
<pre><code>from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user
u=user.User() #error on this line
</code></pre>
<p>And user.py:</p>
<pre><code>class User(Entity):
using_options(tablename='users')
username = Field(String(15))
password = Field(String(64))
email = Field(String(50))
status = Field(Integer)
created = Field(DateTime)
</code></pre>
<p>The error is:
AttributeError: 'module' object has no attribute 'User'</p>
| 40 |
2009-01-19T03:53:35Z
| 457,630 |
<blockquote>
<p>import user</p>
<p>u=user.User() #error on this line</p>
</blockquote>
<p>Because of the lack of __init__ mentioned above, you would expect an ImportError which would make the problem clearer.</p>
<p>You don't get one because 'user' is also an existing module in the standard library. Your import statement grabs that one and tries to find the User class inside it; that doesn't exist and only then do you get the error.</p>
<p>It is generally a good idea to make your import absolute:</p>
<pre><code>import Server.Models.user
</code></pre>
<p>to avoid this kind of ambiguity. Indeed from Python 2.7 'import user' won't look relative to the current module at all.</p>
<p>If you really want relative imports, you can have them explicitly in Python 2.5 and up using the somewhat ugly syntax:</p>
<pre><code>from .user import User
</code></pre>
| 9 |
2009-01-19T13:51:51Z
|
[
"python"
] |
Can't get Python to import from a different folder
| 456,481 |
<p>I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:</p>
<pre><code>Server
-server.py
-Models
--user.py
</code></pre>
<p>Here's the contents of server.py:</p>
<pre><code>from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user
u=user.User() #error on this line
</code></pre>
<p>And user.py:</p>
<pre><code>class User(Entity):
using_options(tablename='users')
username = Field(String(15))
password = Field(String(64))
email = Field(String(50))
status = Field(Integer)
created = Field(DateTime)
</code></pre>
<p>The error is:
AttributeError: 'module' object has no attribute 'User'</p>
| 40 |
2009-01-19T03:53:35Z
| 9,643,062 |
<p>The right way to import a module located on a parent folder, when you don't have a standard package structure, is:</p>
<pre><code>import os, sys
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))
</code></pre>
<p>(you can merge the last two lines but this way is easier to understand).</p>
<p>This solution is cross-platform and is general enough to need not modify in other circumstances.</p>
| 5 |
2012-03-10T01:15:35Z
|
[
"python"
] |
Can't get Python to import from a different folder
| 456,481 |
<p>I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:</p>
<pre><code>Server
-server.py
-Models
--user.py
</code></pre>
<p>Here's the contents of server.py:</p>
<pre><code>from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user
u=user.User() #error on this line
</code></pre>
<p>And user.py:</p>
<pre><code>class User(Entity):
using_options(tablename='users')
username = Field(String(15))
password = Field(String(64))
email = Field(String(50))
status = Field(Integer)
created = Field(DateTime)
</code></pre>
<p>The error is:
AttributeError: 'module' object has no attribute 'User'</p>
| 40 |
2009-01-19T03:53:35Z
| 18,153,930 |
<p>The solution by glarrain works the best. I ran into the issue of Python being unable to recognize my python modules and gave me 'module not found' error. For me , even after adding <code>__init__.py</code> files and importing the modules appropriately, I still got the same error.
I resolved the issue by following glarrain's answer.</p>
| 1 |
2013-08-09T19:08:59Z
|
[
"python"
] |
Can't get Python to import from a different folder
| 456,481 |
<p>I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:</p>
<pre><code>Server
-server.py
-Models
--user.py
</code></pre>
<p>Here's the contents of server.py:</p>
<pre><code>from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user
u=user.User() #error on this line
</code></pre>
<p>And user.py:</p>
<pre><code>class User(Entity):
using_options(tablename='users')
username = Field(String(15))
password = Field(String(64))
email = Field(String(50))
status = Field(Integer)
created = Field(DateTime)
</code></pre>
<p>The error is:
AttributeError: 'module' object has no attribute 'User'</p>
| 40 |
2009-01-19T03:53:35Z
| 22,525,533 |
<p>how do you write out the parameters <code>os.path.dirname</code>.... command?</p>
<pre><code>import os, sys
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))
</code></pre>
| 1 |
2014-03-20T06:51:17Z
|
[
"python"
] |
Can't get Python to import from a different folder
| 456,481 |
<p>I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:</p>
<pre><code>Server
-server.py
-Models
--user.py
</code></pre>
<p>Here's the contents of server.py:</p>
<pre><code>from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user
u=user.User() #error on this line
</code></pre>
<p>And user.py:</p>
<pre><code>class User(Entity):
using_options(tablename='users')
username = Field(String(15))
password = Field(String(64))
email = Field(String(50))
status = Field(Integer)
created = Field(DateTime)
</code></pre>
<p>The error is:
AttributeError: 'module' object has no attribute 'User'</p>
| 40 |
2009-01-19T03:53:35Z
| 39,152,647 |
<p>My preferred way is to have __init__.py on every directory that contains modules that get used by other modules, and in the entry point, override sys.path as below:</p>
<pre><code>def get_path(ss):
return os.path.join(os.path.dirname(__file__), ss)
sys.path += [
get_path('Server'),
get_path('Models')
]
</code></pre>
<p>This makes the files in specified directories visible for import, and I can import user from Server.py.</p>
| 0 |
2016-08-25T18:45:55Z
|
[
"python"
] |
Throttling with urllib2
| 456,649 |
<p>is it possible to easily cap the kbps when using <code>urllib2</code>?
If it is, any code examples or resources you could direct me to would be greatly appreciated.</p>
| 8 |
2009-01-19T05:53:58Z
| 456,668 |
<p>There is the <code>urlretrieve(url, filename=None, reporthook=None, data=None)</code> function in the <code>urllib</code> module.
If you implement the <code>reporthook</code>-function/object as either a <a href="http://en.wikipedia.org/wiki/Token_bucket">token bucket</a>, or a leaky bucket, you have your global rate-limit.</p>
<p><strong>EDIT:</strong> Upon closer examination I see that it isn't as easy to do global rate-limit with <code>reporthook</code> as I thought. <code>reporthook</code> is only given the downloaded amount and the total size, which on their own isn't enough to information to use with the token-bucket. One way to get around it is by storing the last downloaded amount in each rate-limiter, but use a global token-bucket.</p>
<p><hr /></p>
<p><strong>EDIT 2:</strong> Combined both codes into one example.</p>
<pre><code>"""Rate limiters with shared token bucket."""
import os
import sys
import threading
import time
import urllib
import urlparse
class TokenBucket(object):
"""An implementation of the token bucket algorithm.
source: http://code.activestate.com/recipes/511490/
>>> bucket = TokenBucket(80, 0.5)
>>> print bucket.consume(10)
True
>>> print bucket.consume(90)
False
"""
def __init__(self, tokens, fill_rate):
"""tokens is the total tokens in the bucket. fill_rate is the
rate in tokens/second that the bucket will be refilled."""
self.capacity = float(tokens)
self._tokens = float(tokens)
self.fill_rate = float(fill_rate)
self.timestamp = time.time()
self.lock = threading.RLock()
def consume(self, tokens):
"""Consume tokens from the bucket. Returns 0 if there were
sufficient tokens, otherwise the expected time until enough
tokens become available."""
self.lock.acquire()
tokens = max(tokens,self.tokens)
expected_time = (tokens - self.tokens) / self.fill_rate
if expected_time <= 0:
self._tokens -= tokens
self.lock.release()
return max(0,expected_time)
@property
def tokens(self):
self.lock.acquire()
if self._tokens < self.capacity:
now = time.time()
delta = self.fill_rate * (now - self.timestamp)
self._tokens = min(self.capacity, self._tokens + delta)
self.timestamp = now
value = self._tokens
self.lock.release()
return value
class RateLimit(object):
"""Rate limit a url fetch.
source: http://mail.python.org/pipermail/python-list/2008-January/472859.html
(but mostly rewritten)
"""
def __init__(self, bucket, filename):
self.bucket = bucket
self.last_update = 0
self.last_downloaded_kb = 0
self.filename = filename
self.avg_rate = None
def __call__(self, block_count, block_size, total_size):
total_kb = total_size / 1024.
downloaded_kb = (block_count * block_size) / 1024.
just_downloaded = downloaded_kb - self.last_downloaded_kb
self.last_downloaded_kb = downloaded_kb
predicted_size = block_size/1024.
wait_time = self.bucket.consume(predicted_size)
while wait_time > 0:
time.sleep(wait_time)
wait_time = self.bucket.consume(predicted_size)
now = time.time()
delta = now - self.last_update
if self.last_update != 0:
if delta > 0:
rate = just_downloaded / delta
if self.avg_rate is not None:
rate = 0.9 * self.avg_rate + 0.1 * rate
self.avg_rate = rate
else:
rate = self.avg_rate or 0.
print "%20s: %4.1f%%, %5.1f KiB/s, %.1f/%.1f KiB" % (
self.filename, 100. * downloaded_kb / total_kb,
rate, downloaded_kb, total_kb,
)
self.last_update = now
def main():
"""Fetch the contents of urls"""
if len(sys.argv) < 4:
print 'Syntax: %s rate url1 url2 ...' % sys.argv[0]
raise SystemExit(1)
rate_limit = float(sys.argv[1])
urls = sys.argv[2:]
bucket = TokenBucket(10*rate_limit, rate_limit)
print "rate limit = %.1f" % (rate_limit,)
threads = []
for url in urls:
path = urlparse.urlparse(url,'http')[2]
filename = os.path.basename(path)
print 'Downloading "%s" to "%s"...' % (url,filename)
rate_limiter = RateLimit(bucket, filename)
t = threading.Thread(
target=urllib.urlretrieve,
args=(url, filename, rate_limiter))
t.start()
threads.append(t)
for t in threads:
t.join()
print 'All downloads finished'
if __name__ == "__main__":
main()
</code></pre>
| 18 |
2009-01-19T06:06:17Z
|
[
"python",
"urllib2",
"bandwidth-throttling"
] |
Class factory in Python
| 456,672 |
<p>I'm new to Python and need some advice implementing the scenario below.</p>
<p>I have two classes for managing domains at two different registrars. Both have the same interface, e.g.</p>
<pre><code>class RegistrarA(Object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>and</p>
<pre><code>class RegistrarB(object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>I would like to create a Domain class that, given a domain name, loads the correct registrar class based on the extension, e.g.</p>
<pre><code>com = Domain('test.com') #load RegistrarA
com.lookup()
biz = Domain('test.biz') #load RegistrarB
biz.lookup()
</code></pre>
<p>I know this can be accomplished using a factory function (see below), but is this the best way of doing it or is there a better way using OOP features?</p>
<pre><code>def factory(domain):
if ...:
return RegistrarA(domain)
else:
return RegistrarB(domain)
</code></pre>
| 46 |
2009-01-19T06:08:16Z
| 456,731 |
<p>Assuming you need separate classes for different registrars (though it's not obvious in your example) your solution looks okay, though <strong>RegistrarA</strong> and <strong>RegistrarB</strong> probably share functionality and could be derived from an <a href="http://docs.python.org/2/library/abc.html" rel="nofollow">Abstract Base Class</a>.</p>
<p>As an alternative to your <code>factory</code> function, you could specify a dict, mapping to your registrar classes:</p>
<pre><code>Registrar = {'test.com': RegistrarA, 'test.biz': RegistrarB}
</code></pre>
<p>Then:</p>
<pre><code>registrar = Registrar['test.com'](domain)
</code></pre>
<p>One quibble: You're not really doing a Class Factory here as you're returning instances rather than classes.</p>
| 15 |
2009-01-19T06:39:00Z
|
[
"python",
"factory"
] |
Class factory in Python
| 456,672 |
<p>I'm new to Python and need some advice implementing the scenario below.</p>
<p>I have two classes for managing domains at two different registrars. Both have the same interface, e.g.</p>
<pre><code>class RegistrarA(Object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>and</p>
<pre><code>class RegistrarB(object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>I would like to create a Domain class that, given a domain name, loads the correct registrar class based on the extension, e.g.</p>
<pre><code>com = Domain('test.com') #load RegistrarA
com.lookup()
biz = Domain('test.biz') #load RegistrarB
biz.lookup()
</code></pre>
<p>I know this can be accomplished using a factory function (see below), but is this the best way of doing it or is there a better way using OOP features?</p>
<pre><code>def factory(domain):
if ...:
return RegistrarA(domain)
else:
return RegistrarB(domain)
</code></pre>
| 46 |
2009-01-19T06:08:16Z
| 456,747 |
<p>I think using a function is fine.</p>
<p>The more interesting question is how do you determine which registrar to load? One option is to have an abstract base Registrar class which concrete implementations subclass, then iterate over its <code>__subclasses__()</code> calling an <code>is_registrar_for()</code> class method:</p>
<pre><code>class Registrar(object):
def __init__(self, domain):
self.domain = domain
class RegistrarA(Registrar):
@classmethod
def is_registrar_for(cls, domain):
return domain == 'foo.com'
class RegistrarB(Registrar):
@classmethod
def is_registrar_for(cls, domain):
return domain == 'bar.com'
def Domain(domain):
for cls in Registrar.__subclasses__():
if cls.is_registrar_for(domain):
return cls(domain)
raise ValueError
print Domain('foo.com')
print Domain('bar.com')
</code></pre>
<p>This will let you transparently add new <code>Registrar</code>s and delegate the decision of which domains each supports, to them.</p>
| 62 |
2009-01-19T06:49:03Z
|
[
"python",
"factory"
] |
Class factory in Python
| 456,672 |
<p>I'm new to Python and need some advice implementing the scenario below.</p>
<p>I have two classes for managing domains at two different registrars. Both have the same interface, e.g.</p>
<pre><code>class RegistrarA(Object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>and</p>
<pre><code>class RegistrarB(object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>I would like to create a Domain class that, given a domain name, loads the correct registrar class based on the extension, e.g.</p>
<pre><code>com = Domain('test.com') #load RegistrarA
com.lookup()
biz = Domain('test.biz') #load RegistrarB
biz.lookup()
</code></pre>
<p>I know this can be accomplished using a factory function (see below), but is this the best way of doing it or is there a better way using OOP features?</p>
<pre><code>def factory(domain):
if ...:
return RegistrarA(domain)
else:
return RegistrarB(domain)
</code></pre>
| 46 |
2009-01-19T06:08:16Z
| 545,383 |
<p>In Python you can change the actual class directly:</p>
<pre><code>class Domain(object):
def __init__(self, domain):
self.domain = domain
if ...:
self.__class__ = RegistrarA
else:
self.__class__ = RegistrarB
</code></pre>
<p>And then following will work.</p>
<pre><code>com = Domain('test.com') #load RegistrarA
com.lookup()
</code></pre>
<p>I'm using this approach successfully.</p>
| 10 |
2009-02-13T09:51:01Z
|
[
"python",
"factory"
] |
Class factory in Python
| 456,672 |
<p>I'm new to Python and need some advice implementing the scenario below.</p>
<p>I have two classes for managing domains at two different registrars. Both have the same interface, e.g.</p>
<pre><code>class RegistrarA(Object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>and</p>
<pre><code>class RegistrarB(object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>I would like to create a Domain class that, given a domain name, loads the correct registrar class based on the extension, e.g.</p>
<pre><code>com = Domain('test.com') #load RegistrarA
com.lookup()
biz = Domain('test.biz') #load RegistrarB
biz.lookup()
</code></pre>
<p>I know this can be accomplished using a factory function (see below), but is this the best way of doing it or is there a better way using OOP features?</p>
<pre><code>def factory(domain):
if ...:
return RegistrarA(domain)
else:
return RegistrarB(domain)
</code></pre>
| 46 |
2009-01-19T06:08:16Z
| 16,945,996 |
<p>how about something like </p>
<pre><code>class Domain(object):
registrars = []
@classmethod
def add_registrar( cls, reg ):
registrars.append( reg )
def __init__( self, domain ):
self.domain = domain
for reg in self.__class__.registrars:
if reg.is_registrar_for( domain ):
self.registrar = reg
def lookup( self ):
return self.registrar.lookup()
Domain.add_registrar( RegistrarA )
Domain.add_registrar( RegistrarB )
com = Domain('test.com')
com.lookup()
</code></pre>
| 1 |
2013-06-05T17:13:53Z
|
[
"python",
"factory"
] |
Class factory in Python
| 456,672 |
<p>I'm new to Python and need some advice implementing the scenario below.</p>
<p>I have two classes for managing domains at two different registrars. Both have the same interface, e.g.</p>
<pre><code>class RegistrarA(Object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>and</p>
<pre><code>class RegistrarB(object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>I would like to create a Domain class that, given a domain name, loads the correct registrar class based on the extension, e.g.</p>
<pre><code>com = Domain('test.com') #load RegistrarA
com.lookup()
biz = Domain('test.biz') #load RegistrarB
biz.lookup()
</code></pre>
<p>I know this can be accomplished using a factory function (see below), but is this the best way of doing it or is there a better way using OOP features?</p>
<pre><code>def factory(domain):
if ...:
return RegistrarA(domain)
else:
return RegistrarB(domain)
</code></pre>
| 46 |
2009-01-19T06:08:16Z
| 16,946,959 |
<p>I have this problem all the time. If you have the classes embedded in your application (and its modules) then you can use a function; but if you load plugins dynamically, you need something more dynamic -- registering the classes with a factory via metaclasses automatically.</p>
<p>Here is a pattern I'm sure I lifted from StackOverflow originally, but I don't still have the path to the original post</p>
<pre><code>_registry = {}
class PluginType(type):
def __init__(cls, name, bases, attrs):
_registry[name] = cls
return super(PluginType, cls).__init__(name, bases, attrs)
class Plugin(object):
__metaclass__ = PluginType # python <3.0 only
def __init__(self, *args):
pass
def load_class(plugin_name, plugin_dir):
plugin_file = plugin_name + ".py"
for root, dirs, files in os.walk(plugin_dir) :
if plugin_file in (s for s in files if s.endswith('.py')) :
fp, pathname, description = imp.find_module(plugin_name, [root])
try:
mod = imp.load_module(plugin_name, fp, pathname, description)
finally:
if fp:
fp.close()
return
def get_class(plugin_name) :
t = None
if plugin_name in _registry:
t = _registry[plugin_name]
return t
def get_instance(plugin_name, *args):
return get_class(plugin_name)(*args)
</code></pre>
| 1 |
2013-06-05T18:10:20Z
|
[
"python",
"factory"
] |
Class factory in Python
| 456,672 |
<p>I'm new to Python and need some advice implementing the scenario below.</p>
<p>I have two classes for managing domains at two different registrars. Both have the same interface, e.g.</p>
<pre><code>class RegistrarA(Object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>and</p>
<pre><code>class RegistrarB(object):
def __init__(self, domain):
self.domain = domain
def lookup(self):
...
def register(self, info):
...
</code></pre>
<p>I would like to create a Domain class that, given a domain name, loads the correct registrar class based on the extension, e.g.</p>
<pre><code>com = Domain('test.com') #load RegistrarA
com.lookup()
biz = Domain('test.biz') #load RegistrarB
biz.lookup()
</code></pre>
<p>I know this can be accomplished using a factory function (see below), but is this the best way of doing it or is there a better way using OOP features?</p>
<pre><code>def factory(domain):
if ...:
return RegistrarA(domain)
else:
return RegistrarB(domain)
</code></pre>
| 46 |
2009-01-19T06:08:16Z
| 37,476,396 |
<p>You can create a 'wrapper' class and overload its <code>__new__()</code> method to return instances of the specialized sub-classes, e.g.:</p>
<pre><code>class Registrar(object):
def __new__(self, domain):
if ...:
return RegistrarA(domain)
elif ...:
return RegistrarB(domain)
else:
raise Exception()
</code></pre>
<p>Additionally, in order to deal with non-mutually exclusive conditions, an issue that was raised in other answers, the first question to ask yourself is whether you want the wrapper class, which plays the role of a dispatcher, to govern the conditions, or it will delegate it to the specialized classes. I can suggest a shared mechanism, where the specialized classes define their own conditions, but the wrapper does the validation, like this (provided that each specialized class exposes a class method that verifies whether it is a registrar for a particular domain, is_registrar_for(...) as suggested in other answers):</p>
<pre><code>class Registrar(object):
registrars = [RegistrarA, RegistrarB]
def __new__(self, domain):
matched_registrars = [r for r in self.registrars if r.is_registrar_for(domain)]
if len(matched_registrars) > 1:
raise Exception('More than one registrar matched!')
elif len(matched_registrars) < 1:
raise Exception('No registrar was matched!')
else:
return matched_registrars[0](domain)
</code></pre>
| 1 |
2016-05-27T06:34:03Z
|
[
"python",
"factory"
] |
How to handle the error that occurs on giving wrong number of parameters in a function call in Python?
| 456,673 |
<p>When i give wrong number of parameters in a function , i get errors.
How do I handle it?</p>
<p>I gave </p>
<pre><code>def fun_name(...):
try:
...
except TypeError:
print 'Wrong no of arg'
</code></pre>
<p>It is not working.</p>
<p>Help please.</p>
| 0 |
2009-01-19T06:09:47Z
| 456,679 |
<p>If you remove the <code>try...catch</code> parts it should show you what kind of exception it is throwing.</p>
| -2 |
2009-01-19T06:13:01Z
|
[
"python",
"function-call"
] |
How to handle the error that occurs on giving wrong number of parameters in a function call in Python?
| 456,673 |
<p>When i give wrong number of parameters in a function , i get errors.
How do I handle it?</p>
<p>I gave </p>
<pre><code>def fun_name(...):
try:
...
except TypeError:
print 'Wrong no of arg'
</code></pre>
<p>It is not working.</p>
<p>Help please.</p>
| 0 |
2009-01-19T06:09:47Z
| 456,681 |
<p>The caller triggers this exception, not the receiver.</p>
<p>If you want the receiving function to explicitly check argument count you'll need to use varargs:</p>
<pre><code>def fun_name(*args):
if len(args) != 2:
raise TypeError('Two arguments required')
</code></pre>
| 4 |
2009-01-19T06:13:08Z
|
[
"python",
"function-call"
] |
How to handle the error that occurs on giving wrong number of parameters in a function call in Python?
| 456,673 |
<p>When i give wrong number of parameters in a function , i get errors.
How do I handle it?</p>
<p>I gave </p>
<pre><code>def fun_name(...):
try:
...
except TypeError:
print 'Wrong no of arg'
</code></pre>
<p>It is not working.</p>
<p>Help please.</p>
| 0 |
2009-01-19T06:09:47Z
| 456,683 |
<p>You need to handle it where you call the function.</p>
<pre><code>try:
fun_name(...)
except TypeError:
print "error!"
</code></pre>
| 4 |
2009-01-19T06:13:24Z
|
[
"python",
"function-call"
] |
How to handle the error that occurs on giving wrong number of parameters in a function call in Python?
| 456,673 |
<p>When i give wrong number of parameters in a function , i get errors.
How do I handle it?</p>
<p>I gave </p>
<pre><code>def fun_name(...):
try:
...
except TypeError:
print 'Wrong no of arg'
</code></pre>
<p>It is not working.</p>
<p>Help please.</p>
| 0 |
2009-01-19T06:09:47Z
| 457,026 |
<p>If you call a function with the wrong number of parameters then there are two possibilities:</p>
<ul>
<li>Either you design your function to handle an arbitrary number of arguments. Then you should know what to do with the extra arguments. The answer of Alec Thomas shows you how to handle this case.</li>
<li>Or your design is fundamentally flawed and you are in deep trouble. Catching the error doesn't help in this case.</li>
</ul>
| 0 |
2009-01-19T09:38:55Z
|
[
"python",
"function-call"
] |
Evaluate my Python server structure
| 456,753 |
<p>I'm building a game server in Python and I just wanted to get some input on the architecture of the server that I was thinking up.</p>
<p>So, as we all know, Python cannot scale across cores with a single process. Therefore, on a server with 4 cores, I would need to spawn 4 processes. </p>
<p>Here is the steps taken when a client wishes to connect to the server cluster:</p>
<p>The IP the client initially communicates with is the Gateway node. The gateway keeps track of how many clients are on each machine, and forwards the connection request to the machine with the lowest client count.</p>
<p>On each machine, there is one Manager process and X Server processes, where X is the number of cores on the processor (since Python cannot scale across cores, we need to spawn 4 cores to use 100% of a quad core processor)</p>
<p>The manager's job is to keep track of how many clients are on each process, as well as to restart the processes if any of them crash. When a connection request is sent from the gateway to a manager, the manager looks at its server processes on that machine (3 in the diagram) and forwards the request to whatever process has the least amount of clients.</p>
<p>The Server process is what actually does the communicating with the client.</p>
<p>Here is what a 3 machine cluster would look like. For the sake of the diagram, assume each node has 3 cores.
<img src="http://img152.imageshack.us/img152/5412/serverlx2.jpg" alt="alt text" /></p>
<p>This also got me thinking - could I implement hot swapping this way? Since each process is controlled by the manager, when I want to swap in a new version of the server process I just let the manager know that it should not send any more connections to it, and then I will register the new version process with the old one. The old version is kept alive as long as clients are connected to it, then terminates when there are no more.</p>
<p>Phew. Let me know what you guys think.</p>
| 3 |
2009-01-19T06:51:37Z
| 456,824 |
<p>Sounds like you'll want to look at <a href="http://pyprocessing.berlios.de/">PyProcessing</a>, now included in Python 2.6 and beyond as <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a>. It takes care of a lot of the machinery of dealing with multiple processes.</p>
<p>An alternative architectural model is to setup a work queue using something like <a href="http://xph.us/software/beanstalkd/">beanstalkd</a> and have each of the "servers" pull jobs from the queue. That way you can add servers as you wish, swap them out, etc, without having to worry about registering them with the manager (this is assuming the work you're spreading over the servers can be quantified as "jobs").</p>
<p>Finally, it may be worthwhile to build the whole thing on HTTP and take advantage of existing well known and highly scalable load distribution mechanisms, such as <a href="http://nginx.net/">nginx</a>. If you can make the communication HTTP based then you'll be able to use lots of off-the-shelf tools to handle most of what you describe.</p>
| 5 |
2009-01-19T07:50:14Z
|
[
"python"
] |
AttributeError: 'module' object has no attribute 'model'
| 456,867 |
<p>Can anyone help me please to solve this..</p>
<pre><code>from django.db import models
# Create your models here.
class Poll(models.model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
</code></pre>
<p>Running:</p>
<pre><code>c:\projects\mysite>python manage.py sql polls
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Python25\Lib\site-packages\django\core\management\__init__.py", line 340, in execute_manager
utility.execute()
File "C:\Python25\Lib\site-packages\django\core\management\__init__.py", line 295, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 195, in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 221, in execute
self.validate()
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "C:\Python25\lib\site-packages\django\core\management\validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 128, in get_app_errors
self._populate()
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 57, in _populate
self.load_app(app_name, True)
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 72, in load_app
mod = __import__(app_name, {}, {}, ['models'])
File "c:\projects\mysite\..\mysite\polls\models.py", line 4, in <module>
class Poll(models.model):
AttributeError: 'module' object has no attribute 'model'
</code></pre>
| 14 |
2009-01-19T08:19:25Z
| 456,880 |
<p>As the error message says in the last line: the module <code>models</code> in the file <code>c:\projects\mysite..\mysite\polls\models.py</code> contains no class <code>model</code>. This error occurs in the definition of the <code>Poll</code> class:</p>
<pre><code>class Poll(models.model):
</code></pre>
<p>Either the class <code>model</code> is misspelled in the definition of the class <code>Poll</code> or it is misspelled in the module <code>models</code>. Another possibility is that it is completely missing from the module <code>models</code>. Maybe it is in another module or it is not yet implemented in <code>models</code>.</p>
| 2 |
2009-01-19T08:29:13Z
|
[
"python",
"django"
] |
AttributeError: 'module' object has no attribute 'model'
| 456,867 |
<p>Can anyone help me please to solve this..</p>
<pre><code>from django.db import models
# Create your models here.
class Poll(models.model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
</code></pre>
<p>Running:</p>
<pre><code>c:\projects\mysite>python manage.py sql polls
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Python25\Lib\site-packages\django\core\management\__init__.py", line 340, in execute_manager
utility.execute()
File "C:\Python25\Lib\site-packages\django\core\management\__init__.py", line 295, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 195, in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 221, in execute
self.validate()
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "C:\Python25\lib\site-packages\django\core\management\validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 128, in get_app_errors
self._populate()
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 57, in _populate
self.load_app(app_name, True)
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 72, in load_app
mod = __import__(app_name, {}, {}, ['models'])
File "c:\projects\mysite\..\mysite\polls\models.py", line 4, in <module>
class Poll(models.model):
AttributeError: 'module' object has no attribute 'model'
</code></pre>
| 14 |
2009-01-19T08:19:25Z
| 456,886 |
<p>It's called models.Model and not models.model (case sensitive). Fix your Poll model like this -</p>
<pre><code>class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
</code></pre>
<p>Hope that helps...</p>
| 58 |
2009-01-19T08:32:41Z
|
[
"python",
"django"
] |
AttributeError: 'module' object has no attribute 'model'
| 456,867 |
<p>Can anyone help me please to solve this..</p>
<pre><code>from django.db import models
# Create your models here.
class Poll(models.model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
</code></pre>
<p>Running:</p>
<pre><code>c:\projects\mysite>python manage.py sql polls
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Python25\Lib\site-packages\django\core\management\__init__.py", line 340, in execute_manager
utility.execute()
File "C:\Python25\Lib\site-packages\django\core\management\__init__.py", line 295, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 195, in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 221, in execute
self.validate()
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "C:\Python25\lib\site-packages\django\core\management\validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 128, in get_app_errors
self._populate()
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 57, in _populate
self.load_app(app_name, True)
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 72, in load_app
mod = __import__(app_name, {}, {}, ['models'])
File "c:\projects\mysite\..\mysite\polls\models.py", line 4, in <module>
class Poll(models.model):
AttributeError: 'module' object has no attribute 'model'
</code></pre>
| 14 |
2009-01-19T08:19:25Z
| 10,863,390 |
<p>I realized that by looking at the stack trace it was trying to load my own script in place of another module called the same way,i.e., my script was called random.py and when a module i used was trying to import the "random" package, it was loading my script causing a circular reference and so i renamed it and deleted a .pyc file it had created from the working folder and things worked just fine.</p>
| 1 |
2012-06-02T15:04:32Z
|
[
"python",
"django"
] |
AttributeError: 'module' object has no attribute 'model'
| 456,867 |
<p>Can anyone help me please to solve this..</p>
<pre><code>from django.db import models
# Create your models here.
class Poll(models.model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
</code></pre>
<p>Running:</p>
<pre><code>c:\projects\mysite>python manage.py sql polls
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Python25\Lib\site-packages\django\core\management\__init__.py", line 340, in execute_manager
utility.execute()
File "C:\Python25\Lib\site-packages\django\core\management\__init__.py", line 295, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 195, in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 221, in execute
self.validate()
File "C:\Python25\Lib\site-packages\django\core\management\base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "C:\Python25\lib\site-packages\django\core\management\validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 128, in get_app_errors
self._populate()
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 57, in _populate
self.load_app(app_name, True)
File "C:\Python25\lib\site-packages\django\db\models\loading.py", line 72, in load_app
mod = __import__(app_name, {}, {}, ['models'])
File "c:\projects\mysite\..\mysite\polls\models.py", line 4, in <module>
class Poll(models.model):
AttributeError: 'module' object has no attribute 'model'
</code></pre>
| 14 |
2009-01-19T08:19:25Z
| 20,197,595 |
<p>I also got the same error but I noticed that I had typed in Foreign*<em>k</em>*ey and not Foreign*<em>K</em>*ey,(capital K) if there is a newbie out there, check out spelling and caps. </p>
| 3 |
2013-11-25T16:04:54Z
|
[
"python",
"django"
] |
Extending python - to swig, not to swig or Cython
| 456,884 |
<p>I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance.</p>
<p>With the help of swig you almost don't need to care about arguments etc. Everything works fine.</p>
<p>Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code.</p>
<p>Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it. </p>
| 55 |
2009-01-19T08:32:06Z
| 456,894 |
<p>If its not a big extension, boost::python might also be an option, it executes faster than swig, because you control what's happening, but it'll take longer to dev.</p>
<p>Anyways swig's overhead is acceptable if the amount of work within a single call is large enough. For example if you issue is that you have some medium sized logic block you want to move to C/C++, but that block is called within a tight-loop, frequently, you might have to avoid swig, but I can't really think of any real-world examples except for scripted graphics shaders.</p>
| 3 |
2009-01-19T08:34:30Z
|
[
"python",
"c++",
"c",
"swig",
"cython"
] |
Extending python - to swig, not to swig or Cython
| 456,884 |
<p>I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance.</p>
<p>With the help of swig you almost don't need to care about arguments etc. Everything works fine.</p>
<p>Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code.</p>
<p>Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it. </p>
| 55 |
2009-01-19T08:32:06Z
| 456,949 |
<p>You should consider Boost.Python if you are not planning to generate bindings for other languages as well with swig. </p>
<p>If you have a lot of functions and classes to bind, <a href="http://sourceforge.net/projects/pygccxml/">Py++</a> is a great tool that automatically generates the needed code to make the bindings.</p>
<p><a href="http://code.google.com/p/pybindgen/">Pybindgen </a> may also be an option, but it's a new project and less complete that Boost.Python.</p>
<hr>
<p>Edit:</p>
<p>Maybe I need to be more explicit about pro and cons.</p>
<ul>
<li><p>Swig:</p>
<p>pro: you can generate bindings for many scripting languages.</p>
<p>cons: I don't like the way the parser works. I don't know if the made some progress but two years ago the C++ parser was quite limited. Most of the time I had to copy/past my .h headers add some <code>%</code> characters and give extra hints to the swig parser.</p>
<p>I was also needed to deal with the Python C-API from time to time for (not so) complicated type conversions. </p>
<p>I'm not using it anymore. </p></li>
<li><p>Boost.Python:</p>
<p>pro:
It's a very complete library. It allows you to do almost everything that is possible with the C-API, but in C++. I never had to write C-API code with this library. I also never encountered bug due to the library. Code for bindings either works like a charm or refuse compile.</p>
<p>It's probably one of the best solutions currently available if you already have some C++ library to bind. But if you only have a small C function to rewrite, I would probably try with Cython.</p>
<p>cons: if you don't have a pre-compiled Boost.Python library you're going to use Bjam (sort of make replacement). I really hate Bjam and its syntax.</p>
<p>Python libraries created with B.P tend to become obese. It also takes a <strong>lot</strong> of time to compile them.</p></li>
<li><p>Py++ (discontinued): it's Boost.Python made easy. Py++ uses a C++ parser to read your code and then generates Boost.Python code automatically. You also have a great support from its author (no it's not me ;-) ).</p>
<p>cons: only the problems due to Boost.Python itself. Update: As of 2014 this project now looks discontinued.</p></li>
<li><p>Pybindgen:</p>
<p>It generates the code dealing with the C-API. You can either describe functions and classes in a Python file, or let Pybindgen read your headers and generate bindings automatically (for this it uses pygccxml, a python library wrote by the author of Py++).</p>
<p>cons: it's a young project, with a smaller team than Boost.Python. There are still some limitations: you cannot use multiple inheritance for your C++ classes, Callbacks (not automatically, custom callback handling code can be written, though). Translation of Python exceptions to C.</p>
<p>It's definitely worth a good look.</p></li>
<li><p>A new one:
On 2009/01/20 the author of Py++ announced a <a href="http://mail.python.org/pipermail/cplusplus-sig/2009-January/014198.html">new package</a> for interfacing C/C++ code with python. It is based on ctypes. I didn't try it already but I will! Note: this project looks discontiued, as Py++.</p></li>
<li><p><a href="http://cffi.readthedocs.org/">CFFI</a>: I did not know the existence of this one until very recently so for now I cannot give my opinion. It looks like you can define C functions in Python strings and call them directly from the same Python module. </p></li>
<li><p><a href="http://cython.org/">Cython</a>: This is the method I'm currently using in my projects. Basically you write code in special .pyx files. Those files are compiled (translated) into C code which in turn are compiled to CPython modules.
Cython code can look like regular Python (and in fact pure Python are valid .pyx Cython files), but you can also more information like variable types. This optional typing allows Cython to generate faster C code. Code in Cython files can call both pure Python functions but also C and C++ functions (and also C++ methods). </p>
<p>It took me some time to think in Cython, that in the same code call C and C++ function, mix Python and C variables, and so on. But it's a very powerful language, with an active (in 2014) and friendly community.</p></li>
</ul>
| 53 |
2009-01-19T09:00:41Z
|
[
"python",
"c++",
"c",
"swig",
"cython"
] |
Extending python - to swig, not to swig or Cython
| 456,884 |
<p>I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance.</p>
<p>With the help of swig you almost don't need to care about arguments etc. Everything works fine.</p>
<p>Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code.</p>
<p>Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it. </p>
| 55 |
2009-01-19T08:32:06Z
| 456,953 |
<p>Before giving up on your python code, have a look at <a href="http://code.google.com/p/shedskin/" rel="nofollow">ShedSkin</a>. They claim better performance than Psyco on some code (and also state that it is still experimental).</p>
<p>Else, there are several choices for binding C/C++ code to python.</p>
<p>Boost is lengthy to compile but is really the most flexible and easy to use solution.</p>
<p>I have never used SWIG but compared to boost, it's not as flexible as it's generic binding framework, not a framework dedicated to python.</p>
<p>Next choice is <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">Pyrex</a>. It allows to write pseudo python code that gets compiled as a C extension.</p>
| 3 |
2009-01-19T09:02:57Z
|
[
"python",
"c++",
"c",
"swig",
"cython"
] |
Extending python - to swig, not to swig or Cython
| 456,884 |
<p>I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance.</p>
<p>With the help of swig you almost don't need to care about arguments etc. Everything works fine.</p>
<p>Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code.</p>
<p>Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it. </p>
| 55 |
2009-01-19T08:32:06Z
| 456,995 |
<p>For sure you will always have a performance gain doing this by hand, but the gain will be very small compared to the effort required to do this. I don't have any figure to give you but I don't recommend this, because you will need to maintain the interface by hand, and this is not an option if your module is large!</p>
<p>You did the right thing to chose to use a scripting language because you wanted rapid development. This way you've avoided the early optimization syndrome, and now you want to optimize bottleneck parts, great! But if you do the C/python interface by hand you will fall in the early optimization syndrome for sure.</p>
<p>If you want something with less interface code, you can think about creating a dll from your C code, and use that library directly from python with <a href="http://python.net/crew/theller/ctypes/">cstruct</a>.</p>
<p>Consider also <a href="http://www.cython.org/">Cython</a> if you want to use only python code in your program.</p>
| 23 |
2009-01-19T09:20:19Z
|
[
"python",
"c++",
"c",
"swig",
"cython"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.