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
keyerror inside django model class __init__
866,399
<p>Here's a Django model class I wrote. This class gets a keyerror when I call <code>get_object_or_404</code> from Django (I conceive that keyerror is raised due to no kwargs being passed to <code>__init__</code> by the get function, arguments are all positional). Interestingly, it does not get an error when I call <code>get_object_or_404</code> from console.</p> <p>I wonder why, and if the below code is the correct way (ie, using <strong>init</strong> to populate the link field) to construct this class.</p> <pre><code>class Link(models.Model) event_type = models.IntegerField(choices=EVENT_TYPES) user = models.ForeignKey(User) created_on = models.DateTimeField(auto_now_add = True) link = models.CharField(max_length=30) isActive = models.BooleanField(default=True) def _generate_link(self): prelink = str(self.user.id)+str(self.event_type)+str(self.created_on) m = md5.new() m.update(prelink) return m.hexdigest() def __init__(self, *args, **kwargs): self.user = kwargs['user'].pop() self.event_type = kwargs['event_type'].pop() self.link = self._generate_link() super(Link,self).__init__(*args,**kwargs) </code></pre>
1
2009-05-14T23:35:13Z
866,456
<pre><code>self.user = kwargs['user'].pop() self.event_type = kwargs['event_type'].pop() </code></pre> <p>You're trying to retrieve an entry from the dictionary, and then call its pop method. If you want to remove and return an object from a dictionary, call <code>dict.pop()</code>:</p> <pre><code>self.user = kwargs.pop('user') </code></pre> <p>Of course, this will fail with a <code>KeyError</code> when <code>"user"</code> is not present in <code>kwargs</code>. You'll want to provide a default value to pop:</p> <pre><code>self.user = kwargs.pop('user', None) </code></pre> <p>This means "if <code>"user"</code> is in the dictionary, remove and return it. Otherwise, return <code>None</code>".</p> <p>Regarding the other two lines:</p> <pre><code>self.link = self._generate_link() super(Link,self).__init__(*args,**kwargs) </code></pre> <p><code>super().__init__()</code> will set <code>link</code> to something, probably <code>None</code>. I would reverse the lines, to something like this:</p> <pre><code>super(Link,self).__init__(*args,**kwargs) self.link = self._generate_link() </code></pre> <p>You might want to add a test before setting the link, to see if it already exists (<code>if self.link is not None: ...</code>). That way, links you pass into the constructor won't be overwritten.</p>
7
2009-05-14T23:58:34Z
[ "python", "django", "django-models" ]
keyerror inside django model class __init__
866,399
<p>Here's a Django model class I wrote. This class gets a keyerror when I call <code>get_object_or_404</code> from Django (I conceive that keyerror is raised due to no kwargs being passed to <code>__init__</code> by the get function, arguments are all positional). Interestingly, it does not get an error when I call <code>get_object_or_404</code> from console.</p> <p>I wonder why, and if the below code is the correct way (ie, using <strong>init</strong> to populate the link field) to construct this class.</p> <pre><code>class Link(models.Model) event_type = models.IntegerField(choices=EVENT_TYPES) user = models.ForeignKey(User) created_on = models.DateTimeField(auto_now_add = True) link = models.CharField(max_length=30) isActive = models.BooleanField(default=True) def _generate_link(self): prelink = str(self.user.id)+str(self.event_type)+str(self.created_on) m = md5.new() m.update(prelink) return m.hexdigest() def __init__(self, *args, **kwargs): self.user = kwargs['user'].pop() self.event_type = kwargs['event_type'].pop() self.link = self._generate_link() super(Link,self).__init__(*args,**kwargs) </code></pre>
1
2009-05-14T23:35:13Z
866,662
<p>There's no reason to write your own <code>__init__</code> for Django model classes. I think you'll be a lot happier without it. </p> <p>Almost anything you think you want to do in <code>__init__</code> can be better done in <code>save</code>.</p>
2
2009-05-15T01:31:40Z
[ "python", "django", "django-models" ]
keyerror inside django model class __init__
866,399
<p>Here's a Django model class I wrote. This class gets a keyerror when I call <code>get_object_or_404</code> from Django (I conceive that keyerror is raised due to no kwargs being passed to <code>__init__</code> by the get function, arguments are all positional). Interestingly, it does not get an error when I call <code>get_object_or_404</code> from console.</p> <p>I wonder why, and if the below code is the correct way (ie, using <strong>init</strong> to populate the link field) to construct this class.</p> <pre><code>class Link(models.Model) event_type = models.IntegerField(choices=EVENT_TYPES) user = models.ForeignKey(User) created_on = models.DateTimeField(auto_now_add = True) link = models.CharField(max_length=30) isActive = models.BooleanField(default=True) def _generate_link(self): prelink = str(self.user.id)+str(self.event_type)+str(self.created_on) m = md5.new() m.update(prelink) return m.hexdigest() def __init__(self, *args, **kwargs): self.user = kwargs['user'].pop() self.event_type = kwargs['event_type'].pop() self.link = self._generate_link() super(Link,self).__init__(*args,**kwargs) </code></pre>
1
2009-05-14T23:35:13Z
866,665
<blockquote> <p>wonder why, and if the below code is the correct way (ie, using <code>__init__</code> to populate the link field) to construct this class.</p> </blockquote> <p>I once got some problems when I tried to overload <code>__init__</code> In the maillist i got this answer</p> <blockquote> <p>It's best not to overload it with your own <code>__init__</code>. A better option is to hook into the <code>post_init</code> signal with a custom method and in that method do your <code>process()</code> and <code>make_thumbnail()</code> calls.</p> </blockquote> <p>In your case the post_init-signal should do the trick and implementing <code>__init__</code> shouldn't be necessary at all. You could write something like this:</p> <pre><code>class Link(models.Model) event_type = models.IntegerField(choices=EVENT_TYPES) user = models.ForeignKey(User) created_on = models.DateTimeField(auto_now_add = True) link = models.CharField(max_length=30) isActive = models.BooleanField(default=True) def create_link(self): prelink = str(self.user.id)+str(self.event_type)+str(self.created_on) m = md5.new() m.update(prelink) return m.hexdigest() def post_link_init(sender, **kwargs): kwargs['instance'].create_link() post_init.connect(post_link_init, sender=Link) &gt;&gt;&gt; link = Link(event_type=1, user=aUser, created_on=datetime.now(), link='foo', isActive=True) </code></pre> <p>providing keyword <code>unique</code> for <code>link = models.CharField(max_length=30, unique=True)</code> could be helpful, too. If it is not provided, get_object_or_404 may won't work in case the same value in the link-field exists several times.</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow">signals</a> and <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#unique" rel="nofollow">unique</a> in the django-docs </p>
1
2009-05-15T01:35:20Z
[ "python", "django", "django-models" ]
keyerror inside django model class __init__
866,399
<p>Here's a Django model class I wrote. This class gets a keyerror when I call <code>get_object_or_404</code> from Django (I conceive that keyerror is raised due to no kwargs being passed to <code>__init__</code> by the get function, arguments are all positional). Interestingly, it does not get an error when I call <code>get_object_or_404</code> from console.</p> <p>I wonder why, and if the below code is the correct way (ie, using <strong>init</strong> to populate the link field) to construct this class.</p> <pre><code>class Link(models.Model) event_type = models.IntegerField(choices=EVENT_TYPES) user = models.ForeignKey(User) created_on = models.DateTimeField(auto_now_add = True) link = models.CharField(max_length=30) isActive = models.BooleanField(default=True) def _generate_link(self): prelink = str(self.user.id)+str(self.event_type)+str(self.created_on) m = md5.new() m.update(prelink) return m.hexdigest() def __init__(self, *args, **kwargs): self.user = kwargs['user'].pop() self.event_type = kwargs['event_type'].pop() self.link = self._generate_link() super(Link,self).__init__(*args,**kwargs) </code></pre>
1
2009-05-14T23:35:13Z
867,254
<p>I don't think you need the <code>__init__</code> here at all. </p> <p>You are always calculating the value of link when the class is instantiated. This means you ignore whatever is stored in the database. Since this is the case, why bother with a model field at all? You would be better making link a property, with the getter using the code from <code>_generate_link</code>.</p> <pre><code>@property def link(self): .... </code></pre>
2
2009-05-15T06:29:39Z
[ "python", "django", "django-models" ]
In Django, how can you change the User class to work with a different db table?
866,418
<p>We're running django alongside - and sharing a database with - an existing application. And we want to use an existing "user" table (not Django's own) to store user information. </p> <p>It looks like it's possible to change the name of the table that Django uses, in the Meta class of the User definition. </p> <p>But we'd prefer not to change the Django core itself.</p> <p>So we were thinking that we could sub-class the core auth.User class like this :</p> <pre><code>class OurUser(User) : objects = UserManager() class Meta: db_table = u'our_user_table' </code></pre> <p>Here, the aim is not to add any extra fields to the customized User class. But just to use the alternative table. </p> <p>However, this fails (likely because the ORM is assuming that the our_user_table should have a foreign key referring back to the original User table, which it doesn't).</p> <p>So, is this sensible way to do what we want to do? Have I missed out on some easier way to map classes onto tables? Or, if not, can this be made to work?</p> <p>Update : </p> <p>I think I might be able to make the change I want just by "monkey-patching" the _meta of User in a local_settings.py</p> <pre><code>User._meta.db_table = 'our_user_table' </code></pre> <p>Can anyone think of anything bad that could happen if I do this? (Particularly in the context of a fairly typical Django / Pinax application?)</p>
1
2009-05-14T23:41:46Z
866,434
<p>You might find it useful to set up your old table as an <a href="http://docs.djangoproject.com/en/dev/topics/auth/#other-authentication-sources" rel="nofollow">alternative authentication source</a> and sidestep all these issues. </p> <p>Another option is to <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users" rel="nofollow">subclass the user</a> and have the subclass point to your user-model. Override the save function to ensure that everything you need to do to preserve your old functionality is there.</p> <p>I haven't done either of these myself but hopefully they are useful pointers.</p> <p><strong>Update</strong> What I mean by alternative authentication in this case is a small python script that says "Yes, this is a valid username / password" - It then creates an instance of model in the standard Django table, copies fields across from the legacy table and returns the new user to the caller. </p> <p>If you need to keep the two tables in sync, you could decide to have your alternative authentication never create a standard django user and just say "Yes, this is a valid password and username"</p>
6
2009-05-14T23:50:16Z
[ "python", "django", "django-models", "monkeypatching" ]
Creating a new terminal/shell window to simply display text
866,737
<p>I want to pipe [edit: real-time text] the output of several subprocesses (sometimes chained, sometimes parallel) to a single terminal/tty window that is not the active python shell (be it an IDE, command-line, or a running script using tkinter). IPython is not an option. I need something that comes with the standard install. Prefer OS-agnostic solution, but needs to work on XP/Vista. </p> <p>I'll post what I've tried already if you want it, but it’s embarrassing.</p>
1
2009-05-15T02:16:21Z
866,750
<p>You say "pipe" so I assume you're dealing with text output from the subprocesses. A simple solution may be to just write output to files?</p> <p>e.g. in the subprocess:</p> <ol> <li>Redirect output <code>%TEMP%\output.txt</code></li> <li>On exit, copy <code>output.txt</code> to a directory your main process is watching.</li> </ol> <p>In the main process:</p> <ol> <li>Every second, examine directory for new files.</li> <li>When files found, process and remove them.</li> </ol> <p>You could encode the subprocess name in the output filename so you know how to process it.</p>
0
2009-05-15T02:27:00Z
[ "python", "shell" ]
Creating a new terminal/shell window to simply display text
866,737
<p>I want to pipe [edit: real-time text] the output of several subprocesses (sometimes chained, sometimes parallel) to a single terminal/tty window that is not the active python shell (be it an IDE, command-line, or a running script using tkinter). IPython is not an option. I need something that comes with the standard install. Prefer OS-agnostic solution, but needs to work on XP/Vista. </p> <p>I'll post what I've tried already if you want it, but it’s embarrassing.</p>
1
2009-05-15T02:16:21Z
866,805
<p>A good solution in Unix would be named pipes. I know you asked about Windows, but there might be a similar approach in Windows, or this might be helpful for someone else.</p> <p>on terminal 1:</p> <pre><code>mkfifo /tmp/display_data myapp &gt;&gt; /tmp/display_data </code></pre> <p>on terminal 2 (bash):</p> <pre><code>tail -f /tmp/display_data </code></pre> <p><strong>Edit</strong>: <em>changed terminal 2 command to use "tail -f" instead of infinite loop.</em></p>
2
2009-05-15T03:01:20Z
[ "python", "shell" ]
Creating a new terminal/shell window to simply display text
866,737
<p>I want to pipe [edit: real-time text] the output of several subprocesses (sometimes chained, sometimes parallel) to a single terminal/tty window that is not the active python shell (be it an IDE, command-line, or a running script using tkinter). IPython is not an option. I need something that comes with the standard install. Prefer OS-agnostic solution, but needs to work on XP/Vista. </p> <p>I'll post what I've tried already if you want it, but it’s embarrassing.</p>
1
2009-05-15T02:16:21Z
872,075
<p>You could make a producer-customer system, where lines are inserted over a socket (nothing fancy here). The customer would be a multithreaded socket server listening to connections and putting all lines into a <strong><a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue</a></strong>. In the separate thread it would get items from the queue and print it on the console. The program can be run from the cmd console or from the eclipse console as an external tool without much trouble.</p> <p>From your point of view, it should be realtime. As a bonus, You can place producers and customers on separate boxes. Producers can even form a network.</p> <p>Some Examples of socket programming with python can be found <a href="http://docs.python.org/library/socket.html#example" rel="nofollow">here</a>. Look <a href="http://ilab.cs.byu.edu/python/socket/echoserver.html" rel="nofollow">here</a> for an tcp echoserver example and <a href="http://floppsie.comp.glam.ac.uk/Glamorgan/gaius/wireless/5.html" rel="nofollow">here</a> for a tcp "hello world" socket client.</p> <p>There also is an extension for windows that enables usage of named pipes.</p> <p>On linux (possibly cygwin?) You could just <em>tail -f named-fifo</em>.</p> <p>Good luck!</p>
0
2009-05-16T09:40:15Z
[ "python", "shell" ]
Can I segment a document in BeautifulSoup before converting it to text based on my analysis of the document?
866,772
<p>I have some html files that I want to convert to text. I have played around with BeautifulSoup and made some progress on understanding how to use the instructions and can submit html and get back text. </p> <p>However, my files have a lot of text that is formatted using table structures. For example I might have a paragraph of text that resides in a td tag within set of table tags</p> <pre><code>&lt;table&gt; &lt;td&gt; here is some really useful information and there might be other markup tags but this information is really textual in my eyes-I want to preserve it &lt;/td&gt; &lt;/table&gt; </code></pre> <p>And then there are the 'classic tables' that have data within the body of the table.</p> <p>I want to be able to apply an algorithm to the table and set some rules that determine whether the table is ripped out before I convert the document to text.</p> <p>I have figured out how to get the characteristics of my tables- for example to get the number of cols in each table:</p> <pre><code>numbCols=[] for table in soup.findAll('table'): rows=[] for row in table.findAll('tr'): columns=0 for column in row.findAll('td'): columns+=1 rows.append(columns) numbCols.append(rows) </code></pre> <p>so I can operate on numbCols and use the len of each item in the list and the values in each item in the list to analyze the characteristics of my tables and identify the ones I want to keep or discard. </p> <p>I am not seeing an elegant way to the use this information with BeautifulSoup to get the text. I guess what I am trying to get at is suppose I analyze numbCols and decide that of the ten tables in a particular document I want to exclude tables 2, 4, 6, &amp; 9. So the part of the html document includes everything but those tables. How can I segment my soup that way? </p> <p>The solution I have come up with is first identify the position of each of the open and close table tags using finditer and getting the spans and then zipping the spans with the numbCols. I can then use this list to snip and join the pieces of my string together. Once this is finished I can then use BeautifulSoup to convert the html to text.</p> <p>I feel sure that I should be able to do all of this in BeautifulSoup. Any suggestions or links to existing examples would be great. I should mention that my source files can be large and I have thousands to handle.</p> <p>Didn't have the answer but I am getting closer</p>
0
2009-05-15T02:40:42Z
871,736
<p>Man I love this stuff Assuming in a naive case that I want to delete all of the tables that have any rows with a column length greater than 3 My answer is </p> <pre><code>for table in soup.findAll('table'): rows=[] for row in table.findAll('tr'): columns=0 for column in row.findAll('td'): columns+=1 rows.append(columns) if max(rows)&gt;3: table.delete() </code></pre> <p>You can do any processing you want at any level in that loop, it is only necessary to identify the test and get the right instance to test.</p>
0
2009-05-16T05:00:33Z
[ "python", "beautifulsoup" ]
python instance variables as optional arguments
867,115
<p>In python, is there a way I can use instance variables as optional arguments in a class method? ie:</p> <pre><code>def function(self, arg1=val1, arg2=val2, arg3=self.instance_var): # do stuff.... </code></pre> <p>Any help would be appreciated.</p>
7
2009-05-15T05:40:57Z
867,124
<p>Try this:</p> <pre><code>def foo(self, blah=None): if blah is None: # faster than blah == None - thanks to kcwu blah = self.instance_var </code></pre>
14
2009-05-15T05:45:31Z
[ "python", "function", "class" ]
python instance variables as optional arguments
867,115
<p>In python, is there a way I can use instance variables as optional arguments in a class method? ie:</p> <pre><code>def function(self, arg1=val1, arg2=val2, arg3=self.instance_var): # do stuff.... </code></pre> <p>Any help would be appreciated.</p>
7
2009-05-15T05:40:57Z
867,129
<p>no, because the instance doesn't exist when class function definition time</p> <p>You have to rewrite as following</p> <pre><code>def function(self, arg1=val1, arg2=val2, arg3=None): if arg3 is None: arg3 = self.instance_var </code></pre> <p>This is slightly different to original one: you cannot pass arg3 with None value if you really want.</p> <p>Alternative solution:</p> <pre><code>def function(self, arg1=val1, arg2=val2, **argd): arg3 = argd.get('arg3', self.instance_var) </code></pre>
2
2009-05-15T05:47:33Z
[ "python", "function", "class" ]
python instance variables as optional arguments
867,115
<p>In python, is there a way I can use instance variables as optional arguments in a class method? ie:</p> <pre><code>def function(self, arg1=val1, arg2=val2, arg3=self.instance_var): # do stuff.... </code></pre> <p>Any help would be appreciated.</p>
7
2009-05-15T05:40:57Z
867,146
<p>An alternative way of doing this would be:</p> <pre><code>def foo(self, blah=None): blah = blah or self.instance_var </code></pre> <p>This shorter version looks better, specially when there is more than one optional argument.</p> <p><strong>Use with care. See the comments below...</strong></p>
-1
2009-05-15T05:53:02Z
[ "python", "function", "class" ]
python instance variables as optional arguments
867,115
<p>In python, is there a way I can use instance variables as optional arguments in a class method? ie:</p> <pre><code>def function(self, arg1=val1, arg2=val2, arg3=self.instance_var): # do stuff.... </code></pre> <p>Any help would be appreciated.</p>
7
2009-05-15T05:40:57Z
867,458
<p>All the responses suggesting <code>None</code> are correct; if you want to make sure a caller can pass None as a regular argument, use a special <code>sentinel</code> and test with <code>is</code>:</p> <pre><code>class Foo(object): __default = object() def foo(self, blah=Foo.__default): if blah is Foo.__default: blah = self.instavar </code></pre> <p>Each call to <code>object()</code> makes a unique object, such that <code>is</code> will never succeed between it and any other value. The two underscores in <code>__default</code> mean "strongly private", meaning that callers know they shouldn't try to mess with it (and would need quite some work to do so, explicitly imitating the name mangling that the compiler is doing).</p> <p>The reason you can't just use the code you posted, btw, is that default values evaluate when the <code>def</code> statement evaluates, not later at call time; and at the time <code>def</code> evaluates, there is as yet no <code>self</code> from which to take the instance variable.</p>
5
2009-05-15T07:51:18Z
[ "python", "function", "class" ]
python instance variables as optional arguments
867,115
<p>In python, is there a way I can use instance variables as optional arguments in a class method? ie:</p> <pre><code>def function(self, arg1=val1, arg2=val2, arg3=self.instance_var): # do stuff.... </code></pre> <p>Any help would be appreciated.</p>
7
2009-05-15T05:40:57Z
2,142,400
<pre><code>def foo(self, blah=None): blah = blah if not blah is None else self.instance_var </code></pre> <p>This works with python 2.5 and forwards and handles the cases where blah is empty strings, lists and so on.</p>
0
2010-01-26T20:27:45Z
[ "python", "function", "class" ]
db connection in python
867,175
<p>I am writing a code in python in which I established a connection with database.I have queries in a loop.While queries being executed in the loop ,If i unplug the network cable it should stop with an exception.But this not happens ,When i again plug yhe network cabe after 2 minutes it starts again from where it ended.I am using linux and psycopg2.It is not showing exception</p> <p><strong>Need help urgent.</strong></p>
0
2009-05-15T06:03:32Z
867,202
<p>Your database connection will almost certainly be based on a TCP socket. TCP sockets will hang around for a long time retrying before failing and (in python) raising an exception. Not to mention and retries/automatic reconnection attempts in the database layer.</p>
2
2009-05-15T06:11:53Z
[ "python", "tcp", "database-connection" ]
db connection in python
867,175
<p>I am writing a code in python in which I established a connection with database.I have queries in a loop.While queries being executed in the loop ,If i unplug the network cable it should stop with an exception.But this not happens ,When i again plug yhe network cabe after 2 minutes it starts again from where it ended.I am using linux and psycopg2.It is not showing exception</p> <p><strong>Need help urgent.</strong></p>
0
2009-05-15T06:03:32Z
867,222
<p>As Douglas's answer said, it won't raise exception due to TCP.</p> <p>You may try to use socket.setdefaulttimeout() to set a shorter timeout value.</p> <blockquote> <p>setdefaulttimeout(...)</p> <pre><code> setdefaulttimeout(timeout) Set the default timeout in floating seconds for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None. </code></pre> </blockquote> <p>However, it may not work if your database connection is not build by python socket, for example, native socket.</p>
2
2009-05-15T06:18:49Z
[ "python", "tcp", "database-connection" ]
db connection in python
867,175
<p>I am writing a code in python in which I established a connection with database.I have queries in a loop.While queries being executed in the loop ,If i unplug the network cable it should stop with an exception.But this not happens ,When i again plug yhe network cabe after 2 minutes it starts again from where it ended.I am using linux and psycopg2.It is not showing exception</p> <p><strong>Need help urgent.</strong></p>
0
2009-05-15T06:03:32Z
867,433
<p>If you want to implement timeouts that work no matter how the client library is connecting to the server, it's best to attempt the DB operations in a separate thread, or, better, a separate process, which a "monitor" thread/process can kill if needed; see the multiprocessing module in Python 2.6 standard library (there's a backported version for 2.5 if you need that). A process is better because when it's killed the operating system will take care of deallocating and cleaning up resources, while killing a thread is always a pretty unsafe and messy business.</p>
1
2009-05-15T07:43:58Z
[ "python", "tcp", "database-connection" ]
Python Class Members Initialization
867,219
<p>I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...</p> <p>The scenario: I have a class called A, that has a dictionary data member, following is its code (this is simplification of course):</p> <pre><code>class A: dict1={} def add_stuff_to_1(self, k, v): self.dict1[k]=v def print_stuff(self): print(self.dict1) </code></pre> <p>The class using this code is class B:</p> <pre><code>class B: def do_something_with_a1(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('a', 1) a_instance.add_stuff_to_1('b', 2) a_instance.print_stuff() def do_something_with_a2(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('c', 1) a_instance.add_stuff_to_1('d', 2) a_instance.print_stuff() def do_something_with_a3(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('e', 1) a_instance.add_stuff_to_1('f', 2) a_instance.print_stuff() def __init__(self): self.do_something_with_a1() print("---") self.do_something_with_a2() print("---") self.do_something_with_a3() </code></pre> <p>Notice that every call to <code>do_something_with_aX()</code> initializes a new "clean" instance of class A, and prints the dictionary before and after the addition.</p> <p>The bug (in case you haven't figured it out yet):</p> <pre><code>&gt;&gt;&gt; b_instance = B() {} {'a': 1, 'b': 2} --- {'a': 1, 'b': 2} {'a': 1, 'c': 1, 'b': 2, 'd': 2} --- {'a': 1, 'c': 1, 'b': 2, 'd': 2} {'a': 1, 'c': 1, 'b': 2, 'e': 1, 'd': 2, 'f': 2} </code></pre> <p>In the second initialization of class A, the dictionaries are not empty, but start with the contents of the last initialization, and so forth. I expected them to start "fresh".</p> <p>What solves this "bug" is obviously adding:</p> <pre><code>self.dict1 = {} </code></pre> <p>In the <code>__init__</code> constructor of class A. However, that made me wonder:</p> <ol> <li>What is the meaning of the "dict1 = {}" initialization at the point of dict1's declaration (first line in class A)? It is meaningless?</li> <li>What's the mechanism of instantiation that causes copying the reference from the last initialization? </li> <li>If I add "self.dict1 = {}" in the constructor (or any other data member), how does it not affect the dictionary member of previously initialized instances?</li> </ol> <p><hr /></p> <p>EDIT: Following the answers I now understand that by declaring a data member and not referring to it in the <code>__init__</code> or somewhere else as self.dict1, I'm practically defining what's called in C++/Java a static data member. By calling it self.dict1 I'm making it "instance-bound".</p>
33
2009-05-15T06:17:50Z
867,226
<p>What you keep referring to as a bug is the <a href="http://docs.python.org/tutorial/classes.html">documented</a>, standard behavior of Python classes.</p> <p>Declaring a dict outside of <code>__init__</code> as you initially did is declaring a class-level variable. It is only created once at first, whenever you create new objects it will reuse this same dict. To create instance variables, you declare them with <code>self</code> in <code>__init__</code>; its as simple as that.</p>
47
2009-05-15T06:19:29Z
[ "python", "class", "initialization" ]
Python Class Members Initialization
867,219
<p>I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...</p> <p>The scenario: I have a class called A, that has a dictionary data member, following is its code (this is simplification of course):</p> <pre><code>class A: dict1={} def add_stuff_to_1(self, k, v): self.dict1[k]=v def print_stuff(self): print(self.dict1) </code></pre> <p>The class using this code is class B:</p> <pre><code>class B: def do_something_with_a1(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('a', 1) a_instance.add_stuff_to_1('b', 2) a_instance.print_stuff() def do_something_with_a2(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('c', 1) a_instance.add_stuff_to_1('d', 2) a_instance.print_stuff() def do_something_with_a3(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('e', 1) a_instance.add_stuff_to_1('f', 2) a_instance.print_stuff() def __init__(self): self.do_something_with_a1() print("---") self.do_something_with_a2() print("---") self.do_something_with_a3() </code></pre> <p>Notice that every call to <code>do_something_with_aX()</code> initializes a new "clean" instance of class A, and prints the dictionary before and after the addition.</p> <p>The bug (in case you haven't figured it out yet):</p> <pre><code>&gt;&gt;&gt; b_instance = B() {} {'a': 1, 'b': 2} --- {'a': 1, 'b': 2} {'a': 1, 'c': 1, 'b': 2, 'd': 2} --- {'a': 1, 'c': 1, 'b': 2, 'd': 2} {'a': 1, 'c': 1, 'b': 2, 'e': 1, 'd': 2, 'f': 2} </code></pre> <p>In the second initialization of class A, the dictionaries are not empty, but start with the contents of the last initialization, and so forth. I expected them to start "fresh".</p> <p>What solves this "bug" is obviously adding:</p> <pre><code>self.dict1 = {} </code></pre> <p>In the <code>__init__</code> constructor of class A. However, that made me wonder:</p> <ol> <li>What is the meaning of the "dict1 = {}" initialization at the point of dict1's declaration (first line in class A)? It is meaningless?</li> <li>What's the mechanism of instantiation that causes copying the reference from the last initialization? </li> <li>If I add "self.dict1 = {}" in the constructor (or any other data member), how does it not affect the dictionary member of previously initialized instances?</li> </ol> <p><hr /></p> <p>EDIT: Following the answers I now understand that by declaring a data member and not referring to it in the <code>__init__</code> or somewhere else as self.dict1, I'm practically defining what's called in C++/Java a static data member. By calling it self.dict1 I'm making it "instance-bound".</p>
33
2009-05-15T06:17:50Z
867,239
<p>When you access attribute of instance, say, self.foo, python will first find 'foo' in <code>self.__dict__</code>. If not found, python will find 'foo' in <code>TheClass.__dict__</code></p> <p>In your case, <code>dict1</code> is of class A, not instance. </p>
1
2009-05-15T06:23:12Z
[ "python", "class", "initialization" ]
Python Class Members Initialization
867,219
<p>I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...</p> <p>The scenario: I have a class called A, that has a dictionary data member, following is its code (this is simplification of course):</p> <pre><code>class A: dict1={} def add_stuff_to_1(self, k, v): self.dict1[k]=v def print_stuff(self): print(self.dict1) </code></pre> <p>The class using this code is class B:</p> <pre><code>class B: def do_something_with_a1(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('a', 1) a_instance.add_stuff_to_1('b', 2) a_instance.print_stuff() def do_something_with_a2(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('c', 1) a_instance.add_stuff_to_1('d', 2) a_instance.print_stuff() def do_something_with_a3(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('e', 1) a_instance.add_stuff_to_1('f', 2) a_instance.print_stuff() def __init__(self): self.do_something_with_a1() print("---") self.do_something_with_a2() print("---") self.do_something_with_a3() </code></pre> <p>Notice that every call to <code>do_something_with_aX()</code> initializes a new "clean" instance of class A, and prints the dictionary before and after the addition.</p> <p>The bug (in case you haven't figured it out yet):</p> <pre><code>&gt;&gt;&gt; b_instance = B() {} {'a': 1, 'b': 2} --- {'a': 1, 'b': 2} {'a': 1, 'c': 1, 'b': 2, 'd': 2} --- {'a': 1, 'c': 1, 'b': 2, 'd': 2} {'a': 1, 'c': 1, 'b': 2, 'e': 1, 'd': 2, 'f': 2} </code></pre> <p>In the second initialization of class A, the dictionaries are not empty, but start with the contents of the last initialization, and so forth. I expected them to start "fresh".</p> <p>What solves this "bug" is obviously adding:</p> <pre><code>self.dict1 = {} </code></pre> <p>In the <code>__init__</code> constructor of class A. However, that made me wonder:</p> <ol> <li>What is the meaning of the "dict1 = {}" initialization at the point of dict1's declaration (first line in class A)? It is meaningless?</li> <li>What's the mechanism of instantiation that causes copying the reference from the last initialization? </li> <li>If I add "self.dict1 = {}" in the constructor (or any other data member), how does it not affect the dictionary member of previously initialized instances?</li> </ol> <p><hr /></p> <p>EDIT: Following the answers I now understand that by declaring a data member and not referring to it in the <code>__init__</code> or somewhere else as self.dict1, I'm practically defining what's called in C++/Java a static data member. By calling it self.dict1 I'm making it "instance-bound".</p>
33
2009-05-15T06:17:50Z
867,248
<p>Pythons class declarations are executed as a code block and any local variable definitions (of which function definitions are a special kind of) are stored in the constructed class instance. Due to the way attribute look up works in Python, if an attribute is not found on the instance the value on the class is used.</p> <p>The is <a href="http://python-history.blogspot.com/2009/02/adding-support-for-user-defined-classes.html" rel="nofollow">an interesting article about the class syntax</a> on the history of Python blog.</p>
0
2009-05-15T06:27:39Z
[ "python", "class", "initialization" ]
Python Class Members Initialization
867,219
<p>I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...</p> <p>The scenario: I have a class called A, that has a dictionary data member, following is its code (this is simplification of course):</p> <pre><code>class A: dict1={} def add_stuff_to_1(self, k, v): self.dict1[k]=v def print_stuff(self): print(self.dict1) </code></pre> <p>The class using this code is class B:</p> <pre><code>class B: def do_something_with_a1(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('a', 1) a_instance.add_stuff_to_1('b', 2) a_instance.print_stuff() def do_something_with_a2(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('c', 1) a_instance.add_stuff_to_1('d', 2) a_instance.print_stuff() def do_something_with_a3(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('e', 1) a_instance.add_stuff_to_1('f', 2) a_instance.print_stuff() def __init__(self): self.do_something_with_a1() print("---") self.do_something_with_a2() print("---") self.do_something_with_a3() </code></pre> <p>Notice that every call to <code>do_something_with_aX()</code> initializes a new "clean" instance of class A, and prints the dictionary before and after the addition.</p> <p>The bug (in case you haven't figured it out yet):</p> <pre><code>&gt;&gt;&gt; b_instance = B() {} {'a': 1, 'b': 2} --- {'a': 1, 'b': 2} {'a': 1, 'c': 1, 'b': 2, 'd': 2} --- {'a': 1, 'c': 1, 'b': 2, 'd': 2} {'a': 1, 'c': 1, 'b': 2, 'e': 1, 'd': 2, 'f': 2} </code></pre> <p>In the second initialization of class A, the dictionaries are not empty, but start with the contents of the last initialization, and so forth. I expected them to start "fresh".</p> <p>What solves this "bug" is obviously adding:</p> <pre><code>self.dict1 = {} </code></pre> <p>In the <code>__init__</code> constructor of class A. However, that made me wonder:</p> <ol> <li>What is the meaning of the "dict1 = {}" initialization at the point of dict1's declaration (first line in class A)? It is meaningless?</li> <li>What's the mechanism of instantiation that causes copying the reference from the last initialization? </li> <li>If I add "self.dict1 = {}" in the constructor (or any other data member), how does it not affect the dictionary member of previously initialized instances?</li> </ol> <p><hr /></p> <p>EDIT: Following the answers I now understand that by declaring a data member and not referring to it in the <code>__init__</code> or somewhere else as self.dict1, I'm practically defining what's called in C++/Java a static data member. By calling it self.dict1 I'm making it "instance-bound".</p>
33
2009-05-15T06:17:50Z
867,348
<p>If this is your code:</p> <pre><code>class ClassA: dict1 = {} a = ClassA() </code></pre> <p>Then you probably expected this to happen inside Python:</p> <pre><code>class ClassA: __defaults__['dict1'] = {} a = instance(ClassA) # a bit of pseudo-code here: for name, value in ClassA.__defaults__: a.&lt;name&gt; = value </code></pre> <p>As far as I can tell, that <em>is</em> what happens, except that a <code>dict</code> has its pointer copied, instead of the value, which is the default behaviour everywhere in Python. Look at this code:</p> <pre><code>a = {} b = a a['foo'] = 'bar' print b </code></pre>
0
2009-05-15T07:06:18Z
[ "python", "class", "initialization" ]
Python Class Members Initialization
867,219
<p>I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...</p> <p>The scenario: I have a class called A, that has a dictionary data member, following is its code (this is simplification of course):</p> <pre><code>class A: dict1={} def add_stuff_to_1(self, k, v): self.dict1[k]=v def print_stuff(self): print(self.dict1) </code></pre> <p>The class using this code is class B:</p> <pre><code>class B: def do_something_with_a1(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('a', 1) a_instance.add_stuff_to_1('b', 2) a_instance.print_stuff() def do_something_with_a2(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('c', 1) a_instance.add_stuff_to_1('d', 2) a_instance.print_stuff() def do_something_with_a3(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('e', 1) a_instance.add_stuff_to_1('f', 2) a_instance.print_stuff() def __init__(self): self.do_something_with_a1() print("---") self.do_something_with_a2() print("---") self.do_something_with_a3() </code></pre> <p>Notice that every call to <code>do_something_with_aX()</code> initializes a new "clean" instance of class A, and prints the dictionary before and after the addition.</p> <p>The bug (in case you haven't figured it out yet):</p> <pre><code>&gt;&gt;&gt; b_instance = B() {} {'a': 1, 'b': 2} --- {'a': 1, 'b': 2} {'a': 1, 'c': 1, 'b': 2, 'd': 2} --- {'a': 1, 'c': 1, 'b': 2, 'd': 2} {'a': 1, 'c': 1, 'b': 2, 'e': 1, 'd': 2, 'f': 2} </code></pre> <p>In the second initialization of class A, the dictionaries are not empty, but start with the contents of the last initialization, and so forth. I expected them to start "fresh".</p> <p>What solves this "bug" is obviously adding:</p> <pre><code>self.dict1 = {} </code></pre> <p>In the <code>__init__</code> constructor of class A. However, that made me wonder:</p> <ol> <li>What is the meaning of the "dict1 = {}" initialization at the point of dict1's declaration (first line in class A)? It is meaningless?</li> <li>What's the mechanism of instantiation that causes copying the reference from the last initialization? </li> <li>If I add "self.dict1 = {}" in the constructor (or any other data member), how does it not affect the dictionary member of previously initialized instances?</li> </ol> <p><hr /></p> <p>EDIT: Following the answers I now understand that by declaring a data member and not referring to it in the <code>__init__</code> or somewhere else as self.dict1, I'm practically defining what's called in C++/Java a static data member. By calling it self.dict1 I'm making it "instance-bound".</p>
33
2009-05-15T06:17:50Z
1,542,534
<p>@Matthew : Please review the difference between a class member and an object member in Object Oriented Programming. This problem happens because of the declaration of the original dict makes it a class member, and not an object member (as was the original poster's intent.) Consequently, it exists once for (is shared accross) all instances of the class (ie once for the class itself, as a member of the class object itself) so the behaviour is perfectly correct. </p>
2
2009-10-09T08:21:50Z
[ "python", "class", "initialization" ]
Writing Digg like system in django/python
867,251
<p>I am tying to write a digg , hackernews , <a href="http://collectivesys.com/" rel="nofollow">http://collectivesys.com/</a> like application where users submit something and other users can vote up or down , mark items as favorite ect . I was just wondering if there are some open source implementations django/python that i could use as starting point , instead of reinventing the wheel by starting from scratch.</p>
2
2009-05-15T06:28:17Z
867,259
<p>Check out <a href="http://pinaxproject.com/" rel="nofollow">Pinax</a> and <a href="http://djangoplugables.com/" rel="nofollow">Django Pluggables</a> for some pre-made Django apps to help you out.</p>
6
2009-05-15T06:32:02Z
[ "python", "django", "digg" ]
Writing Digg like system in django/python
867,251
<p>I am tying to write a digg , hackernews , <a href="http://collectivesys.com/" rel="nofollow">http://collectivesys.com/</a> like application where users submit something and other users can vote up or down , mark items as favorite ect . I was just wondering if there are some open source implementations django/python that i could use as starting point , instead of reinventing the wheel by starting from scratch.</p>
2
2009-05-15T06:28:17Z
867,332
<p><a href="http://reddit.com" rel="nofollow">reddit</a> is <a href="https://github.com/reddit/reddit" rel="nofollow">open source</a>, written mostly in python. Apart from the code, there might be some algorithms you may find helpful.</p>
5
2009-05-15T06:57:22Z
[ "python", "django", "digg" ]
Writing Digg like system in django/python
867,251
<p>I am tying to write a digg , hackernews , <a href="http://collectivesys.com/" rel="nofollow">http://collectivesys.com/</a> like application where users submit something and other users can vote up or down , mark items as favorite ect . I was just wondering if there are some open source implementations django/python that i could use as starting point , instead of reinventing the wheel by starting from scratch.</p>
2
2009-05-15T06:28:17Z
867,335
<p>Though not written in django, <a href="http://reddit.com" rel="nofollow">reddit</a> is written in python and is open source. From <a href="http://code.reddit.com/" rel="nofollow">the code</a> you could get some ideas and see how they overcame certain hurdles etc. They've open sourced everything bar their antispam measures.</p>
1
2009-05-15T06:58:51Z
[ "python", "django", "digg" ]
Writing Digg like system in django/python
867,251
<p>I am tying to write a digg , hackernews , <a href="http://collectivesys.com/" rel="nofollow">http://collectivesys.com/</a> like application where users submit something and other users can vote up or down , mark items as favorite ect . I was just wondering if there are some open source implementations django/python that i could use as starting point , instead of reinventing the wheel by starting from scratch.</p>
2
2009-05-15T06:28:17Z
869,039
<p>I'd recommend taking a close look at the <a href="http://code.google.com/p/django-voting/wiki/RedditStyleVoting" rel="nofollow">django-voting project</a> on Google Code.</p> <p>They claim to be an django implementation of "Reddit Style Voting"</p>
3
2009-05-15T14:31:08Z
[ "python", "django", "digg" ]
How do languages such as Python overcome C's Integral data limits?
867,393
<p>While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:</p> <p>In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified <a href="http://en.wikipedia.org/wiki/Integer%5F%28computer%5Fscience%29#Common%5Fintegral%5Fdata%5Ftypes" rel="nofollow">here</a>.</p> <p>In Python, I can find the factorial of a number as large as 999 which consists of a large number of digits, much more than 19. </p> <p>How does CPython achieve this? Does it use a data type like '<a href="http://en.wikipedia.org/wiki/Integer%5F%28computer%5Fscience%29#Common%5Fintegral%5Fdata%5Ftypes" rel="nofollow">octaword</a>' ? </p> <p>I might be missing some fundamental facts here. So, I would appreciate some insights and/or references to read. Thanks!</p> <p>UPDATE: Thank you all for the explanation. Does that means, CPython is using the GNU Multi-precision library (or some other similar library)? </p> <p>UPDATE 2: I am looking for Python's 'bignum' implementation in the sources. Where exactly it is? Its here at <a href="http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup" rel="nofollow">http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup</a>. Thanks Baishampayan.</p>
2
2009-05-15T07:26:49Z
867,405
<p>Python assigns to <code>long</code> integers (all <code>int</code>s in Python 3) just as much space as they need -- an array of "digits" (base being a power of 2) allocated as needed.</p>
1
2009-05-15T07:30:36Z
[ "python", "c", "types", "integer" ]
How do languages such as Python overcome C's Integral data limits?
867,393
<p>While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:</p> <p>In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified <a href="http://en.wikipedia.org/wiki/Integer%5F%28computer%5Fscience%29#Common%5Fintegral%5Fdata%5Ftypes" rel="nofollow">here</a>.</p> <p>In Python, I can find the factorial of a number as large as 999 which consists of a large number of digits, much more than 19. </p> <p>How does CPython achieve this? Does it use a data type like '<a href="http://en.wikipedia.org/wiki/Integer%5F%28computer%5Fscience%29#Common%5Fintegral%5Fdata%5Ftypes" rel="nofollow">octaword</a>' ? </p> <p>I might be missing some fundamental facts here. So, I would appreciate some insights and/or references to read. Thanks!</p> <p>UPDATE: Thank you all for the explanation. Does that means, CPython is using the GNU Multi-precision library (or some other similar library)? </p> <p>UPDATE 2: I am looking for Python's 'bignum' implementation in the sources. Where exactly it is? Its here at <a href="http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup" rel="nofollow">http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup</a>. Thanks Baishampayan.</p>
2
2009-05-15T07:26:49Z
867,408
<p>Not octaword. It implemented <a href="http://en.wikipedia.org/wiki/Bignum" rel="nofollow">bignum</a> structure to store arbitary-precision numbers.</p>
3
2009-05-15T07:32:07Z
[ "python", "c", "types", "integer" ]
How do languages such as Python overcome C's Integral data limits?
867,393
<p>While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:</p> <p>In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified <a href="http://en.wikipedia.org/wiki/Integer%5F%28computer%5Fscience%29#Common%5Fintegral%5Fdata%5Ftypes" rel="nofollow">here</a>.</p> <p>In Python, I can find the factorial of a number as large as 999 which consists of a large number of digits, much more than 19. </p> <p>How does CPython achieve this? Does it use a data type like '<a href="http://en.wikipedia.org/wiki/Integer%5F%28computer%5Fscience%29#Common%5Fintegral%5Fdata%5Ftypes" rel="nofollow">octaword</a>' ? </p> <p>I might be missing some fundamental facts here. So, I would appreciate some insights and/or references to read. Thanks!</p> <p>UPDATE: Thank you all for the explanation. Does that means, CPython is using the GNU Multi-precision library (or some other similar library)? </p> <p>UPDATE 2: I am looking for Python's 'bignum' implementation in the sources. Where exactly it is? Its here at <a href="http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup" rel="nofollow">http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup</a>. Thanks Baishampayan.</p>
2
2009-05-15T07:26:49Z
867,411
<p>It's called <em>Arbitrary Precision Arithmetic</em>. There's more here: <a href="http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic">http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic</a></p>
9
2009-05-15T07:33:02Z
[ "python", "c", "types", "integer" ]
How do languages such as Python overcome C's Integral data limits?
867,393
<p>While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:</p> <p>In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified <a href="http://en.wikipedia.org/wiki/Integer%5F%28computer%5Fscience%29#Common%5Fintegral%5Fdata%5Ftypes" rel="nofollow">here</a>.</p> <p>In Python, I can find the factorial of a number as large as 999 which consists of a large number of digits, much more than 19. </p> <p>How does CPython achieve this? Does it use a data type like '<a href="http://en.wikipedia.org/wiki/Integer%5F%28computer%5Fscience%29#Common%5Fintegral%5Fdata%5Ftypes" rel="nofollow">octaword</a>' ? </p> <p>I might be missing some fundamental facts here. So, I would appreciate some insights and/or references to read. Thanks!</p> <p>UPDATE: Thank you all for the explanation. Does that means, CPython is using the GNU Multi-precision library (or some other similar library)? </p> <p>UPDATE 2: I am looking for Python's 'bignum' implementation in the sources. Where exactly it is? Its here at <a href="http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup" rel="nofollow">http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup</a>. Thanks Baishampayan.</p>
2
2009-05-15T07:26:49Z
867,416
<p>Data types such as <code>int</code> in C are directly mapped (more or less) to the data types supported by the processor. So the limits on C's <code>int</code> are essentially the limits imposed by the processor hardware.</p> <p>But one can implement one's own <code>int</code> data type entirely in software. You can for example use an array of digits as your underlying representation. May be like this:</p> <pre><code>class MyInt { private int [] digits; public MyInt(int noOfDigits) { digits = new int[noOfDigits]; } } </code></pre> <p>Once you do that you may use this class and store integers containing as many digits as you want, as long as you don't run out memory.</p> <p>Perhaps Python is doing something like this inside its virtual machine. You may want to read <a href="http://en.wikipedia.org/wiki/Arbitrary%5Fprecision" rel="nofollow">this article</a> on Arbitrary Precision Arithmetic to get the details.</p>
4
2009-05-15T07:34:43Z
[ "python", "c", "types", "integer" ]
How do languages such as Python overcome C's Integral data limits?
867,393
<p>While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:</p> <p>In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified <a href="http://en.wikipedia.org/wiki/Integer%5F%28computer%5Fscience%29#Common%5Fintegral%5Fdata%5Ftypes" rel="nofollow">here</a>.</p> <p>In Python, I can find the factorial of a number as large as 999 which consists of a large number of digits, much more than 19. </p> <p>How does CPython achieve this? Does it use a data type like '<a href="http://en.wikipedia.org/wiki/Integer%5F%28computer%5Fscience%29#Common%5Fintegral%5Fdata%5Ftypes" rel="nofollow">octaword</a>' ? </p> <p>I might be missing some fundamental facts here. So, I would appreciate some insights and/or references to read. Thanks!</p> <p>UPDATE: Thank you all for the explanation. Does that means, CPython is using the GNU Multi-precision library (or some other similar library)? </p> <p>UPDATE 2: I am looking for Python's 'bignum' implementation in the sources. Where exactly it is? Its here at <a href="http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup" rel="nofollow">http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup</a>. Thanks Baishampayan.</p>
2
2009-05-15T07:26:49Z
870,429
<p>Looking at the Python source code, it seems the <code>long</code> type (at least in pre-Python 3 code) is defined in <a href="http://svn.python.org/view/python/trunk/Include/longintrepr.h?view=markup" rel="nofollow">longintrepr.h</a> like this -</p> <pre><code>/* Long integer representation. The absolute value of a number is equal to SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i) Negative numbers are represented with ob_size &lt; 0; zero is represented by ob_size == 0. In a normalized number, ob_digit[abs(ob_size)-1] (the most significant digit) is never zero. Also, in all cases, for all valid i, 0 &lt;= ob_digit[i] &lt;= MASK. The allocation function takes care of allocating extra memory so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available. CAUTION: Generic code manipulating subtypes of PyVarObject has to aware that longs abuse ob_size's sign bit. */ struct _longobject { PyObject_VAR_HEAD digit ob_digit[1]; }; </code></pre> <p>The actual usable interface of the <code>long</code> type is then defined in <a href="http://svn.python.org/view/python/trunk/Include/longobject.h?view=markup" rel="nofollow">longobject.h</a> by creating a new type PyLongObject like this -</p> <pre><code>typedef struct _longobject PyLongObject; </code></pre> <p>And so on.</p> <p>There is more stuff happening inside <a href="http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup" rel="nofollow">longobject.c</a>, you can take a look at those for more details.</p>
6
2009-05-15T19:32:03Z
[ "python", "c", "types", "integer" ]
Numbers Comparison - Python Bug?
867,436
<p>Deep inside my code, in a nested if inside a nested for inside a class method, I'm comparing a certain index value to the length of a certain list, to validate I can access that index. The code looks something like that:</p> <pre><code>if t.index_value &lt; len(work_list): ... do stuff ... else: ... print some error ... </code></pre> <p>For clarification, <code>index_value</code> is at least zero (validated somewhere else). To my surprise, even though I know the <code>index_value</code> data is valid, the code keeps going to the "else:" clause. I added some ad-hoc debug code:</p> <pre><code>print('Checking whether '+str(t.index_value)+"&lt;"+str(len(work_list))) x = t.index_value y = len(work_list) print(x) print(y) print(x&lt;y) if t.index_value &lt; len(work_list): ... do stuff ... else: ... print some error ... </code></pre> <p>Following is the output:</p> <pre><code>&gt;&gt; Checking whether 3&lt;4 &gt;&gt; 3 &gt;&gt; 4 &gt;&gt; False </code></pre> <p>Can anyone help me understand what's going on here?</p> <p>Further clarifications:</p> <ul> <li>work_list is a local variable instantiated within the method</li> <li>t is a class instance, instantiated within the method ( <code>t = SomeClass()</code> )</li> </ul> <p><hr /></p> <p>Update: The problem was that the type of <code>t.index_value</code> was UNICODE and not int. The reason was that I deserialized the contents of t from a text file, where the value of index_value is represented by a single digit character. After I extracted it from the text, I immediately assigned it to <code>index_value</code>, without passing it through int() which it what I should have done, and that solved the problem.</p> <p>I decided to keep the "controversial" title despite the fact it's clearly my bug and not Python's, because people with the same problem may find it using this title.</p>
1
2009-05-15T07:45:07Z
867,457
<p>In my experience, what is the type of "t.index_value"? Maybe it is a string "3".</p> <pre><code>&gt;&gt;&gt; print '3' &lt; 4 False </code></pre>
8
2009-05-15T07:51:05Z
[ "python", "numbers" ]
Numbers Comparison - Python Bug?
867,436
<p>Deep inside my code, in a nested if inside a nested for inside a class method, I'm comparing a certain index value to the length of a certain list, to validate I can access that index. The code looks something like that:</p> <pre><code>if t.index_value &lt; len(work_list): ... do stuff ... else: ... print some error ... </code></pre> <p>For clarification, <code>index_value</code> is at least zero (validated somewhere else). To my surprise, even though I know the <code>index_value</code> data is valid, the code keeps going to the "else:" clause. I added some ad-hoc debug code:</p> <pre><code>print('Checking whether '+str(t.index_value)+"&lt;"+str(len(work_list))) x = t.index_value y = len(work_list) print(x) print(y) print(x&lt;y) if t.index_value &lt; len(work_list): ... do stuff ... else: ... print some error ... </code></pre> <p>Following is the output:</p> <pre><code>&gt;&gt; Checking whether 3&lt;4 &gt;&gt; 3 &gt;&gt; 4 &gt;&gt; False </code></pre> <p>Can anyone help me understand what's going on here?</p> <p>Further clarifications:</p> <ul> <li>work_list is a local variable instantiated within the method</li> <li>t is a class instance, instantiated within the method ( <code>t = SomeClass()</code> )</li> </ul> <p><hr /></p> <p>Update: The problem was that the type of <code>t.index_value</code> was UNICODE and not int. The reason was that I deserialized the contents of t from a text file, where the value of index_value is represented by a single digit character. After I extracted it from the text, I immediately assigned it to <code>index_value</code>, without passing it through int() which it what I should have done, and that solved the problem.</p> <p>I decided to keep the "controversial" title despite the fact it's clearly my bug and not Python's, because people with the same problem may find it using this title.</p>
1
2009-05-15T07:45:07Z
867,508
<p>To display values which might be of different types than you expect (e.g. a string rather than a number, as kcwu suggests), use <code>repr(x)</code> and the like.</p>
2
2009-05-15T08:07:11Z
[ "python", "numbers" ]
How to catch str exception?
867,522
<pre><code>import sys try: raise "xxx" except str,e: print "1",e except: print "2",sys.exc_type,sys.exc_value </code></pre> <p>In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it. So how can I catch such exception without relying on catch all, which could be bad.</p> <p>except str,e: doesn't catch it? why?</p> <p>system: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2</p>
2
2009-05-15T08:11:01Z
867,553
<pre><code>try: raise "xxx" except "xxx": print "xxx caught" </code></pre> <p><code>except &lt;class&gt;</code> only works with classes that are a subclass of <code>Exception</code> i think. Oh btw, use <code>basestring</code> when checking the type of strings, works with unicode strings too.</p>
2
2009-05-15T08:19:29Z
[ "python", "exception", "string" ]
How to catch str exception?
867,522
<pre><code>import sys try: raise "xxx" except str,e: print "1",e except: print "2",sys.exc_type,sys.exc_value </code></pre> <p>In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it. So how can I catch such exception without relying on catch all, which could be bad.</p> <p>except str,e: doesn't catch it? why?</p> <p>system: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2</p>
2
2009-05-15T08:11:01Z
867,559
<p>The generic <code>except:</code> clause is the only way to catch all str exceptions.</p> <p>str exceptions are a legacy Python feature. In new code you should use <code>raise Exception("xxx")</code> or raise your own Exception subclass, or <code>assert 0, "xxx"</code>.</p>
6
2009-05-15T08:22:14Z
[ "python", "exception", "string" ]
How to catch str exception?
867,522
<pre><code>import sys try: raise "xxx" except str,e: print "1",e except: print "2",sys.exc_type,sys.exc_value </code></pre> <p>In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it. So how can I catch such exception without relying on catch all, which could be bad.</p> <p>except str,e: doesn't catch it? why?</p> <p>system: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2</p>
2
2009-05-15T08:11:01Z
868,017
<p>Raising raw strings is just wrong. It's a deprecated feature (and as such should have raised warnings). Catching the explicit string will work if you really need it, and so will catching everything. Since catching everything puts the ugliness in <em>your</em> code, I recommend catching the string explicitly, or even better: fixing the broken library.</p> <pre><code>try: #code_that_throws_string() raise("spam") except "spam": pass </code></pre> <p>The pass statement will be reached. There are loads of good reasons not to use strings as exceptions, and this is one of them (the other being: I don't believe you can get tracebacks, so they're largely useless for bug fixing).</p> <p>So, fix the library (good). Or catch the string explicitly (bad). Or catch everything (very bad) and do some isinstance(e, str) checking (even worse).</p>
2
2009-05-15T10:53:12Z
[ "python", "exception", "string" ]
How to catch str exception?
867,522
<pre><code>import sys try: raise "xxx" except str,e: print "1",e except: print "2",sys.exc_type,sys.exc_value </code></pre> <p>In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it. So how can I catch such exception without relying on catch all, which could be bad.</p> <p>except str,e: doesn't catch it? why?</p> <p>system: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2</p>
2
2009-05-15T08:11:01Z
868,244
<p>Here is the solution from <a href="http://groups.google.com/group/comp.lang.python/browse_frm/thread/6f82aa367e86a54e/6891821d373b50a8#6891821d373b50a8" rel="nofollow">python mailing list</a>, not very elegant but will work if can't avoid the need for such hack</p> <pre><code>import sys try: raise "a string exception" except: e, t, tb = sys.exc_info() if not isinstance(e, str): raise print "caught", e </code></pre>
3
2009-05-15T11:54:47Z
[ "python", "exception", "string" ]
Creating a wrapper for a C library in Python
867,850
<p>I'm trying to create a wrapper of my own for FLAC, so that I can use FLAC in my own Python code.</p> <p>I tried using ctypes first, but it showed a really weird interface to the library, e.g. all the init functions for FLAC streams and files became one function with no real information on how to initialize it. Especially since it wants a reference to a stream decoder, but Python has no way to store pointers ( <a href="http://docs.python.org/library/ctypes.html#fundamental-data-types" rel="nofollow">BZZZT!</a> ), and thus I can't store the pointer to the stream decoder. It doesn't help that the different init functions have a different number of arguments and some argument types differ. It also has a lot of enumerations and structures, and I don't know how to get these into my code.</p> <p>I've been looking into Pyrex, but I kinda ran into the same problem with pointers, but I think I solved it, sort-of. <a href="http://github.com/Bocom/zet-subou-/blob/db6d1d37068c936f1e3a98b09ec038b38b7d25e0/flac_wrapper.pyx" rel="nofollow">The file isn't small either, and it's not even complete.</a></p> <p>So I'm looking for alternatives, or guides that would help me understand the aforementioned ways better. It would really help if I could get a recommendation and/or help.</p>
5
2009-05-15T10:06:06Z
867,861
<p>Did you have a look at <a href="http://www.swig.org/">http://www.swig.org/</a>:</p> <blockquote> <p>SWIG is a software development tool that connects programs written in C and C++ with a variety of high-level programming languages.</p> </blockquote>
5
2009-05-15T10:12:24Z
[ "python", "c" ]
Creating a wrapper for a C library in Python
867,850
<p>I'm trying to create a wrapper of my own for FLAC, so that I can use FLAC in my own Python code.</p> <p>I tried using ctypes first, but it showed a really weird interface to the library, e.g. all the init functions for FLAC streams and files became one function with no real information on how to initialize it. Especially since it wants a reference to a stream decoder, but Python has no way to store pointers ( <a href="http://docs.python.org/library/ctypes.html#fundamental-data-types" rel="nofollow">BZZZT!</a> ), and thus I can't store the pointer to the stream decoder. It doesn't help that the different init functions have a different number of arguments and some argument types differ. It also has a lot of enumerations and structures, and I don't know how to get these into my code.</p> <p>I've been looking into Pyrex, but I kinda ran into the same problem with pointers, but I think I solved it, sort-of. <a href="http://github.com/Bocom/zet-subou-/blob/db6d1d37068c936f1e3a98b09ec038b38b7d25e0/flac_wrapper.pyx" rel="nofollow">The file isn't small either, and it's not even complete.</a></p> <p>So I'm looking for alternatives, or guides that would help me understand the aforementioned ways better. It would really help if I could get a recommendation and/or help.</p>
5
2009-05-15T10:06:06Z
867,864
<blockquote> <p>Python has no way to store pointers, and thus I can't store the pointer to the stream decoder</p> </blockquote> <p><strong>ctypes</strong> has pointers, and ctypes can be used to wrap existing C libraries. Just a tip, you will need to wrap/rewrite all relavent C structures into ctypes.Structure. Take look at examples: <a href="http://code.google.com/p/pyxlib-ctypes/">code.google.com/p/pyxlib-ctypes</a> and <a href="http://code.google.com/p/pyxlib-ctypes/">code.google.com/p/pycairo-ctypes</a>. More info how to map function/procedure and its <em>argtypes</em> and <em>restype</em> at <a href="http://docs.python.org/library/ctypes.html">http://docs.python.org/library/ctypes.html</a></p> <blockquote> <p>I've been looking into Pyrex, but I kinda ran into the same problem with pointers, but I think I solved it, sort-of. The file isn't small either, and it's not even complete.</p> </blockquote> <p><strong>cython</strong> may be what you need if you want clean syntax. <a href="http://www.cython.org">www.cython.org</a></p> <blockquote> <p>So I'm looking for alternatives, or guides that would help me understand the aforementioned ways better. It would really help if I could get a recommendation and/or help.</p> </blockquote> <p><strong>swig</strong> on other hand can always be used but it is more complicated if you are not used to it. <a href="http://www.swig.org">www.swig.org</a></p>
10
2009-05-15T10:13:15Z
[ "python", "c" ]
Creating a wrapper for a C library in Python
867,850
<p>I'm trying to create a wrapper of my own for FLAC, so that I can use FLAC in my own Python code.</p> <p>I tried using ctypes first, but it showed a really weird interface to the library, e.g. all the init functions for FLAC streams and files became one function with no real information on how to initialize it. Especially since it wants a reference to a stream decoder, but Python has no way to store pointers ( <a href="http://docs.python.org/library/ctypes.html#fundamental-data-types" rel="nofollow">BZZZT!</a> ), and thus I can't store the pointer to the stream decoder. It doesn't help that the different init functions have a different number of arguments and some argument types differ. It also has a lot of enumerations and structures, and I don't know how to get these into my code.</p> <p>I've been looking into Pyrex, but I kinda ran into the same problem with pointers, but I think I solved it, sort-of. <a href="http://github.com/Bocom/zet-subou-/blob/db6d1d37068c936f1e3a98b09ec038b38b7d25e0/flac_wrapper.pyx" rel="nofollow">The file isn't small either, and it's not even complete.</a></p> <p>So I'm looking for alternatives, or guides that would help me understand the aforementioned ways better. It would really help if I could get a recommendation and/or help.</p>
5
2009-05-15T10:06:06Z
868,007
<p>Some people use <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">pyrex</a> for this.</p>
0
2009-05-15T10:49:07Z
[ "python", "c" ]
Creating a wrapper for a C library in Python
867,850
<p>I'm trying to create a wrapper of my own for FLAC, so that I can use FLAC in my own Python code.</p> <p>I tried using ctypes first, but it showed a really weird interface to the library, e.g. all the init functions for FLAC streams and files became one function with no real information on how to initialize it. Especially since it wants a reference to a stream decoder, but Python has no way to store pointers ( <a href="http://docs.python.org/library/ctypes.html#fundamental-data-types" rel="nofollow">BZZZT!</a> ), and thus I can't store the pointer to the stream decoder. It doesn't help that the different init functions have a different number of arguments and some argument types differ. It also has a lot of enumerations and structures, and I don't know how to get these into my code.</p> <p>I've been looking into Pyrex, but I kinda ran into the same problem with pointers, but I think I solved it, sort-of. <a href="http://github.com/Bocom/zet-subou-/blob/db6d1d37068c936f1e3a98b09ec038b38b7d25e0/flac_wrapper.pyx" rel="nofollow">The file isn't small either, and it's not even complete.</a></p> <p>So I'm looking for alternatives, or guides that would help me understand the aforementioned ways better. It would really help if I could get a recommendation and/or help.</p>
5
2009-05-15T10:06:06Z
870,957
<blockquote> <p>but Python has no way to store pointers ( BZZZT! )</p> </blockquote> <p>That is incorrect. You create a pointer like this:</p> <pre><code>pInt = POINTER(c_int)() </code></pre> <p>and you access it like this</p> <pre><code>pInt[0] # or p.contents </code></pre>
4
2009-05-15T21:33:20Z
[ "python", "c" ]
Creating a wrapper for a C library in Python
867,850
<p>I'm trying to create a wrapper of my own for FLAC, so that I can use FLAC in my own Python code.</p> <p>I tried using ctypes first, but it showed a really weird interface to the library, e.g. all the init functions for FLAC streams and files became one function with no real information on how to initialize it. Especially since it wants a reference to a stream decoder, but Python has no way to store pointers ( <a href="http://docs.python.org/library/ctypes.html#fundamental-data-types" rel="nofollow">BZZZT!</a> ), and thus I can't store the pointer to the stream decoder. It doesn't help that the different init functions have a different number of arguments and some argument types differ. It also has a lot of enumerations and structures, and I don't know how to get these into my code.</p> <p>I've been looking into Pyrex, but I kinda ran into the same problem with pointers, but I think I solved it, sort-of. <a href="http://github.com/Bocom/zet-subou-/blob/db6d1d37068c936f1e3a98b09ec038b38b7d25e0/flac_wrapper.pyx" rel="nofollow">The file isn't small either, and it's not even complete.</a></p> <p>So I'm looking for alternatives, or guides that would help me understand the aforementioned ways better. It would really help if I could get a recommendation and/or help.</p>
5
2009-05-15T10:06:06Z
22,825,713
<p>This post is old, but there's an alternative to <code>ctypes</code>: <a href="http://cffi.readthedocs.org" rel="nofollow">CFFI</a>. It's lots easier, somewhat faster, and works better under PyPy. Plus, it supports pointers well. Here's an example:</p> <pre><code>from cffi import FFI ffi = cffi.FFI() ffi.cdef(''' struct x { void *a; } void* get_buffer(); struct x* make_x(void*); void change_x(struct x*, void*); ''') dll = ffi.dlopen('libmyawesomelibrary.so') buf = dll.get_buffer() tst = dll.new('struct x*') tst.a = buf change_x(tst, get_buffer()) tst2 = make_x(get_buffer()) </code></pre>
1
2014-04-03T00:39:47Z
[ "python", "c" ]
Convert unicode codepoint to UTF8 hex in python
867,866
<p>I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.</p> <p>e.g I want to convert the string <code>'FD9B'</code> to the string <code>'EFB69B'</code>.</p> <p>I can do this manually using string literals like this:</p> <pre><code>u'\uFD9B'.encode('utf-8') </code></pre> <p>but I cannot work out how to do it programatically.</p>
11
2009-05-15T10:13:24Z
867,880
<p>Use the built-in function <code><a href="http://docs.python.org/library/functions.html#unichr">unichr()</a></code> to convert the number to character, then encode that:</p> <pre><code>&gt;&gt;&gt; unichr(int('fd9b', 16)).encode('utf-8') '\xef\xb6\x9b' </code></pre> <p>This is the string itself. If you want the string as ASCII hex, you'd need to walk through and convert each character <code>c</code> to hex, using <code>hex(ord(c))</code> or similar.</p>
17
2009-05-15T10:18:55Z
[ "python", "unicode" ]
Convert unicode codepoint to UTF8 hex in python
867,866
<p>I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.</p> <p>e.g I want to convert the string <code>'FD9B'</code> to the string <code>'EFB69B'</code>.</p> <p>I can do this manually using string literals like this:</p> <pre><code>u'\uFD9B'.encode('utf-8') </code></pre> <p>but I cannot work out how to do it programatically.</p>
11
2009-05-15T10:13:24Z
867,884
<pre><code>Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; u'\uFD9B'.encode('utf-8') '\xef\xb6\x9b' &gt;&gt;&gt; s = 'FD9B' &gt;&gt;&gt; i = int(s, 16) &gt;&gt;&gt; i 64923 &gt;&gt;&gt; unichr(i) u'\ufd9b' &gt;&gt;&gt; _.encode('utf-8') '\xef\xb6\x9b' </code></pre>
1
2009-05-15T10:20:48Z
[ "python", "unicode" ]
Convert unicode codepoint to UTF8 hex in python
867,866
<p>I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.</p> <p>e.g I want to convert the string <code>'FD9B'</code> to the string <code>'EFB69B'</code>.</p> <p>I can do this manually using string literals like this:</p> <pre><code>u'\uFD9B'.encode('utf-8') </code></pre> <p>but I cannot work out how to do it programatically.</p>
11
2009-05-15T10:13:24Z
869,221
<pre><code>data_from_file='\uFD9B' unicode(data_from_file,"unicode_escape").encode("utf8") </code></pre>
3
2009-05-15T15:05:03Z
[ "python", "unicode" ]
Convert unicode codepoint to UTF8 hex in python
867,866
<p>I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.</p> <p>e.g I want to convert the string <code>'FD9B'</code> to the string <code>'EFB69B'</code>.</p> <p>I can do this manually using string literals like this:</p> <pre><code>u'\uFD9B'.encode('utf-8') </code></pre> <p>but I cannot work out how to do it programatically.</p>
11
2009-05-15T10:13:24Z
870,567
<p>If the input string length is a multiple of 4 (i.e. your unicode code points are UCS-2 encoded), then try this:</p> <pre><code>import struct def unihex2utf8hex(arg): count= len(arg)//4 uniarr= struct.unpack('!%dH' % count, arg.decode('hex')) return u''.join(map(unichr, uniarr)).encode('utf-8').encode('hex') &gt;&gt;&gt; unihex2utf8hex('fd9b') 'efb69b' </code></pre>
1
2009-05-15T19:54:55Z
[ "python", "unicode" ]
Convert unicode codepoint to UTF8 hex in python
867,866
<p>I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.</p> <p>e.g I want to convert the string <code>'FD9B'</code> to the string <code>'EFB69B'</code>.</p> <p>I can do this manually using string literals like this:</p> <pre><code>u'\uFD9B'.encode('utf-8') </code></pre> <p>but I cannot work out how to do it programatically.</p>
11
2009-05-15T10:13:24Z
15,181,783
<p>here's a complete solution:</p> <pre><code>&gt;&gt;&gt; ''.join(['{0:x}'.format(ord(x)) for x in unichr(int('FD9B', 16)).encode('utf-8')]).upper() 'EFB69B' </code></pre>
2
2013-03-03T02:22:40Z
[ "python", "unicode" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
867,983
<p>I have no idea what you're trying to do with that code. But I'm 99% certain that whatever it is could probably be done in 2 lines. I also get the feeling that the '==' operator should be an 'is' operator, otherwise what is the compare() function doing? And what happens if the item returned from the second jump_iter.next call also equals 'item'? It seems like the algorithm would do the wrong thing since you'll compare the second and not the first.</p>
0
2009-05-15T10:44:14Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
867,991
<p>You could put the whole iteration into a single try structure, that way it would be clearer:</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() for item in items: if jump_item is item: jump_item = jump_iter.next() # do lots of stuff with item and jump_item except StopIteration: pass </code></pre>
0
2009-05-15T10:46:34Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
867,994
<p>So you want to compare pairs of items in the same list, the second item of the pair having to meet some condition. Normally, when you want to compare pairs in a list use <code>zip</code> (or <code>itertools.izip</code>):</p> <pre><code>for item1, item2 in zip(items, items[1:]): compare(item1, item2) </code></pre> <p>Figure out how to fit your <code>some_cond</code> in this :)</p>
0
2009-05-15T10:46:37Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
868,000
<p>I have no idea what <code>compare()</code> is doing, but 80% of the time, you can do this with a trivial dictionary or pair of dictionaries. Jumping around in a list is a kind of linear search. Linear Search -- to the extent possible -- should always be replaced with either a direct reference (i.e., a dict) or a tree search (using the bisect module).</p>
1
2009-05-15T10:47:45Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
868,152
<p>Are you basically trying to compare every item in the iterator with every other item in the original list?</p> <p>To my mind this should just be a case of using two loops, rather than trying to fit it into one.</p> <pre> <code> filtered_items = (j for j in items if some_cond) for filtered in filtered_items: for item in items: if filtered != item: compare(filtered, item) </code> </pre>
0
2009-05-15T11:31:25Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
868,363
<p>Here is one simple solution that might look a little cleaner: </p> <pre><code>for i, item in enumerate(items): for next_item in items[i+1:]: if some_cond(next_item): break # do some stuff with both items </code></pre> <p>The disadvantage is that you check the condition for next_item multiple times. But you can easily optimize this:</p> <pre><code>cond_items = [item if some_cond(item) else None for item in items] for i, item in enumerate(items): for next_item in cond_items[i+1:]: if next_item is not None: break # do some stuff with both items </code></pre> <p>However, both solutions carry more overhead than the original solution from the question. And when you start using counters to work around this then I think it is better to use the iterator interface directly (as in the original solution).</p>
0
2009-05-15T12:19:15Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
868,396
<p>How about this?</p> <pre><code>paired_values = [] for elmt in reversed(items): if &lt;condition&gt;: current_val = elmt try: paired_values.append(current_val) except NameError: # for the last elements of items that don't pass the condition pass paired_values.reverse() for (item, jump_item) in zip(items, paired_values): # zip() truncates to len(paired_values) # do lots of stuff </code></pre> <p>If the first element of items matches, then it is used as a jump_item. This is the only difference with your original code (and you might want this behavior).</p>
1
2009-05-15T12:26:24Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
868,410
<p>My first answer was wrong because I didn't quite understand what you were trying to achieve. So if I understand correctly (this time, I hope), you want the main <code>for item in items:</code> to "chase" after an iterator that filters out some items. Well, there's not much you can do, except maybe wrap this into a <code>chase_iterator(iterable, some_cond)</code> generator, which would make your main code a little more readable.</p> <p>Maybe that a more readable approach would be an "accumulator approach" (if the order of the compare() don't matter), like:</p> <pre><code>others = [] for item in items: if some_cond(item): for other in others: compare(item, other) others = [] else: others.append(item) </code></pre> <p>(man, I'm beginning to hate Stack Overflow... too addictive...)</p>
0
2009-05-15T12:29:29Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
868,458
<p>The following iterator is time and memory-efficient:</p> <pre><code>def jump_items(items): number_to_be_returned = 0 for elmt in items: if &lt;condition(elmt)&gt;: for i in range(number_to_be_returned): yield elmt number_to_be_returned = 1 else: number_to_be_returned += 1 for (item, jump_item) in zip(items, jump_items(items)): # do lots of stuff </code></pre> <p>Note that you may actually want to set the first number_to_be_returned to 1...</p>
1
2009-05-15T12:40:49Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
868,497
<pre><code>for i in range( 0, len( items ) ): for j in range( i+1, len( items ) ): if some_cond: #do something #items[i] = item, items[j] = jump_item </code></pre>
0
2009-05-15T12:49:50Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
868,631
<p>With just iterators</p> <pre><code>def(lst, some_cond): jump_item_iter = (j for j in lst if som_cond(j)) pairs = itertools.izip(lst, lst[1:]) for last in jump_item_iter: for start, start_next in itertools.takewhile(lambda pair: pair[0] &lt; last, pairs): yield start, last pairs = itertools.chain([(start_next, 'dummy')], pairs) </code></pre> <p>with the input: range(10) and some_cond = lambda x : x % 2 gives [(0, 1), (1, 3), (2, 3), (3, 5), (4, 5), (5, 7), (6, 7), (7, 9), (8, 9)] (same that your example)</p>
0
2009-05-15T13:19:04Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
868,763
<p>Even better using itertools.groupby:</p> <pre><code>def h(lst, cond): remain = lst for last in (l for l in lst if cond(l)): group = itertools.groupby(remain, key=lambda x: x &lt; last) for start in group.next()[1]: yield start, last remain = list(group.next()[1]) </code></pre> <p>Usage: lst = range(10) cond = lambda x: x%2 print list(h(lst, cond))</p> <p>will print </p> <pre><code>[(0, 1), (1, 3), (2, 3), (3, 5), (4, 5), (5, 7), (6, 7), (7, 9), (8, 9)] </code></pre>
0
2009-05-15T13:46:05Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
868,770
<p>Maybe it is too late, but what about:</p> <pre><code>l = [j for j in items if some_cond] for item, jump_item in zip(l, l[1:]): # do lots of stuff with item and jump_item </code></pre> <p>If l = [j for j in range(10) if j%2 ==0] then the iteration is over: [(0, 2),(2, 4),(4, 6),(6, 8)].</p>
0
2009-05-15T13:47:15Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
868,864
<p>Write a generator function:</p> <pre><code>def myIterator(someValue): yield (someValue[0], someValue[1]) for element1, element2 in myIterator(array): # do something with those elements. </code></pre>
1
2009-05-15T14:03:58Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
869,468
<p>As far as I can see any of the existing solutions work on a general one shot, possiboly infinite iter**ator**, all of them seem to require an iter**able**.</p> <p>Heres a solution to that.</p> <pre><code>def batch_by(condition, seq): it = iter(seq) batch = [it.next()] for jump_item in it: if condition(jump_item): for item in batch: yield item, jump_item batch = [] batch.append(jump_item) </code></pre> <p>This will easily work on infinite iterators:</p> <pre><code>from itertools import count, islice is_prime = lambda n: n == 2 or all(n % div for div in xrange(2,n)) print list(islice(batch_by(is_prime, count()), 100)) </code></pre> <p>This will print first 100 integers with the prime number that follows them.</p>
4
2009-05-15T15:49:57Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
870,027
<p>You could write your loop body as:</p> <pre><code>import itertools, functools, operator for item in items: jump_item_iter = itertools.dropwhile(functools.partial(operator.is_, item), jump_item_iter) # do something with item and jump_item_iter </code></pre> <p>dropwhile will return an iterator that skips over all those which match the condition (here "<code>is item</code>").</p>
0
2009-05-15T17:48:53Z
[ "python", "iterator" ]
Python: Elegant way of dual/multiple iteration over the same list
867,936
<p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p> <pre><code>jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if jump_item is item: try: jump_item = jump_iter.next() except StopIteration: return # do lots of stuff with item and jump_item </code></pre> <p>I don't think the "<code>except StopIteration</code>" is very elegant</p> <p>Edit:</p> <p>To hopefully make it clearer, I want to visit each item in a list and pair it with the next item further on in the list (jump_item) which satisfies some_cond.</p>
6
2009-05-15T10:35:14Z
870,982
<p>You could do something like:</p> <pre><code>import itertools def matcher(iterable, compare): iterator= iter(iterable) while True: try: item= iterator.next() except StopIteration: break iterator, iterator2= itertools.tee(iterator) for item2 in iterator2: if compare(item, item2): yield item, item2 </code></pre> <p>but it's quite elaborate (and actually not very efficient), and it would be simpler if you just did a</p> <pre><code>items= list(iterable) </code></pre> <p>and then just write two loops over <code>items</code>.</p> <p>Obviously, this won't work with infinite iterables, but your specification can only work on finite iterables.</p>
0
2009-05-15T21:41:22Z
[ "python", "iterator" ]
Loading files into variables in python
868,112
<p>I am trying to write a small function that gets a variable name, check if it exists, and if not loads it from a file (using pickle) to the global namespace.</p> <p>I tried using this in a file:</p> <pre><code>import cPickle # # Load if neccesary # def loadfile(variable, filename): if variable not in globals(): cmd = "%s = cPickle.load(file('%s','r'))" % (variable, filename) print cmd exec(cmd) in globals() </code></pre> <p>But it doesn't work - the variable don't get defined. What am I doing wrong?</p>
2
2009-05-15T11:17:57Z
868,172
<p>You could alway avoid exec entirely:</p> <pre> <code> import cPickle # # Load if neccesary # def loadfile(variable, filename): g=globals() if variable not in g: g[variable]=cPickle.load(file(filename,'r')) </code> </pre> <p>EDIT: of course that only loads the globals into the current module's globals.</p> <p>If you want to load the stuff into the globals of another module you'd be best to pass in them in as a parameter:</p> <pre> <code> import cPickle # # Load if neccesary # def loadfile(variable, filename, g=None): if g is None: g=globals() if variable not in g: g[variable]=cPickle.load(file(filename,'r')) # then in another module do this loadfile('myvar','myfilename',globals()) </code> </pre>
2
2009-05-15T11:37:16Z
[ "python", "namespaces", "pickle" ]
Loading files into variables in python
868,112
<p>I am trying to write a small function that gets a variable name, check if it exists, and if not loads it from a file (using pickle) to the global namespace.</p> <p>I tried using this in a file:</p> <pre><code>import cPickle # # Load if neccesary # def loadfile(variable, filename): if variable not in globals(): cmd = "%s = cPickle.load(file('%s','r'))" % (variable, filename) print cmd exec(cmd) in globals() </code></pre> <p>But it doesn't work - the variable don't get defined. What am I doing wrong?</p>
2
2009-05-15T11:17:57Z
868,443
<p>Using 'globals' has the problem that it only works for the current module. Rather than passing 'globals' around, a better way is to use the 'setattr' builtin directly on a namespace. This means you can then reuse the function on instances as well as modules.</p> <pre><code>import cPickle # # Load if neccesary # def loadfile(variable, filename, namespace=None): if module is None: import __main__ as namespace setattr(namespace, variable, cPickle.load(file(filename,'r'))) # From the main script just do: loadfile('myvar','myfilename') # To set the variable in module 'mymodule': import mymodule ... loadfile('myvar', 'myfilename', mymodule) </code></pre> <p>Be careful about the module name: the main script is always a module <strong>main</strong>. If you are running script.py and do 'import script' you'll get a separate copy of your code which is usually not what you want.</p>
2
2009-05-15T12:36:41Z
[ "python", "namespaces", "pickle" ]
What host to use when making a UDP socket in python?
868,173
<p>I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python:</p> <pre><code>import socket import sys HOST = ??????? PORT = 80 # SOCK_DGRAM is the socket type to use for UDP sockets sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((HOST,PORT)) data,addr = sock.recv(1024) print "Received: %s" % data print "Addr: %s" % addr </code></pre> <p>What should I use as host? I know the IP of the sender but it seems anything thats not local gives me socket.error: [Errno 10049]. The IP that the VPN gives me (the same IP that the sender sends to, that is)? Or just localhost?</p>
4
2009-05-15T11:37:25Z
868,191
<p>The host argument is the host IP you want to bind to. Specify the IP of one of your interfaces (Eg, your public IP, or 127.0.0.1 for localhost), or use 0.0.0.0 to bind to all interfaces. If you bind to a specific interface, your service will only be available on that interface - for example, if you want to run something that can only be accessed via localhost, or if you have multiple IPs and need to run different servers on each.</p>
10
2009-05-15T11:40:10Z
[ "python", "sockets", "udp" ]
What host to use when making a UDP socket in python?
868,173
<p>I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python:</p> <pre><code>import socket import sys HOST = ??????? PORT = 80 # SOCK_DGRAM is the socket type to use for UDP sockets sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((HOST,PORT)) data,addr = sock.recv(1024) print "Received: %s" % data print "Addr: %s" % addr </code></pre> <p>What should I use as host? I know the IP of the sender but it seems anything thats not local gives me socket.error: [Errno 10049]. The IP that the VPN gives me (the same IP that the sender sends to, that is)? Or just localhost?</p>
4
2009-05-15T11:37:25Z
868,206
<p>"0.0.0.0" will listen for all incoming hosts. For example,</p> <pre><code>sock.bind(("0.0.0.0", 999)) data,addr = sock.recv(1024) </code></pre>
3
2009-05-15T11:42:54Z
[ "python", "sockets", "udp" ]
What host to use when making a UDP socket in python?
868,173
<p>I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python:</p> <pre><code>import socket import sys HOST = ??????? PORT = 80 # SOCK_DGRAM is the socket type to use for UDP sockets sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((HOST,PORT)) data,addr = sock.recv(1024) print "Received: %s" % data print "Addr: %s" % addr </code></pre> <p>What should I use as host? I know the IP of the sender but it seems anything thats not local gives me socket.error: [Errno 10049]. The IP that the VPN gives me (the same IP that the sender sends to, that is)? Or just localhost?</p>
4
2009-05-15T11:37:25Z
868,230
<p>Use:</p> <pre><code>sock.bind(("", 999)) </code></pre>
3
2009-05-15T11:49:50Z
[ "python", "sockets", "udp" ]
Python Newbie: Returning Multiple Int/String Results in Python
868,325
<p>I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. </p> <p>In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not sure what's the right solution, because integers and strings are not passed by reference but by value (at least this is what I understand from trial-and-error), so the following code won't work:</p> <pre><code>def analyze(string, number_of_words, average_length): ... do some analysis ... number_of_words = ... average_length = ... </code></pre> <p>If i do the above, the values outside the scope of the function don't change. What I currently do is use a dictionary like so:</p> <pre><code>def analyze(string, result): ... do some analysis ... result['number_of_words'] = ... result['average_length'] = ... </code></pre> <p>And I use the function like this:</p> <pre><code>s = "hello goodbye" result = {} analyze(s, result) </code></pre> <p>However, that does not feel right. What's the correct Pythonian way to achieve this? Please note I'm referring only to cases where the function returns 2-3 results, not tens of results. Also, I'm a complete newbie to Python, so I know I may be missing something trivial here...</p> <p>Thanks</p>
1
2009-05-15T12:12:31Z
868,355
<p>If you need to use method arguments in both directions, you can encapsulate the arguments to the class and pass object to the method and let the method use its properties.</p>
0
2009-05-15T12:17:44Z
[ "python", "parameters", "reference" ]
Python Newbie: Returning Multiple Int/String Results in Python
868,325
<p>I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. </p> <p>In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not sure what's the right solution, because integers and strings are not passed by reference but by value (at least this is what I understand from trial-and-error), so the following code won't work:</p> <pre><code>def analyze(string, number_of_words, average_length): ... do some analysis ... number_of_words = ... average_length = ... </code></pre> <p>If i do the above, the values outside the scope of the function don't change. What I currently do is use a dictionary like so:</p> <pre><code>def analyze(string, result): ... do some analysis ... result['number_of_words'] = ... result['average_length'] = ... </code></pre> <p>And I use the function like this:</p> <pre><code>s = "hello goodbye" result = {} analyze(s, result) </code></pre> <p>However, that does not feel right. What's the correct Pythonian way to achieve this? Please note I'm referring only to cases where the function returns 2-3 results, not tens of results. Also, I'm a complete newbie to Python, so I know I may be missing something trivial here...</p> <p>Thanks</p>
1
2009-05-15T12:12:31Z
868,356
<p>python has a <code>return</code> statement, which allows you to do the follwing:</p> <pre><code>def func(input): # do calculation on input return result s = "hello goodbye" res = func(s) # res now a result dictionary </code></pre> <p>but you don't need to have <code>result</code> at all, you can return a few values like so:</p> <pre><code>def func(input): # do work return length, something_else # one might be an integer another string, etc. s = "hello goodbye" length, something = func(s) </code></pre>
17
2009-05-15T12:17:50Z
[ "python", "parameters", "reference" ]
Python Newbie: Returning Multiple Int/String Results in Python
868,325
<p>I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. </p> <p>In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not sure what's the right solution, because integers and strings are not passed by reference but by value (at least this is what I understand from trial-and-error), so the following code won't work:</p> <pre><code>def analyze(string, number_of_words, average_length): ... do some analysis ... number_of_words = ... average_length = ... </code></pre> <p>If i do the above, the values outside the scope of the function don't change. What I currently do is use a dictionary like so:</p> <pre><code>def analyze(string, result): ... do some analysis ... result['number_of_words'] = ... result['average_length'] = ... </code></pre> <p>And I use the function like this:</p> <pre><code>s = "hello goodbye" result = {} analyze(s, result) </code></pre> <p>However, that does not feel right. What's the correct Pythonian way to achieve this? Please note I'm referring only to cases where the function returns 2-3 results, not tens of results. Also, I'm a complete newbie to Python, so I know I may be missing something trivial here...</p> <p>Thanks</p>
1
2009-05-15T12:12:31Z
868,365
<p>If you return the variables in your function like this:</p> <pre><code>def analyze(s, num_words, avg_length): # do something return s, num_words, avg_length </code></pre> <p>Then you can call it like this to update the parameters that were passed:</p> <pre><code>s, num_words, avg_length = analyze(s, num_words, avg_length) </code></pre> <p>But, for your example function, this would be better:</p> <pre><code>def analyze(s): # do something return num_words, avg_length </code></pre>
3
2009-05-15T12:19:32Z
[ "python", "parameters", "reference" ]
Python Newbie: Returning Multiple Int/String Results in Python
868,325
<p>I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. </p> <p>In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not sure what's the right solution, because integers and strings are not passed by reference but by value (at least this is what I understand from trial-and-error), so the following code won't work:</p> <pre><code>def analyze(string, number_of_words, average_length): ... do some analysis ... number_of_words = ... average_length = ... </code></pre> <p>If i do the above, the values outside the scope of the function don't change. What I currently do is use a dictionary like so:</p> <pre><code>def analyze(string, result): ... do some analysis ... result['number_of_words'] = ... result['average_length'] = ... </code></pre> <p>And I use the function like this:</p> <pre><code>s = "hello goodbye" result = {} analyze(s, result) </code></pre> <p>However, that does not feel right. What's the correct Pythonian way to achieve this? Please note I'm referring only to cases where the function returns 2-3 results, not tens of results. Also, I'm a complete newbie to Python, so I know I may be missing something trivial here...</p> <p>Thanks</p>
1
2009-05-15T12:12:31Z
868,760
<p>In python you don't modify parameters in the C/C++ way (passing them by reference or through a pointer and doing modifications <em>in situ</em>).There are some reasons such as that the string objects are inmutable in python. The right thing to do is to return the modified parameters in a tuple (as SilentGhost suggested) and rebind the variables to the new values.</p>
1
2009-05-15T13:45:26Z
[ "python", "parameters", "reference" ]
Problem using py2app with the lxml package
868,510
<p>I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' installed.</p> <p>My Setup.py looks like this:</p> <pre><code>from setuptools import setup OPTIONS = {'argv_emulation': True, 'packages' : ['lxml']} setup(app=[MyApp.py], data_files=[], options={'py2app' : OPTIONS}, setup_requires=['py2app']) </code></pre> <p>Running the application produces the following output:</p> <pre><code>MyApp Error An unexpected error has occurred during execution of the main script ImportError: dlopen(/Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so, 2): Symbol not found: _xmlSchematronParse Referenced from: /Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so Expected in: dynamic lookup </code></pre> <p>The symbol '_xmlSchematronParse' is from a library called 'libxml2' that 'lxml' depends on. The version that comes preinstalled with Mac OS X isn't up to date enough for 'lxml', so I had to install version 2.7.2 (in /usr/local). py2app, for some reason, is linking in the version in /Developer/SDKs/MacOSX10.3.9.sdk/usr/lib. When I run my application as a Python script though, the correct version is found. (I checked this just now by hiding the 2.7.2 version.)</p> <p>So my question now is, how can I tell py2app where to look for libraries?</p>
5
2009-05-15T12:52:37Z
868,549
<p><strong>------------- Edit--------------</strong><br> <code>libxml2</code> is standard in the python.org version of Python. It is not standard in Apple's version of Python. Make sure py2app is using the right version of Python, or install <code>libxml2</code> and <code>libxslt</code> on your Mac.</p>
1
2009-05-15T13:01:48Z
[ "python", "lxml", "py2app" ]
Problem using py2app with the lxml package
868,510
<p>I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' installed.</p> <p>My Setup.py looks like this:</p> <pre><code>from setuptools import setup OPTIONS = {'argv_emulation': True, 'packages' : ['lxml']} setup(app=[MyApp.py], data_files=[], options={'py2app' : OPTIONS}, setup_requires=['py2app']) </code></pre> <p>Running the application produces the following output:</p> <pre><code>MyApp Error An unexpected error has occurred during execution of the main script ImportError: dlopen(/Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so, 2): Symbol not found: _xmlSchematronParse Referenced from: /Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so Expected in: dynamic lookup </code></pre> <p>The symbol '_xmlSchematronParse' is from a library called 'libxml2' that 'lxml' depends on. The version that comes preinstalled with Mac OS X isn't up to date enough for 'lxml', so I had to install version 2.7.2 (in /usr/local). py2app, for some reason, is linking in the version in /Developer/SDKs/MacOSX10.3.9.sdk/usr/lib. When I run my application as a Python script though, the correct version is found. (I checked this just now by hiding the 2.7.2 version.)</p> <p>So my question now is, how can I tell py2app where to look for libraries?</p>
5
2009-05-15T12:52:37Z
874,923
<p>I have no experience with the combination of lxml and py2app specifically, but I've had issues with py2app not picking up modules that were not explicitly imported. For example, I had to explicitly include modules that are imported via <code>__import__()</code>, like this:</p> <pre><code>OPTIONS['includes'] = [filename[:-3].replace('/', '.') for filename \ in glob.glob('path/to/*.py')] </code></pre> <p>Maybe it also helps in your case to insert an explicit <code>from lxml import etree</code> somewhere in your code?</p>
1
2009-05-17T16:24:43Z
[ "python", "lxml", "py2app" ]
Problem using py2app with the lxml package
868,510
<p>I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' installed.</p> <p>My Setup.py looks like this:</p> <pre><code>from setuptools import setup OPTIONS = {'argv_emulation': True, 'packages' : ['lxml']} setup(app=[MyApp.py], data_files=[], options={'py2app' : OPTIONS}, setup_requires=['py2app']) </code></pre> <p>Running the application produces the following output:</p> <pre><code>MyApp Error An unexpected error has occurred during execution of the main script ImportError: dlopen(/Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so, 2): Symbol not found: _xmlSchematronParse Referenced from: /Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so Expected in: dynamic lookup </code></pre> <p>The symbol '_xmlSchematronParse' is from a library called 'libxml2' that 'lxml' depends on. The version that comes preinstalled with Mac OS X isn't up to date enough for 'lxml', so I had to install version 2.7.2 (in /usr/local). py2app, for some reason, is linking in the version in /Developer/SDKs/MacOSX10.3.9.sdk/usr/lib. When I run my application as a Python script though, the correct version is found. (I checked this just now by hiding the 2.7.2 version.)</p> <p>So my question now is, how can I tell py2app where to look for libraries?</p>
5
2009-05-15T12:52:37Z
877,560
<p>I just tried my app (uses py2app and lxml, with a similar setup) on another Mac without development libraries installed, and it works, so there must be something wrong in your system. My guess is that py2app picks the wrong version of libxml2 (I see it comes bundled with the iPhone SDK for example, which is probably not the version you want).</p> <p>Mine, as the whole python toolchain, comes from MacPorts, md5 sum of the latest libxml2.2.dylib (the one that ends up in my .app) is 863c7208b6c34f116a2925444933c22a on my system.</p>
1
2009-05-18T12:46:32Z
[ "python", "lxml", "py2app" ]
Problem using py2app with the lxml package
868,510
<p>I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' installed.</p> <p>My Setup.py looks like this:</p> <pre><code>from setuptools import setup OPTIONS = {'argv_emulation': True, 'packages' : ['lxml']} setup(app=[MyApp.py], data_files=[], options={'py2app' : OPTIONS}, setup_requires=['py2app']) </code></pre> <p>Running the application produces the following output:</p> <pre><code>MyApp Error An unexpected error has occurred during execution of the main script ImportError: dlopen(/Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so, 2): Symbol not found: _xmlSchematronParse Referenced from: /Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so Expected in: dynamic lookup </code></pre> <p>The symbol '_xmlSchematronParse' is from a library called 'libxml2' that 'lxml' depends on. The version that comes preinstalled with Mac OS X isn't up to date enough for 'lxml', so I had to install version 2.7.2 (in /usr/local). py2app, for some reason, is linking in the version in /Developer/SDKs/MacOSX10.3.9.sdk/usr/lib. When I run my application as a Python script though, the correct version is found. (I checked this just now by hiding the 2.7.2 version.)</p> <p>So my question now is, how can I tell py2app where to look for libraries?</p>
5
2009-05-15T12:52:37Z
888,551
<p>Found it. py2app has a 'frameworks' option to let you specify frameworks, and also dylibs. My setup.py file now looks like this:</p> <pre><code>from setuptools import setup DATA_FILES = [] OPTIONS = {'argv_emulation': True, 'packages' : ['lxml'], 'frameworks' : ['/usr/local/libxml2-2.7.2/lib/libxml2.2.7.2.dylib'] } setup(app=MyApp.py, data_files=DATA_FILES, options={'py2app' : OPTIONS}, setup_requires=['py2app']) </code></pre> <p>and that's fixed it.</p> <p>Thanks for the suggestions that led me here.</p>
10
2009-05-20T15:15:54Z
[ "python", "lxml", "py2app" ]
On GAE, how may I show a date according to right client TimeZone?
868,708
<p>On my Google App Engine application, i'm storing an auto-updated date/time in my model like that :</p> <pre><code>class MyModel(db.Model): date = db.DateTimeProperty(auto_now_add=True) </code></pre> <p>But, that date/time is the local time on server, according to it's time zone.</p> <p>So, when I would like to display it on my web page, how may I format it according the <strong>client</strong> time zone ?</p> <p>Also, how may I know on which time zone that google server is ?</p>
5
2009-05-15T13:34:23Z
868,762
<p>You can find out the server's timezone by asking for local and UTC time and seeing what the difference is. To find out the client timezone you need to have in your template a little bit of Javascript that will tell you e.g. in an AJAX exchange. To manipulate timezones once you've discovered the deltas I suggest pytz, pytz.sourceforge.net/ .</p>
1
2009-05-15T13:45:45Z
[ "python", "django", "google-app-engine", "timezone" ]
On GAE, how may I show a date according to right client TimeZone?
868,708
<p>On my Google App Engine application, i'm storing an auto-updated date/time in my model like that :</p> <pre><code>class MyModel(db.Model): date = db.DateTimeProperty(auto_now_add=True) </code></pre> <p>But, that date/time is the local time on server, according to it's time zone.</p> <p>So, when I would like to display it on my web page, how may I format it according the <strong>client</strong> time zone ?</p> <p>Also, how may I know on which time zone that google server is ?</p>
5
2009-05-15T13:34:23Z
868,793
<p>With respect to the second part of your question:</p> <p>Python time() returns UTC regardless of what time zone the server is in. timezone() and tzname() will give you, respectively, the offset to local time on the server and the name of the timezone and the DST timezone as a tuple. GAE uses Python 2.5.x as of the time of this posting; see the documentation for Python time functions <a href="http://www.python.org/doc/2.3.5/lib/module-time.html" rel="nofollow">here</a>.</p> <p>For the first part of the question:</p> <p>You can either format the date with code on the server, or with code on the client. </p> <ul> <li><p>If you format on the server, you can </p> <ul> <li>Use the timezone of the requester's IP address</li> <li>Require a user to register and give you a timezone, store it, and use the stored value</li> <li>Use a (hidden?) field on the GET or POST so the client's desired timezone is part of the request</li> </ul></li> <li><p>If you format on the client, you'll need to write a few lines of JavaScript. The procedure is something like "make a date from UTC using Date(utctime), then stuff it into the document." By default, JavaScript dates display as local time regardless of how they were initialized - awesome! </p></li> </ul> <p>I recommend formatting on the client, because what's a webpage like without a bit of JavaScript? It's 2009! <a href="http://blogs.msdn.com/marcelolr/archive/2008/06/04/javascript-date-utc-and-local-times.aspx" rel="nofollow">Marcelo</a> has some examples.</p>
5
2009-05-15T13:50:08Z
[ "python", "django", "google-app-engine", "timezone" ]
On GAE, how may I show a date according to right client TimeZone?
868,708
<p>On my Google App Engine application, i'm storing an auto-updated date/time in my model like that :</p> <pre><code>class MyModel(db.Model): date = db.DateTimeProperty(auto_now_add=True) </code></pre> <p>But, that date/time is the local time on server, according to it's time zone.</p> <p>So, when I would like to display it on my web page, how may I format it according the <strong>client</strong> time zone ?</p> <p>Also, how may I know on which time zone that google server is ?</p>
5
2009-05-15T13:34:23Z
868,885
<p>Ok, so thanks to Thomas L Holaday, I have to sent that UTC date to the client, for example using JSON : </p> <pre><code>json = '{"serverUTCDate":new Date("%s")}' % date.ctime() </code></pre> <p>And then, on the client side, add/remove the number of seconds according to the user time zone like that :</p> <pre><code>var localDate = serverUTCDate.getTime() - (new Date()).getTimezoneOffset()*60000; </code></pre>
2
2009-05-15T14:07:55Z
[ "python", "django", "google-app-engine", "timezone" ]
HTML Newbie Question: Colored Background for Characters in Django HttpResponse
868,871
<p>I would like to generate an HttpResponse that contains a certain string. For each of the characters in the string I have a background color I want to use. </p> <p>For simplification, let's assume I can only have shades of green in the background, and that the "background colors" data represents "level of brightness" in the green domain.</p> <p>For example, a response may be 'abcd', and my "background colors" data may be:</p> <pre><code>[0.0, 1.0, 0.5, 1.0] </code></pre> <p>This would mean the first character 'a' needs to have a background of dark green (e.g. 004000), the second character 'b' needs to have a background of bright green (e.g. 00ff00), the third character 'c' needs to have a "middle" brightness (e.g. 00A000), and so on.</p> <p>I don't want to use a template but rather just return "plain text" response. Is that possible?</p> <p>If not - what would be the simplest template I could use for that?</p> <p>Thanks</p>
1
2009-05-15T14:04:30Z
869,024
<p>It could be something like this:</p> <pre><code>aString = 'abcd' newString ='' colors= [0.0, 1.0, 0.5, 1.0] for i in aString: newString = newString + '&lt;span style="background-color: rgb(0,%s,0)"&gt;%s&lt;/span&gt;'%(colors.pop(0)*255,i) response = HttpResponse(newString) </code></pre> <p>untested</p>
2
2009-05-15T14:28:52Z
[ "python", "html", "django", "colors" ]
HTML Newbie Question: Colored Background for Characters in Django HttpResponse
868,871
<p>I would like to generate an HttpResponse that contains a certain string. For each of the characters in the string I have a background color I want to use. </p> <p>For simplification, let's assume I can only have shades of green in the background, and that the "background colors" data represents "level of brightness" in the green domain.</p> <p>For example, a response may be 'abcd', and my "background colors" data may be:</p> <pre><code>[0.0, 1.0, 0.5, 1.0] </code></pre> <p>This would mean the first character 'a' needs to have a background of dark green (e.g. 004000), the second character 'b' needs to have a background of bright green (e.g. 00ff00), the third character 'c' needs to have a "middle" brightness (e.g. 00A000), and so on.</p> <p>I don't want to use a template but rather just return "plain text" response. Is that possible?</p> <p>If not - what would be the simplest template I could use for that?</p> <p>Thanks</p>
1
2009-05-15T14:04:30Z
869,031
<p>you can use something like this to generate html in the django view itself and return it as text/html</p> <pre><code>data = "abcd" greenShades = [0.0, 1.0, 0.5, 1.0] out = "&lt;html&gt;" for d, clrG in zip(data,greenShades): out +=""" &lt;div style="background-color:RGB(0,%s,0);color:white;"&gt;%s&lt;/div&gt; """%(int(clrG*255), d) out += "&lt;/html&gt;" </code></pre>
2
2009-05-15T14:30:08Z
[ "python", "html", "django", "colors" ]
HTML Newbie Question: Colored Background for Characters in Django HttpResponse
868,871
<p>I would like to generate an HttpResponse that contains a certain string. For each of the characters in the string I have a background color I want to use. </p> <p>For simplification, let's assume I can only have shades of green in the background, and that the "background colors" data represents "level of brightness" in the green domain.</p> <p>For example, a response may be 'abcd', and my "background colors" data may be:</p> <pre><code>[0.0, 1.0, 0.5, 1.0] </code></pre> <p>This would mean the first character 'a' needs to have a background of dark green (e.g. 004000), the second character 'b' needs to have a background of bright green (e.g. 00ff00), the third character 'c' needs to have a "middle" brightness (e.g. 00A000), and so on.</p> <p>I don't want to use a template but rather just return "plain text" response. Is that possible?</p> <p>If not - what would be the simplest template I could use for that?</p> <p>Thanks</p>
1
2009-05-15T14:04:30Z
869,071
<p>Your best bet here would be to use the <code>span</code> element, as well as a stylesheet. If you don't want to use a template, then you'd have to render this inline. An example: </p> <pre><code>string_data = 'asdf' color_data = [0.0, 1.0, 0.5, 1.0] response = [] for char, color in zip(string_data, color_data): response.append('&lt;span style="background-color:rgb(0,%s,0);"&gt;%s&lt;/span&gt;' % (color, char) response = HttpResponse(''.join(response)) </code></pre> <p>I'd imagine that this could also be done in a template if you wanted.</p>
1
2009-05-15T14:35:16Z
[ "python", "html", "django", "colors" ]
cx_oracle and oracle 7?
868,888
<p>At work we have Oracle 7. I would like to use python to access the DB. Has anyone done that or knows how to do it? I have Windows XP, Python 2.6 and the cx_oracle version for python 2.6</p> <p>However, when I try to import cx_oracle i get the following error:</p> <pre><code>ImportError: DLL load failed the module could not be found </code></pre> <p>Any help is appreciated!</p> <p>Matt</p>
4
2009-05-15T14:09:08Z
896,416
<p>cx_Oracle is currently only being provided with linkage to the 9i, 10g, and 11i clients. Install one of these clients and configure it to connect to the Oracle 7 database using the proper ORACLE_SID.</p>
2
2009-05-22T04:58:09Z
[ "python", "cx-oracle" ]
cx_oracle and oracle 7?
868,888
<p>At work we have Oracle 7. I would like to use python to access the DB. Has anyone done that or knows how to do it? I have Windows XP, Python 2.6 and the cx_oracle version for python 2.6</p> <p>However, when I try to import cx_oracle i get the following error:</p> <pre><code>ImportError: DLL load failed the module could not be found </code></pre> <p>Any help is appreciated!</p> <p>Matt</p>
4
2009-05-15T14:09:08Z
896,470
<p>I was running into that same problem at work. I finally dropped trying to use cx_Oracle and went with <a href="http://adodbapi.sourceforge.net/" rel="nofollow">adodbapi</a>. It worked with Oracle 8.</p>
0
2009-05-22T05:20:45Z
[ "python", "cx-oracle" ]
cx_oracle and oracle 7?
868,888
<p>At work we have Oracle 7. I would like to use python to access the DB. Has anyone done that or knows how to do it? I have Windows XP, Python 2.6 and the cx_oracle version for python 2.6</p> <p>However, when I try to import cx_oracle i get the following error:</p> <pre><code>ImportError: DLL load failed the module could not be found </code></pre> <p>Any help is appreciated!</p> <p>Matt</p>
4
2009-05-15T14:09:08Z
906,577
<p>If you have ODBC configured then you can use it. It is available with ActivePython or as win32 extensions. You will obtain connection with:</p> <pre><code>connection = odbc.odbc('db_alias/user/passwd') </code></pre> <p>Optionally you can use Jython and thin JDBC client. Instalation of client is not required. With Jython you have access to db via db url:</p> <pre><code>db = DriverManager.getConnection(db_url, usr, passwd) </code></pre> <p>where db_url looks like:</p> <pre><code>jdbc:oracle:thin:user/passwd@machine_ip:port:dbname </code></pre>
0
2009-05-25T12:39:19Z
[ "python", "cx-oracle" ]
cx_oracle and oracle 7?
868,888
<p>At work we have Oracle 7. I would like to use python to access the DB. Has anyone done that or knows how to do it? I have Windows XP, Python 2.6 and the cx_oracle version for python 2.6</p> <p>However, when I try to import cx_oracle i get the following error:</p> <pre><code>ImportError: DLL load failed the module could not be found </code></pre> <p>Any help is appreciated!</p> <p>Matt</p>
4
2009-05-15T14:09:08Z
9,177,179
<p>Make sure you have the location of the oracle .dll (o files set in your PATH environment variable. The location containing oci.dll should suffice.</p>
2
2012-02-07T13:34:34Z
[ "python", "cx-oracle" ]
Why is looping over range() in Python faster than using a while loop?
869,229
<p>The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.</p> <p>Loop 1:</p> <pre><code>int i = 0 while i &lt; 100000000: i += 1 </code></pre> <p>Loop 2:</p> <pre><code>for n in range(0,100000000): pass </code></pre> <p>Why is the first loop so much slower? I know it's a trivial example but it's piqued my interest. Is there something special about the range() function that makes it more efficient than incrementing a variable the same way?</p>
49
2009-05-15T15:06:41Z
869,274
<p>Because you are running more often in code written in C in the interpretor. i.e. i+=1 is in Python, so slow (comparatively), whereas range(0,...) is one C call the for loop will execute mostly in C too.</p>
3
2009-05-15T15:15:04Z
[ "python", "performance", "benchmarking" ]
Why is looping over range() in Python faster than using a while loop?
869,229
<p>The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.</p> <p>Loop 1:</p> <pre><code>int i = 0 while i &lt; 100000000: i += 1 </code></pre> <p>Loop 2:</p> <pre><code>for n in range(0,100000000): pass </code></pre> <p>Why is the first loop so much slower? I know it's a trivial example but it's piqued my interest. Is there something special about the range() function that makes it more efficient than incrementing a variable the same way?</p>
49
2009-05-15T15:06:41Z
869,295
<p><code>range()</code> is implemented in C, whereas <code>i += 1</code> is interpreted.</p> <p>Using <code>xrange()</code> could make it even faster for large numbers. Starting with Python 3.0 <code>range()</code> is the same as previously <code>xrange()</code>.</p>
22
2009-05-15T15:18:02Z
[ "python", "performance", "benchmarking" ]
Why is looping over range() in Python faster than using a while loop?
869,229
<p>The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.</p> <p>Loop 1:</p> <pre><code>int i = 0 while i &lt; 100000000: i += 1 </code></pre> <p>Loop 2:</p> <pre><code>for n in range(0,100000000): pass </code></pre> <p>Why is the first loop so much slower? I know it's a trivial example but it's piqued my interest. Is there something special about the range() function that makes it more efficient than incrementing a variable the same way?</p>
49
2009-05-15T15:06:41Z
869,347
<p>see the disassembly of python byte code, you may get a more concrete idea</p> <p>use while loop:</p> <pre><code>1 0 LOAD_CONST 0 (0) 3 STORE_NAME 0 (i) 2 6 SETUP_LOOP 28 (to 37) &gt;&gt; 9 LOAD_NAME 0 (i) # &lt;- 12 LOAD_CONST 1 (100000000) # &lt;- 15 COMPARE_OP 0 (&lt;) # &lt;- 18 JUMP_IF_FALSE 14 (to 35) # &lt;- 21 POP_TOP # &lt;- 3 22 LOAD_NAME 0 (i) # &lt;- 25 LOAD_CONST 2 (1) # &lt;- 28 INPLACE_ADD # &lt;- 29 STORE_NAME 0 (i) # &lt;- 32 JUMP_ABSOLUTE 9 # &lt;- &gt;&gt; 35 POP_TOP 36 POP_BLOCK </code></pre> <p>The loop body has 10 op</p> <p>use range:</p> <pre><code>1 0 SETUP_LOOP 23 (to 26) 3 LOAD_NAME 0 (range) 6 LOAD_CONST 0 (0) 9 LOAD_CONST 1 (100000000) 12 CALL_FUNCTION 2 15 GET_ITER &gt;&gt; 16 FOR_ITER 6 (to 25) # &lt;- 19 STORE_NAME 1 (n) # &lt;- 2 22 JUMP_ABSOLUTE 16 # &lt;- &gt;&gt; 25 POP_BLOCK &gt;&gt; 26 LOAD_CONST 2 (None) 29 RETURN_VALUE </code></pre> <p>The loop body has 3 op</p> <p>The time to run C code is much shorter than intepretor and can be ignored.</p>
93
2009-05-15T15:27:07Z
[ "python", "performance", "benchmarking" ]
Why is looping over range() in Python faster than using a while loop?
869,229
<p>The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.</p> <p>Loop 1:</p> <pre><code>int i = 0 while i &lt; 100000000: i += 1 </code></pre> <p>Loop 2:</p> <pre><code>for n in range(0,100000000): pass </code></pre> <p>Why is the first loop so much slower? I know it's a trivial example but it's piqued my interest. Is there something special about the range() function that makes it more efficient than incrementing a variable the same way?</p>
49
2009-05-15T15:06:41Z
869,414
<p>Most of Python's built in method calls are run as C code. Code that has to be interpreted is much slower. In terms of memory efficiency and execution speed the difference is gigantic. The python internals have been optimized to the extreme, and it's best to take advantage of those optimizations. </p>
1
2009-05-15T15:39:43Z
[ "python", "performance", "benchmarking" ]
Why is looping over range() in Python faster than using a while loop?
869,229
<p>The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.</p> <p>Loop 1:</p> <pre><code>int i = 0 while i &lt; 100000000: i += 1 </code></pre> <p>Loop 2:</p> <pre><code>for n in range(0,100000000): pass </code></pre> <p>Why is the first loop so much slower? I know it's a trivial example but it's piqued my interest. Is there something special about the range() function that makes it more efficient than incrementing a variable the same way?</p>
49
2009-05-15T15:06:41Z
16,072,743
<p>It must be said that there is a lot of object creation and destruction going on with the while loop.</p> <pre><code>i += 1 </code></pre> <p>is the same as:</p> <pre><code>i = i + 1 </code></pre> <p>But because Python ints are immutable, it doesn't modify the existing object; rather it creates a brand new object with a new value. It's basically:</p> <pre><code>i = new int(i + 1) # Using C++ or Java-ish syntax </code></pre> <p>The garbage collector will also have a large amount of cleanup to do. "Object creation is expensive".</p>
3
2013-04-18T00:54:44Z
[ "python", "performance", "benchmarking" ]
Running unittest.main() from a module?
869,519
<p>I wrote a little function that dynamically defines unittest.TestCase classes (trivial version below).</p> <p>When I moved it out of the same source file into its own module, I can't figure out how to get unittest to discover the new classes. Calling unittest.main() from either file doesn't execute any tests.</p> <p><code>factory.py</code>:</p> <pre><code>import unittest _testnum = 0 def test_factory(a, b): global _testnum testname = 'dyntest' + str(_testnum) globals()[testname] = type(testname, (unittest.TestCase,), {'testme': lambda self: self.assertEqual(a, b)}) _testnum += 1 def finish(): unittest.main() </code></pre> <p><code>someotherfile.py</code>:</p> <pre><code>from factory import test_factory, finish test_factory(1, 1) test_factory(1, 2) if __name__ == '__main__': finish() </code></pre> <p>Output:</p> <pre><code>---------------------------------------------------------------------- Ran 0 tests in 0.000s OK </code></pre> <p>So it doesn't execute any tests.</p> <p>Note that keeping it all in the same file works as expected:</p> <pre><code>import unittest _testnum = 0 def test_factory(a, b): global _testnum testname = 'dyntest' + str(_testnum) globals()[testname] = type(testname, (unittest.TestCase,), {'testme': lambda self: self.assertEqual(a, b)}) _testnum += 1 test_factory(1, 1) test_factory(1, 2) if __name__ == '__main__': unittest.main() </code></pre> <p>Output (as expected):</p> <pre><code>.F ====================================================================== FAIL: testme (__main__.dyntest1) ---------------------------------------------------------------------- Traceback (most recent call last): File "partb.py", line 11, in &lt;lambda&gt; globals()[testname] = type(testname, (unittest.TestCase,), {'testme': lambda self: self.assertEqual(a, b)}) AssertionError: 1 != 2 ---------------------------------------------------------------------- Ran 2 tests in 0.008s FAILED (failures=1) </code></pre> <p>How I use my test_factory() function such that I can execute all of the TestCase objects it defines from a separate source file?</p>
1
2009-05-15T15:57:58Z
869,671
<p>The general idea (what unittest.main does for you) is:</p> <pre><code>suite = unittest.TestLoader().loadTestsFromTestCase(SomeTestCase) unittest.TextTestRunner(verbosity=2).run(suite) </code></pre> <p>as per <a href="http://docs.python.org/library/unittest.html?highlight=unittest#module-unittest">http://docs.python.org/library/unittest.html?highlight=unittest#module-unittest</a> . Your test cases are hidden in <code>globals()</code> by the <code>test_factory</code> function, so just do a <code>dir()</code>, find the globals that are instances of <code>unittest.TestCase</code> (or ones with names starting with <code>'dyntest'</code>, etc), and just build your suite that way and run it.</p>
8
2009-05-15T16:31:53Z
[ "python", "unit-testing" ]
Running unittest.main() from a module?
869,519
<p>I wrote a little function that dynamically defines unittest.TestCase classes (trivial version below).</p> <p>When I moved it out of the same source file into its own module, I can't figure out how to get unittest to discover the new classes. Calling unittest.main() from either file doesn't execute any tests.</p> <p><code>factory.py</code>:</p> <pre><code>import unittest _testnum = 0 def test_factory(a, b): global _testnum testname = 'dyntest' + str(_testnum) globals()[testname] = type(testname, (unittest.TestCase,), {'testme': lambda self: self.assertEqual(a, b)}) _testnum += 1 def finish(): unittest.main() </code></pre> <p><code>someotherfile.py</code>:</p> <pre><code>from factory import test_factory, finish test_factory(1, 1) test_factory(1, 2) if __name__ == '__main__': finish() </code></pre> <p>Output:</p> <pre><code>---------------------------------------------------------------------- Ran 0 tests in 0.000s OK </code></pre> <p>So it doesn't execute any tests.</p> <p>Note that keeping it all in the same file works as expected:</p> <pre><code>import unittest _testnum = 0 def test_factory(a, b): global _testnum testname = 'dyntest' + str(_testnum) globals()[testname] = type(testname, (unittest.TestCase,), {'testme': lambda self: self.assertEqual(a, b)}) _testnum += 1 test_factory(1, 1) test_factory(1, 2) if __name__ == '__main__': unittest.main() </code></pre> <p>Output (as expected):</p> <pre><code>.F ====================================================================== FAIL: testme (__main__.dyntest1) ---------------------------------------------------------------------- Traceback (most recent call last): File "partb.py", line 11, in &lt;lambda&gt; globals()[testname] = type(testname, (unittest.TestCase,), {'testme': lambda self: self.assertEqual(a, b)}) AssertionError: 1 != 2 ---------------------------------------------------------------------- Ran 2 tests in 0.008s FAILED (failures=1) </code></pre> <p>How I use my test_factory() function such that I can execute all of the TestCase objects it defines from a separate source file?</p>
1
2009-05-15T15:57:58Z
869,770
<p>By default, unittest.main() looks for unit TestCase objects in the main module. The test_factory creates the TestCase objects in its own module. That's why moving it outside of the main module causes the behavior you see.</p> <p>Try:</p> <pre><code>def finish(): unittest.main(module=__name__) </code></pre>
6
2009-05-15T16:55:28Z
[ "python", "unit-testing" ]
How do I disassemble a Python script?
869,586
<p>Earlier today, I <a href="http://stackoverflow.com/questions/869229/why-is-looping-over-range-in-python-faster-than-using-a-while-loop">asked a question</a> about the way Python handles certain kinds of loops. One of the answers contained disassembled versions of my examples.</p> <p>I'd like to know more. How can I disassemble my own Python code?</p>
9
2009-05-15T16:12:02Z
869,600
<p>Look at the <a href="http://docs.python.org/library/dis.html">dis</a> module:</p> <pre><code>def myfunc(alist): return len(alist) &gt;&gt;&gt; dis.dis(myfunc) 2 0 LOAD_GLOBAL 0 (len) 3 LOAD_FAST 0 (alist) 6 CALL_FUNCTION 1 9 RETURN_VALUE </code></pre>
12
2009-05-15T16:14:49Z
[ "python", "debugging", "reverse-engineering" ]
How do I disassemble a Python script?
869,586
<p>Earlier today, I <a href="http://stackoverflow.com/questions/869229/why-is-looping-over-range-in-python-faster-than-using-a-while-loop">asked a question</a> about the way Python handles certain kinds of loops. One of the answers contained disassembled versions of my examples.</p> <p>I'd like to know more. How can I disassemble my own Python code?</p>
9
2009-05-15T16:12:02Z
869,640
<p>Use the <code>dis</code> module from the Python standard library (<code>import dis</code> e.g. in an interactive interpreter, then <code>dis.dis</code> any function you care about!-).</p>
2
2009-05-15T16:24:53Z
[ "python", "debugging", "reverse-engineering" ]
How do I disassemble a Python script?
869,586
<p>Earlier today, I <a href="http://stackoverflow.com/questions/869229/why-is-looping-over-range-in-python-faster-than-using-a-while-loop">asked a question</a> about the way Python handles certain kinds of loops. One of the answers contained disassembled versions of my examples.</p> <p>I'd like to know more. How can I disassemble my own Python code?</p>
9
2009-05-15T16:12:02Z
869,970
<p>Besides using <code>dis</code> as module, you can also run it as command line tool</p> <p>For example, on windows you can run:</p> <pre><code>c:\Python25\Lib\dis.py test.py </code></pre> <p>And it will output the disassembed result to console.</p>
2
2009-05-15T17:38:30Z
[ "python", "debugging", "reverse-engineering" ]
Downloading file using post method and python
869,679
<p>I need a little help getting a tar file to download from a website. The website is set up as a form where you pick the file you want and click submit and then the download windows opens up for you to pick the location.</p> <p>I'm trying to do the same thing in code (so I don't have to manual pick each file). So far I have gotten python 2.5.2 to return a response but its in a <code>socket._fileobject</code> and I'm now not sure how to convert that into a file on my computer.</p> <p>Below is output of the python shell and the steps I have taken</p> <pre><code>Python 2.5.2 on win32 IDLE 1.2.2 &gt;&gt;&gt; import urllib &gt;&gt;&gt; import urllib2 &gt;&gt;&gt; url = 'http://website/getdata.php' &gt;&gt;&gt; values = {'data[]': 'filex.tar'} &gt;&gt;&gt; data = urllib.urlencode(values) &gt;&gt;&gt; req = urllib2.Request(url,data) &gt;&gt;&gt; response = urllib2.urlopen(req) &gt;&gt;&gt; response addinfourl at 22250280 whose fp = &lt;socket._fileobject object at 0x01534570 &gt;&gt;&gt; response.fp socket._fileobject object at 0x01534570 </code></pre>
2
2009-05-15T16:33:32Z
869,703
<p>Append this:</p> <pre><code>myfile = open('myfile.tar', 'wb') shutil.copyfileobj(response.fp, myfile) myfile.close() </code></pre> <p><code>response.fp</code> is a file-like object that you can read from, just like an open file. <code>shutil.copyfileobj()</code> is a simple function that reads from one file-like object and writes its contents to another.</p>
2
2009-05-15T16:38:53Z
[ "python", "urllib2" ]
Populating a list/array by index in Python?
869,778
<p>Is this possible:</p> <pre><code>myList = [] myList[12] = 'a' myList[22] = 'b' myList[32] = 'c' myList[42] = 'd' </code></pre> <p>When I try, I get:</p> <pre><code># IndexError: list assignment index out of range # </code></pre>
20
2009-05-15T16:57:25Z
869,805
<p>For a "sparse list" you could use a <code>dict</code> instead:</p> <pre><code>mylist = {} mylist[12] = 'a' </code></pre> <p>etc. If you want an actual list (initialize it with <code>[]</code>, <em>not</em> <code>()</code>, of course!-) you need to fill the un-set slots to _some_thing, e.g. <code>None</code>, by a little auxiliary function or by subclassing <code>list</code>.</p>
22
2009-05-15T17:01:13Z
[ "python", "list" ]
Populating a list/array by index in Python?
869,778
<p>Is this possible:</p> <pre><code>myList = [] myList[12] = 'a' myList[22] = 'b' myList[32] = 'c' myList[42] = 'd' </code></pre> <p>When I try, I get:</p> <pre><code># IndexError: list assignment index out of range # </code></pre>
20
2009-05-15T16:57:25Z
869,818
<p>You'll have to pre-fill it with something (e.g. <code>0</code> or <code>None</code>) before you can index it:</p> <pre><code>myList = [None] * 100 # Create list of 100 'None's myList[12] = 'a' # etc. </code></pre> <p>Alternatively, use a dict instead of a list, as <a href="http://stackoverflow.com/questions/869778/populating-a-list-array-by-index-in-python/869805#869805">Alex Martelli suggested</a>.</p>
37
2009-05-15T17:03:29Z
[ "python", "list" ]