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
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)? </p>
73
2009-04-27T14:31:00Z
33,218,555
<p>The value of <a href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHASHSEED" rel="nofollow">PYTHONHASHSEED</a> might be used to initialize the hash values.</p> <p>Try:</p> <pre><code>PYTHONHASHSEED python -c 'print(hash('http://stackoverflow.com'))' </code></pre>
1
2015-10-19T15:39:15Z
[ "python", "google-app-engine", "hash" ]
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I have a hash function which will give me same results across different platforms (Windows, Linux, Mac)? </p>
73
2009-04-27T14:31:00Z
33,763,349
<p>Most answers suggest this is because of different platforms, but there is more to it. From <a href="https://docs.python.org/3.5/reference/datamodel.html#object.__hash__" rel="nofollow">the documentation of <code>object.__hash__(self)</code></a>:</p> <blockquote> <p>By default, the <code>__hash__()</code> values of <code>str</code>, <code>bytes</code> and <code>datetime</code> objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.</p> <p>This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n²) complexity. See <a href="http://www.ocert.org/advisories/ocert-2011-003.html" rel="nofollow">http://www.ocert.org/advisories/ocert-2011-003.html</a> for details.</p> <p>Changing hash values affects the iteration order of <code>dicts</code>, <code>sets</code> and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).</p> </blockquote> <p>Even running on the same machine will yield varying results across invocations:</p> <pre><code>$ python -c "print(hash('http://stackoverflow.com'))" -3455286212422042986 $ python -c "print(hash('http://stackoverflow.com'))" -6940441840934557333 </code></pre> <p>While:</p> <pre><code>$ python -c "print(hash((1,2,3)))" 2528502973977326415 $ python -c "print(hash((1,2,3)))" 2528502973977326415 </code></pre> <hr> <p>See also the environment variable <a href="https://docs.python.org/3.5/using/cmdline.html#envvar-PYTHONHASHSEED" rel="nofollow"><code>PYTHONHASHSEED</code></a>:</p> <blockquote> <p>If this variable is not set or set to <code>random</code>, a random value is used to seed the hashes of <code>str</code>, <code>bytes</code> and <code>datetime</code> objects.</p> <p>If <code>PYTHONHASHSEED</code> is set to an integer value, it is used as a fixed seed for generating the <code>hash()</code> of the types covered by the hash randomization.</p> <p>Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of python processes to share hash values.</p> <p>The integer must be a decimal number in the range <code>[0, 4294967295]</code>. Specifying the value <code>0</code> will disable hash randomization.</p> </blockquote> <p>For example:</p> <pre><code>$ export PYTHONHASHSEED=0 $ python -c "print(hash('http://stackoverflow.com'))" -5843046192888932305 $ python -c "print(hash('http://stackoverflow.com'))" -5843046192888932305 </code></pre>
9
2015-11-17T17:29:46Z
[ "python", "google-app-engine", "hash" ]
SQLAlchemy - MappedCollection problem
793,848
<p>I have some problems with setting up the dictionary collection in Python's SQLAlchemy:</p> <p>I am using declarative definition of tables. I have <code>Item</code> table in 1:N relation with <code>Record</code> table. I set up the relation using the following code:</p> <pre><code>_Base = declarative_base() class Record(_Base): __tablename__ = 'records' item_id = Column(String(M_ITEM_ID), ForeignKey('items.id')) id = Column(String(M_RECORD_ID), primary_key=True) uri = Column(String(M_RECORD_URI)) name = Column(String(M_RECORD_NAME)) class Item(_Base): __tablename__ = 'items' id = Column(String(M_ITEM_ID), primary_key=True) records = relation(Record, collection_class=column_mapped_collection(Record.name), backref='item') </code></pre> <p>Now I want to work with the <code>Item</code>s and <code>Record</code>s. Let's create some objects:</p> <pre><code>i1 = Item(id='id1') r = Record(id='mujrecord') </code></pre> <p>And now I want to associate these objects using the following code:</p> <pre><code>i1.records['source_wav'] = r </code></pre> <p>but the <code>Record r</code> doesn't have set the <code>name</code> attribute (the foreign key). Is there any solution how to automatically ensure this? (I know that setting the foreign key during the <code>Record</code> creation works, but it doesn't sound good for me).</p> <p>Many thanks</p>
3
2009-04-27T14:46:10Z
836,855
<p>You have:</p> <pre><code>backref='item' </code></pre> <p>Is this a typo for </p> <pre><code>backref='name' </code></pre> <p>?</p>
0
2009-05-07T20:29:12Z
[ "python", "sqlalchemy" ]
SQLAlchemy - MappedCollection problem
793,848
<p>I have some problems with setting up the dictionary collection in Python's SQLAlchemy:</p> <p>I am using declarative definition of tables. I have <code>Item</code> table in 1:N relation with <code>Record</code> table. I set up the relation using the following code:</p> <pre><code>_Base = declarative_base() class Record(_Base): __tablename__ = 'records' item_id = Column(String(M_ITEM_ID), ForeignKey('items.id')) id = Column(String(M_RECORD_ID), primary_key=True) uri = Column(String(M_RECORD_URI)) name = Column(String(M_RECORD_NAME)) class Item(_Base): __tablename__ = 'items' id = Column(String(M_ITEM_ID), primary_key=True) records = relation(Record, collection_class=column_mapped_collection(Record.name), backref='item') </code></pre> <p>Now I want to work with the <code>Item</code>s and <code>Record</code>s. Let's create some objects:</p> <pre><code>i1 = Item(id='id1') r = Record(id='mujrecord') </code></pre> <p>And now I want to associate these objects using the following code:</p> <pre><code>i1.records['source_wav'] = r </code></pre> <p>but the <code>Record r</code> doesn't have set the <code>name</code> attribute (the foreign key). Is there any solution how to automatically ensure this? (I know that setting the foreign key during the <code>Record</code> creation works, but it doesn't sound good for me).</p> <p>Many thanks</p>
3
2009-04-27T14:46:10Z
884,728
<p>You want something like this:</p> <pre><code>from sqlalchemy.orm import validates class Item(_Base): [...] @validates('records') def validate_record(self, key, record): assert record.name is not None, "Record fails validation, must have a name" return record </code></pre> <p>With this, you get the desired validation:</p> <pre><code>&gt;&gt;&gt; i1 = Item(id='id1') &gt;&gt;&gt; r = Record(id='mujrecord') &gt;&gt;&gt; i1.records['source_wav'] = r Traceback (most recent call last): [...] AssertionError: Record fails validation, must have a name &gt;&gt;&gt; r.name = 'foo' &gt;&gt;&gt; i1.records['source_wav'] = r &gt;&gt;&gt; </code></pre>
2
2009-05-19T19:58:56Z
[ "python", "sqlalchemy" ]
SQLAlchemy - MappedCollection problem
793,848
<p>I have some problems with setting up the dictionary collection in Python's SQLAlchemy:</p> <p>I am using declarative definition of tables. I have <code>Item</code> table in 1:N relation with <code>Record</code> table. I set up the relation using the following code:</p> <pre><code>_Base = declarative_base() class Record(_Base): __tablename__ = 'records' item_id = Column(String(M_ITEM_ID), ForeignKey('items.id')) id = Column(String(M_RECORD_ID), primary_key=True) uri = Column(String(M_RECORD_URI)) name = Column(String(M_RECORD_NAME)) class Item(_Base): __tablename__ = 'items' id = Column(String(M_ITEM_ID), primary_key=True) records = relation(Record, collection_class=column_mapped_collection(Record.name), backref='item') </code></pre> <p>Now I want to work with the <code>Item</code>s and <code>Record</code>s. Let's create some objects:</p> <pre><code>i1 = Item(id='id1') r = Record(id='mujrecord') </code></pre> <p>And now I want to associate these objects using the following code:</p> <pre><code>i1.records['source_wav'] = r </code></pre> <p>but the <code>Record r</code> doesn't have set the <code>name</code> attribute (the foreign key). Is there any solution how to automatically ensure this? (I know that setting the foreign key during the <code>Record</code> creation works, but it doesn't sound good for me).</p> <p>Many thanks</p>
3
2009-04-27T14:46:10Z
890,005
<p>I can't comment yet, so I'm just going to write this as a separate answer:</p> <pre>from sqlalchemy.orm import validates class Item(_Base): [...] @validates('records') def validate_record(self, key, record): record.name=key return record </pre> <p>This is basically a copy of Gunnlaugur's answer but abusing the validates decorator to do something more useful than exploding.</p>
1
2009-05-20T20:15:07Z
[ "python", "sqlalchemy" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?</p> <p>In the first case, I get very low coupling, but then I will probably have to instantiate a Coord3D object with the obtained values anyway, although outside of the file class. In the second case, I will have the file class tightly coupled with the Coord3D class.</p> <p>Please note that I think there's not a huge difference between the two solutions, but I would like to read your answer and the reason behind it.</p> <p><hr /></p> <p><strong>Edit</strong>: to recap the answers I got until now, it looks like there's no clearcut choice. It has been said (appropriately) that python is not Java, and you don't need a specialized class for everything just because you need it by language architecture. In my case, however, I have the following conditions:</p> <ol> <li>I am working on a library, where the Coord3D object is used as is. Using it would increase the cohesiveness of my library, as the data types will be uniformly used.</li> <li>The Coord3D object has state and behavior. Indeed, the Coord3D object aggregate the coordinates and the units in a single entity. Operations among Coord3D objects will keep into account the potentially different units, and act accordingly.</li> <li>I can put centralize control code into the Coord3D class instantiation to refuse, for example, arrays of length 4, or non units. If I use a tuple, I cannot perform this check. Moreover, if a method accepts a Coord3D, is sort of guaranteed that it's well formed upfront (you could be bold and check for isinstance, or check the interface). A tuple can contain invalid data. Although python approach to error handling is done where the trouble happen, a class preventing me to have an xyz coordinate made out of three strings is somehow beneficial (correct me if wrong, please)</li> </ol> <p>On the other hand, using a tuple has the following advantages:</p> <ol> <li>Less occupation of resources, quite critical in case of huge </li> <li>Simpler design. More classes means more complex design. A tuple is a standard data type which is well understood and can be unpacked easily. A personalized class is not.</li> <li>Using a tuple, the XYZFile class is totally decoupled from the rest of the library (because it does not use the Coord3D object). This means that it can be reused totally as an independent entity.</li> </ol> <p>further comments very welcome!</p>
11
2009-04-27T15:48:48Z
794,152
<p>If it's only going to be used in your application, and if you're going to create a <code>Coord3D</code> instance with the values anyway, I'd just return a <code>Coord3D</code> instance to save you the effort. If, however, you have any interest in making this portable/general, return a tuple. It'll be easy to create a <code>Coord3D</code> anyway, using</p> <pre><code>c3d = Coord3D(*getCoordinate(index)) </code></pre> <p>(assuming your constructor is <code>Coord3D.__init__(self, x, y, z)</code>)</p>
1
2009-04-27T15:55:11Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?</p> <p>In the first case, I get very low coupling, but then I will probably have to instantiate a Coord3D object with the obtained values anyway, although outside of the file class. In the second case, I will have the file class tightly coupled with the Coord3D class.</p> <p>Please note that I think there's not a huge difference between the two solutions, but I would like to read your answer and the reason behind it.</p> <p><hr /></p> <p><strong>Edit</strong>: to recap the answers I got until now, it looks like there's no clearcut choice. It has been said (appropriately) that python is not Java, and you don't need a specialized class for everything just because you need it by language architecture. In my case, however, I have the following conditions:</p> <ol> <li>I am working on a library, where the Coord3D object is used as is. Using it would increase the cohesiveness of my library, as the data types will be uniformly used.</li> <li>The Coord3D object has state and behavior. Indeed, the Coord3D object aggregate the coordinates and the units in a single entity. Operations among Coord3D objects will keep into account the potentially different units, and act accordingly.</li> <li>I can put centralize control code into the Coord3D class instantiation to refuse, for example, arrays of length 4, or non units. If I use a tuple, I cannot perform this check. Moreover, if a method accepts a Coord3D, is sort of guaranteed that it's well formed upfront (you could be bold and check for isinstance, or check the interface). A tuple can contain invalid data. Although python approach to error handling is done where the trouble happen, a class preventing me to have an xyz coordinate made out of three strings is somehow beneficial (correct me if wrong, please)</li> </ol> <p>On the other hand, using a tuple has the following advantages:</p> <ol> <li>Less occupation of resources, quite critical in case of huge </li> <li>Simpler design. More classes means more complex design. A tuple is a standard data type which is well understood and can be unpacked easily. A personalized class is not.</li> <li>Using a tuple, the XYZFile class is totally decoupled from the rest of the library (because it does not use the Coord3D object). This means that it can be reused totally as an independent entity.</li> </ol> <p>further comments very welcome!</p>
11
2009-04-27T15:48:48Z
794,157
<p>I've asked myself the same question, albeit while doing 2D geometry stuff.</p> <p>The answer I found for myself was that if I was planning to write a larger library, with more functions and whatnot, go ahead and return the Point, or in your case the Coord3D object. If it's just a hacky implementation, the tuple will get you going faster. In the end, it's just what you're going to do with it, and is it worth the effort.</p>
1
2009-04-27T15:55:40Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?</p> <p>In the first case, I get very low coupling, but then I will probably have to instantiate a Coord3D object with the obtained values anyway, although outside of the file class. In the second case, I will have the file class tightly coupled with the Coord3D class.</p> <p>Please note that I think there's not a huge difference between the two solutions, but I would like to read your answer and the reason behind it.</p> <p><hr /></p> <p><strong>Edit</strong>: to recap the answers I got until now, it looks like there's no clearcut choice. It has been said (appropriately) that python is not Java, and you don't need a specialized class for everything just because you need it by language architecture. In my case, however, I have the following conditions:</p> <ol> <li>I am working on a library, where the Coord3D object is used as is. Using it would increase the cohesiveness of my library, as the data types will be uniformly used.</li> <li>The Coord3D object has state and behavior. Indeed, the Coord3D object aggregate the coordinates and the units in a single entity. Operations among Coord3D objects will keep into account the potentially different units, and act accordingly.</li> <li>I can put centralize control code into the Coord3D class instantiation to refuse, for example, arrays of length 4, or non units. If I use a tuple, I cannot perform this check. Moreover, if a method accepts a Coord3D, is sort of guaranteed that it's well formed upfront (you could be bold and check for isinstance, or check the interface). A tuple can contain invalid data. Although python approach to error handling is done where the trouble happen, a class preventing me to have an xyz coordinate made out of three strings is somehow beneficial (correct me if wrong, please)</li> </ol> <p>On the other hand, using a tuple has the following advantages:</p> <ol> <li>Less occupation of resources, quite critical in case of huge </li> <li>Simpler design. More classes means more complex design. A tuple is a standard data type which is well understood and can be unpacked easily. A personalized class is not.</li> <li>Using a tuple, the XYZFile class is totally decoupled from the rest of the library (because it does not use the Coord3D object). This means that it can be reused totally as an independent entity.</li> </ol> <p>further comments very welcome!</p>
11
2009-04-27T15:48:48Z
794,183
<p>If other people (aside form yourself) will be using this class, it seems to me that returning an object would encourage some kind of uniformity in data types. If the Coord3D class has a method or property to access these coordinates as a tuple, then that still gives them that option, should they need it:</p> <pre><code># get the object coord_obj = my_obj.getCoordinate(my_index) # get the tuple (for example, via a property named "coords") coord_tup = my_obj.getCoordinate(my_index).coords </code></pre>
2
2009-04-27T16:03:08Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?</p> <p>In the first case, I get very low coupling, but then I will probably have to instantiate a Coord3D object with the obtained values anyway, although outside of the file class. In the second case, I will have the file class tightly coupled with the Coord3D class.</p> <p>Please note that I think there's not a huge difference between the two solutions, but I would like to read your answer and the reason behind it.</p> <p><hr /></p> <p><strong>Edit</strong>: to recap the answers I got until now, it looks like there's no clearcut choice. It has been said (appropriately) that python is not Java, and you don't need a specialized class for everything just because you need it by language architecture. In my case, however, I have the following conditions:</p> <ol> <li>I am working on a library, where the Coord3D object is used as is. Using it would increase the cohesiveness of my library, as the data types will be uniformly used.</li> <li>The Coord3D object has state and behavior. Indeed, the Coord3D object aggregate the coordinates and the units in a single entity. Operations among Coord3D objects will keep into account the potentially different units, and act accordingly.</li> <li>I can put centralize control code into the Coord3D class instantiation to refuse, for example, arrays of length 4, or non units. If I use a tuple, I cannot perform this check. Moreover, if a method accepts a Coord3D, is sort of guaranteed that it's well formed upfront (you could be bold and check for isinstance, or check the interface). A tuple can contain invalid data. Although python approach to error handling is done where the trouble happen, a class preventing me to have an xyz coordinate made out of three strings is somehow beneficial (correct me if wrong, please)</li> </ol> <p>On the other hand, using a tuple has the following advantages:</p> <ol> <li>Less occupation of resources, quite critical in case of huge </li> <li>Simpler design. More classes means more complex design. A tuple is a standard data type which is well understood and can be unpacked easily. A personalized class is not.</li> <li>Using a tuple, the XYZFile class is totally decoupled from the rest of the library (because it does not use the Coord3D object). This means that it can be reused totally as an independent entity.</li> </ol> <p>further comments very welcome!</p>
11
2009-04-27T15:48:48Z
794,200
<p>The more fundamental question is "why do you have Coord3D class?" Why not just use a tuple?</p> <p>The general advice most of us give to Python n00bz is "don't invent new classes until you have to."</p> <p>Does your Coord3D have unique methods? Perhaps you need a new class. Or -- perhaps -- you only need some functions that operate on tuples.</p> <p>Does your Coord3D have changeable state? Hardly likely. An immutable tuple starts to look like a better representation than a new class.</p>
2
2009-04-27T16:07:25Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?</p> <p>In the first case, I get very low coupling, but then I will probably have to instantiate a Coord3D object with the obtained values anyway, although outside of the file class. In the second case, I will have the file class tightly coupled with the Coord3D class.</p> <p>Please note that I think there's not a huge difference between the two solutions, but I would like to read your answer and the reason behind it.</p> <p><hr /></p> <p><strong>Edit</strong>: to recap the answers I got until now, it looks like there's no clearcut choice. It has been said (appropriately) that python is not Java, and you don't need a specialized class for everything just because you need it by language architecture. In my case, however, I have the following conditions:</p> <ol> <li>I am working on a library, where the Coord3D object is used as is. Using it would increase the cohesiveness of my library, as the data types will be uniformly used.</li> <li>The Coord3D object has state and behavior. Indeed, the Coord3D object aggregate the coordinates and the units in a single entity. Operations among Coord3D objects will keep into account the potentially different units, and act accordingly.</li> <li>I can put centralize control code into the Coord3D class instantiation to refuse, for example, arrays of length 4, or non units. If I use a tuple, I cannot perform this check. Moreover, if a method accepts a Coord3D, is sort of guaranteed that it's well formed upfront (you could be bold and check for isinstance, or check the interface). A tuple can contain invalid data. Although python approach to error handling is done where the trouble happen, a class preventing me to have an xyz coordinate made out of three strings is somehow beneficial (correct me if wrong, please)</li> </ol> <p>On the other hand, using a tuple has the following advantages:</p> <ol> <li>Less occupation of resources, quite critical in case of huge </li> <li>Simpler design. More classes means more complex design. A tuple is a standard data type which is well understood and can be unpacked easily. A personalized class is not.</li> <li>Using a tuple, the XYZFile class is totally decoupled from the rest of the library (because it does not use the Coord3D object). This means that it can be reused totally as an independent entity.</li> </ol> <p>further comments very welcome!</p>
11
2009-04-27T15:48:48Z
794,208
<p>Returning an object would be the best practice and would give you a better overall software design. I would recommend doing that</p> <p>But still, keep in mind that creating/returning an object will take more processing time. It could change something if you do this operation a LOT and in that case you might need to think about it...</p>
1
2009-04-27T16:09:14Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?</p> <p>In the first case, I get very low coupling, but then I will probably have to instantiate a Coord3D object with the obtained values anyway, although outside of the file class. In the second case, I will have the file class tightly coupled with the Coord3D class.</p> <p>Please note that I think there's not a huge difference between the two solutions, but I would like to read your answer and the reason behind it.</p> <p><hr /></p> <p><strong>Edit</strong>: to recap the answers I got until now, it looks like there's no clearcut choice. It has been said (appropriately) that python is not Java, and you don't need a specialized class for everything just because you need it by language architecture. In my case, however, I have the following conditions:</p> <ol> <li>I am working on a library, where the Coord3D object is used as is. Using it would increase the cohesiveness of my library, as the data types will be uniformly used.</li> <li>The Coord3D object has state and behavior. Indeed, the Coord3D object aggregate the coordinates and the units in a single entity. Operations among Coord3D objects will keep into account the potentially different units, and act accordingly.</li> <li>I can put centralize control code into the Coord3D class instantiation to refuse, for example, arrays of length 4, or non units. If I use a tuple, I cannot perform this check. Moreover, if a method accepts a Coord3D, is sort of guaranteed that it's well formed upfront (you could be bold and check for isinstance, or check the interface). A tuple can contain invalid data. Although python approach to error handling is done where the trouble happen, a class preventing me to have an xyz coordinate made out of three strings is somehow beneficial (correct me if wrong, please)</li> </ol> <p>On the other hand, using a tuple has the following advantages:</p> <ol> <li>Less occupation of resources, quite critical in case of huge </li> <li>Simpler design. More classes means more complex design. A tuple is a standard data type which is well understood and can be unpacked easily. A personalized class is not.</li> <li>Using a tuple, the XYZFile class is totally decoupled from the rest of the library (because it does not use the Coord3D object). This means that it can be reused totally as an independent entity.</li> </ol> <p>further comments very welcome!</p>
11
2009-04-27T15:48:48Z
795,805
<p>Compromise solution: Instead of a class, make Coord3D a <a href="http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields"><code>namedtuple</code></a> and return that :-)</p> <p>Usage:</p> <pre><code>Coord3D = namedtuple('Coord3D', 'x y z') def getCoordinate(index): # do stuff, creating variables x, y, z return Coord3D(x, y, z) </code></pre> <p>The return value can be used exactly as a tuple, and has the same speed and memory properties, so you don't lose any genericity. But you can also access its values by name: if <code>c</code> is the result of <code>getCoordinate(index)</code>, then you can work with <code>c.x</code>, <code>c.y</code>, etc, for increased readibility.</p> <p>(obviously this is a bit less useful if your Coord3D class needs other functionality too)</p> <p>[if you're not on python2.6, you can get namedtuples from the <a href="http://code.activestate.com/recipes/500261/">cookbook recipe</a>]</p>
12
2009-04-28T00:34:52Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?</p> <p>In the first case, I get very low coupling, but then I will probably have to instantiate a Coord3D object with the obtained values anyway, although outside of the file class. In the second case, I will have the file class tightly coupled with the Coord3D class.</p> <p>Please note that I think there's not a huge difference between the two solutions, but I would like to read your answer and the reason behind it.</p> <p><hr /></p> <p><strong>Edit</strong>: to recap the answers I got until now, it looks like there's no clearcut choice. It has been said (appropriately) that python is not Java, and you don't need a specialized class for everything just because you need it by language architecture. In my case, however, I have the following conditions:</p> <ol> <li>I am working on a library, where the Coord3D object is used as is. Using it would increase the cohesiveness of my library, as the data types will be uniformly used.</li> <li>The Coord3D object has state and behavior. Indeed, the Coord3D object aggregate the coordinates and the units in a single entity. Operations among Coord3D objects will keep into account the potentially different units, and act accordingly.</li> <li>I can put centralize control code into the Coord3D class instantiation to refuse, for example, arrays of length 4, or non units. If I use a tuple, I cannot perform this check. Moreover, if a method accepts a Coord3D, is sort of guaranteed that it's well formed upfront (you could be bold and check for isinstance, or check the interface). A tuple can contain invalid data. Although python approach to error handling is done where the trouble happen, a class preventing me to have an xyz coordinate made out of three strings is somehow beneficial (correct me if wrong, please)</li> </ol> <p>On the other hand, using a tuple has the following advantages:</p> <ol> <li>Less occupation of resources, quite critical in case of huge </li> <li>Simpler design. More classes means more complex design. A tuple is a standard data type which is well understood and can be unpacked easily. A personalized class is not.</li> <li>Using a tuple, the XYZFile class is totally decoupled from the rest of the library (because it does not use the Coord3D object). This means that it can be reused totally as an independent entity.</li> </ol> <p>further comments very welcome!</p>
11
2009-04-27T15:48:48Z
799,336
<p>Take a look at Will McGugan's <a href="http://code.google.com/p/gameobjects/" rel="nofollow">Gameobjects library</a>. He has a <a href="http://code.google.com/p/gameobjects/source/browse/trunk/vector3.py" rel="nofollow">Vector3 class</a> that can be initialized with another Vector3 object, a tuple, individual float values, etc. I think this will answer your question ... plus you may end up just using his library as it's already optimized and has plenty of useful methods already.</p>
2
2009-04-28T18:47:51Z
[ "python", "design" ]
Accessing MultipleChoiceField choices values
794,178
<p>How do I get the choices field values and not the key from the form?</p> <p>I have a form where I let the user select some user's emails for a company. For example I have a form like this (this reason for model form is that it's inside a formset - but that is not important for now):</p> <pre><code>class Contacts(forms.ModelForm): def __init__(self, *args, **kwargs): super(Contacts, self).__init__(*args, **kwargs) self.company = kwargs['initial']['company'] self.fields['emails'].choices = self.company.emails # This produces stuff like: # [(1, 'email@email.com'), ...] emails = forms.MultipleChoiceField(required=False) class Meta: model = Company </code></pre> <p>and I want to get the list of all selected emails in the view, something like this:</p> <pre><code> form = ContactsForm(request.POST) if form.is_valid(): form.cleaned_data['emails'][0] # produces 1 and not email </code></pre> <p>There is no <code>get_emails_display()</code> kind of method, like in the model for example. Also, a suggestion <code>form.fields['emails'].choices</code> does not work, as it gives ALL the choices, whereas I need something like <code>form.fields['emails'].selected_choices</code>?</p> <p>Any ideas, or let me know if it's unclear. </p>
1
2009-04-27T16:00:53Z
794,189
<p>It might not be a beautiful solution, but I would imagine that the display names are all still available from <code>form.fields['emails'].choices</code> so you can loop through <code>form.cleaned_data['emails']</code> and get the choice name from the field's choices.</p>
0
2009-04-27T16:04:35Z
[ "python", "django" ]
Accessing MultipleChoiceField choices values
794,178
<p>How do I get the choices field values and not the key from the form?</p> <p>I have a form where I let the user select some user's emails for a company. For example I have a form like this (this reason for model form is that it's inside a formset - but that is not important for now):</p> <pre><code>class Contacts(forms.ModelForm): def __init__(self, *args, **kwargs): super(Contacts, self).__init__(*args, **kwargs) self.company = kwargs['initial']['company'] self.fields['emails'].choices = self.company.emails # This produces stuff like: # [(1, 'email@email.com'), ...] emails = forms.MultipleChoiceField(required=False) class Meta: model = Company </code></pre> <p>and I want to get the list of all selected emails in the view, something like this:</p> <pre><code> form = ContactsForm(request.POST) if form.is_valid(): form.cleaned_data['emails'][0] # produces 1 and not email </code></pre> <p>There is no <code>get_emails_display()</code> kind of method, like in the model for example. Also, a suggestion <code>form.fields['emails'].choices</code> does not work, as it gives ALL the choices, whereas I need something like <code>form.fields['emails'].selected_choices</code>?</p> <p>Any ideas, or let me know if it's unclear. </p>
1
2009-04-27T16:00:53Z
794,589
<p>Ok, hopefully this is closer to what you wanted.</p> <pre><code>emails = filter(lambda t: t[0] in form.cleaned_data['emails'], form.fields['emails'].choices) </code></pre> <p>That should give you the list of selected choices that you want.</p>
6
2009-04-27T18:06:50Z
[ "python", "django" ]
Python list comprehension - access last created element?
794,774
<p>Is it possible to access the previous element generated in a list comprehension.</p> <p>I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element and the key. The following loop would do.</p> <pre><code>previous = initialization_value cipher = [] for element in message: previous = element ^ previous ^ key cipher.append(previous) </code></pre> <p>I feel like it should be possible to turn this into a list comprehension but I am not exactly sure how to handle both the initial value or accessing the previous value generated. Is it possible and if so what would the comprehension be?</p>
11
2009-04-27T18:46:27Z
794,871
<p>There isn't a good, Pythonic way to do this with a list comprehension. The best way to think about list comprehensions is as a replacement for <code>map</code> and <code>filter</code>. In other words, you'd use a list comprehension whenever you need to take a list and</p> <ul> <li><p>Use its elements as input for some expression (e.g. squaring the elements)</p></li> <li><p>Remove some of its elements based on some condition</p></li> </ul> <p>What these things have in common is that they each only look at a single list element at a time. This is a good rule of thumb; even if you could theoretically write the code you showed as a list comprehension, it would be awkward and unpythonic.</p>
10
2009-04-27T19:12:32Z
[ "python" ]
Python list comprehension - access last created element?
794,774
<p>Is it possible to access the previous element generated in a list comprehension.</p> <p>I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element and the key. The following loop would do.</p> <pre><code>previous = initialization_value cipher = [] for element in message: previous = element ^ previous ^ key cipher.append(previous) </code></pre> <p>I feel like it should be possible to turn this into a list comprehension but I am not exactly sure how to handle both the initial value or accessing the previous value generated. Is it possible and if so what would the comprehension be?</p>
11
2009-04-27T18:46:27Z
794,874
<p>You could use a helper object to store all the internal state while iterating over the sequence:</p> <pre><code>class Encryption: def __init__(self, key, init_value): self.key = key self.previous = init_value def next(self, element): self.previous = element ^ self.previous ^ self.key return self.previous enc = Encryption(...) cipher = [enc.next(e) for e in message] </code></pre> <p>That being said, adding the previously encrypted element into the xor doesn't make your algorithm any harder to break than just xor'ing every element with the key. An attacker can just xor any character in the cipher text with the previous encrypted character and so cancel out the xor that was done during encryption.</p>
1
2009-04-27T19:13:12Z
[ "python" ]
Python list comprehension - access last created element?
794,774
<p>Is it possible to access the previous element generated in a list comprehension.</p> <p>I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element and the key. The following loop would do.</p> <pre><code>previous = initialization_value cipher = [] for element in message: previous = element ^ previous ^ key cipher.append(previous) </code></pre> <p>I feel like it should be possible to turn this into a list comprehension but I am not exactly sure how to handle both the initial value or accessing the previous value generated. Is it possible and if so what would the comprehension be?</p>
11
2009-04-27T18:46:27Z
795,158
<p>You could have done this using <a href="http://docs.python.org/library/functions.html#reduce" rel="nofollow">reduce()</a>. It's not list comprehension, but it's the functional style approach:</p> <pre><code>cipher = [] def f(previous, element): previous = element ^ previous ^ key cipher.append(previous) return previous reduce(f, message, initialization_value) </code></pre> <p>It isn't any prettier than the plain loop in this case though.</p>
3
2009-04-27T20:29:11Z
[ "python" ]
Python list comprehension - access last created element?
794,774
<p>Is it possible to access the previous element generated in a list comprehension.</p> <p>I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element and the key. The following loop would do.</p> <pre><code>previous = initialization_value cipher = [] for element in message: previous = element ^ previous ^ key cipher.append(previous) </code></pre> <p>I feel like it should be possible to turn this into a list comprehension but I am not exactly sure how to handle both the initial value or accessing the previous value generated. Is it possible and if so what would the comprehension be?</p>
11
2009-04-27T18:46:27Z
795,671
<p>It probably can be done; see <a href="http://code.activestate.com/recipes/204297/" rel="nofollow">The Secret Name of List Comprehensions</a>. It's very much not pythonic, though.</p>
2
2009-04-27T23:21:26Z
[ "python" ]
Python list comprehension - access last created element?
794,774
<p>Is it possible to access the previous element generated in a list comprehension.</p> <p>I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element and the key. The following loop would do.</p> <pre><code>previous = initialization_value cipher = [] for element in message: previous = element ^ previous ^ key cipher.append(previous) </code></pre> <p>I feel like it should be possible to turn this into a list comprehension but I am not exactly sure how to handle both the initial value or accessing the previous value generated. Is it possible and if so what would the comprehension be?</p>
11
2009-04-27T18:46:27Z
2,068,496
<p>As a generator:</p> <pre><code>def cypher(message, key, seed): for element in message: seed = element ^ seed ^ key yield seed list(cypher(message, key, initial_seed)) </code></pre>
2
2010-01-15T00:09:20Z
[ "python" ]
PyQT combobox only react on user interaction
794,813
<p>I have a listbox that you can select users in. To the left of that is a combobox listing the available groups the user can be put it. If the user is in a group, the combobox will automatically be set to that group. I want to make it so when you change the group selection, it will move the user to that group. I added this connection:</p> <pre><code>QtCore.QObject.connect(self.GroupsBox, QtCore.SIGNAL("currentIndexChanged(QString)"), self.HandleGrouping) </code></pre> <p>The problem is that since I'll be selecting different users in different groups, every time I select a new user, the default option in the combobox changes and Qt registers this as a 'currentIndexChanged' signal.</p> <p>There appears to be no way to only fire the signal on direct user-interaction with the widget itself. What methods can I use to work around this?</p>
2
2009-04-27T18:55:46Z
794,898
<p>Catch a signal from the QComboBox (<a href="https://doc.qt.io/qt-5/qcombobox.html#activated" rel="nofollow"><code>activated(int index)</code></a>), and update the selected user based on that. In you Handler function, don't do anything if the selected index in the combobox is the same as the group the selected user is in.</p> <p>Maybe move your combobox to the right of the user listbox, as your order of actions will be Select User --> Select Group.</p>
6
2009-04-27T19:16:20Z
[ "python", "qt", "qcombobox" ]
Converting to Precomposed Unicode String using Python-AppKit-ObjectiveC
794,836
<p>This document by Apple <a href="http://developer.apple.com/qa/qa2001/qa1235.html" rel="nofollow">Technical Q&amp;A QA1235</a> describes a way to convert unicode strings from a composed to a decomposed version. Since I have a problem with file names containing some characters (e.g. an accent grave), I'd like to try the conversion function</p> <p>void CFStringNormalize(CFMutableStringRef theString, CFStringNormalizationForm theForm);</p> <p>I am using this with Python and the AppKit library. If i pass a Python String as an argument, I get:</p> <blockquote> <blockquote> <blockquote> <p>CoreFoundation.CFStringNormalize("abc",0) 2009-04-27 21:00:54.314 Python[4519:613] <strong>* -[OC_PythonString _cfNormalize:]: unrecognized selector sent to instance 0x1f02510 Traceback (most recent call last): File "", line 1, in ValueError: NSInvalidArgumentException - *</strong> -[OC_PythonString _cfNormalize:]: unrecognized selector sent to instance 0x1f02510</p> </blockquote> </blockquote> </blockquote> <p>I suppose this is because a CFMutableStringRef is needed as an argument. How do I convert a Python String to CFMutableStringRef? </p>
3
2009-04-27T19:02:54Z
796,392
<p>OC_PythonString (which is what Python strings are bridged to) is an NSString subclass, so you could get an NSMutableString with:</p> <pre><code>mutableString = NSMutableString.alloc().initWithString_("abc") </code></pre> <p>then use mutableString as the argument to CFStringNormalize.</p>
1
2009-04-28T05:52:59Z
[ "python", "objective-c" ]
How to convert datetime to string in python in django
794,995
<p>I have a datetime object at my model. I am sending it to the view, but in html i don't know what to write in order to format it.</p> <p>I am trying </p> <pre><code>{{ item.date.strftime("%Y-%m-%d")|escape }} </code></pre> <p>but I get </p> <pre><code>TemplateSyntaxError: Could not parse some characters: item.date.strftime|("%Y-%m-%d")||escape </code></pre> <p>when I am just using </p> <pre><code>{{ item.date|escape }} </code></pre> <p>it's working, but now with the format I want. </p> <p>Any suggestions?</p>
4
2009-04-27T19:42:52Z
795,000
<p>Try using the built-in Django <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date">date format filter</a> instead:</p> <pre><code>{{ item.date|date:"Y M d" }} </code></pre>
11
2009-04-27T19:44:51Z
[ "python", "django" ]
How to perform common post-initialization tasks in inherited Python classes?
795,190
<p>The initialization process of group of classes that share a common parent can be divided into three parts: common part1, class-specific part, common part2. Currently the first two parts are called from the __init__ function of each child class, but the second common part has to be called separately For example:</p> <pre><code>class BaseClass: def __init__(self): print 'base __init__' self.common1() def common1(self): print 'common 1' def finalizeInitialization(self): print 'finalizeInitialization [common2]' class Subclass1(BaseClass): def __init__(self): BaseClass.__init__(self) self.specific() def specific(self): print 'specific' if __name__ == '__main__': s = Subclass1() #Don't forget to finalize the initialization s.finalizeInitialization() # now the object is fully initialized </code></pre> <p>Is there a way to not to have to call finalizeInitialization()?</p> <p><em>EDIT</em> one can transfer the call to finalizeInitialization() into Subclass1's __init__ (as in <a href="http://stackoverflow.com/questions/795190/how-to-perform-common-post-initialization-tasks-in-inherited-python-classes/795213#795213">S.Lott's answer</a>). This makes the life easier, but still one has to remember to complete the initialization, this time inside the "constructor". Either way there is no way to enforce full initialization, which is what I'm looking for.</p>
4
2009-04-27T20:38:03Z
795,213
<p>Version 1 - delegate everything.</p> <pre><code>class Subclass1(BaseClass): def __init__(self): super( Subclass1, self ).__init__() self.specific() super( Subclass1, self ).finalizeInitialization() </code></pre> <p>Version 2 - delegate just one step</p> <pre><code>class BaseClass: def __init__(self): print 'base __init__' self.common1() self.specific() self.finalizeInitialization() def common1(self): print 'common 1' def finalizeInitialization(self): print 'finalizeInitialization [common2]' def specific( self ): # two choices: # if this is "abstract": raise an exception # if this is "concrete": pass </code></pre>
4
2009-04-27T20:43:57Z
[ "python", "inheritance", "initialization" ]
How to perform common post-initialization tasks in inherited Python classes?
795,190
<p>The initialization process of group of classes that share a common parent can be divided into three parts: common part1, class-specific part, common part2. Currently the first two parts are called from the __init__ function of each child class, but the second common part has to be called separately For example:</p> <pre><code>class BaseClass: def __init__(self): print 'base __init__' self.common1() def common1(self): print 'common 1' def finalizeInitialization(self): print 'finalizeInitialization [common2]' class Subclass1(BaseClass): def __init__(self): BaseClass.__init__(self) self.specific() def specific(self): print 'specific' if __name__ == '__main__': s = Subclass1() #Don't forget to finalize the initialization s.finalizeInitialization() # now the object is fully initialized </code></pre> <p>Is there a way to not to have to call finalizeInitialization()?</p> <p><em>EDIT</em> one can transfer the call to finalizeInitialization() into Subclass1's __init__ (as in <a href="http://stackoverflow.com/questions/795190/how-to-perform-common-post-initialization-tasks-in-inherited-python-classes/795213#795213">S.Lott's answer</a>). This makes the life easier, but still one has to remember to complete the initialization, this time inside the "constructor". Either way there is no way to enforce full initialization, which is what I'm looking for.</p>
4
2009-04-27T20:38:03Z
795,231
<p>What's wrong with calling finalInitilazation from the Subclass's init?</p> <pre><code> class BaseClass: def __init__(self): print 'base __init__' self.common1() def common1(self): print 'common 1' def finalizeInitialization(self): print 'finalizeInitialization [common2]' class Subclass1(BaseClass): def __init__(self): BaseClass.__init__(self) self.specific() BaseClass.finalizeInitialization(self) def specific(self): print 'specific' if __name__ == '__main__': s = Subclass1() #Don't forget to finalize the initialization s.finalizeInitialization() # now the object is fully initialized </code></pre>
0
2009-04-27T20:47:40Z
[ "python", "inheritance", "initialization" ]
How to perform common post-initialization tasks in inherited Python classes?
795,190
<p>The initialization process of group of classes that share a common parent can be divided into three parts: common part1, class-specific part, common part2. Currently the first two parts are called from the __init__ function of each child class, but the second common part has to be called separately For example:</p> <pre><code>class BaseClass: def __init__(self): print 'base __init__' self.common1() def common1(self): print 'common 1' def finalizeInitialization(self): print 'finalizeInitialization [common2]' class Subclass1(BaseClass): def __init__(self): BaseClass.__init__(self) self.specific() def specific(self): print 'specific' if __name__ == '__main__': s = Subclass1() #Don't forget to finalize the initialization s.finalizeInitialization() # now the object is fully initialized </code></pre> <p>Is there a way to not to have to call finalizeInitialization()?</p> <p><em>EDIT</em> one can transfer the call to finalizeInitialization() into Subclass1's __init__ (as in <a href="http://stackoverflow.com/questions/795190/how-to-perform-common-post-initialization-tasks-in-inherited-python-classes/795213#795213">S.Lott's answer</a>). This makes the life easier, but still one has to remember to complete the initialization, this time inside the "constructor". Either way there is no way to enforce full initialization, which is what I'm looking for.</p>
4
2009-04-27T20:38:03Z
795,409
<p>If you have to call multiple methods in a specific order it typically means that the design has problems to begin with (it's leaking implementation detail). So I would try to work from that end.</p> <p>On the other hand if people derive from the class and have to modify the initialisation they should be aware of the implications - it is not something you would want to have in your normal API. Alternatively you could be defensive about the final initialization and check that it has been called in methods that depend on it (to call it or raise an exception if not).</p>
0
2009-04-27T21:43:07Z
[ "python", "inheritance", "initialization" ]
How to perform common post-initialization tasks in inherited Python classes?
795,190
<p>The initialization process of group of classes that share a common parent can be divided into three parts: common part1, class-specific part, common part2. Currently the first two parts are called from the __init__ function of each child class, but the second common part has to be called separately For example:</p> <pre><code>class BaseClass: def __init__(self): print 'base __init__' self.common1() def common1(self): print 'common 1' def finalizeInitialization(self): print 'finalizeInitialization [common2]' class Subclass1(BaseClass): def __init__(self): BaseClass.__init__(self) self.specific() def specific(self): print 'specific' if __name__ == '__main__': s = Subclass1() #Don't forget to finalize the initialization s.finalizeInitialization() # now the object is fully initialized </code></pre> <p>Is there a way to not to have to call finalizeInitialization()?</p> <p><em>EDIT</em> one can transfer the call to finalizeInitialization() into Subclass1's __init__ (as in <a href="http://stackoverflow.com/questions/795190/how-to-perform-common-post-initialization-tasks-in-inherited-python-classes/795213#795213">S.Lott's answer</a>). This makes the life easier, but still one has to remember to complete the initialization, this time inside the "constructor". Either way there is no way to enforce full initialization, which is what I'm looking for.</p>
4
2009-04-27T20:38:03Z
795,877
<p>Template Method Design Pattern to the rescue:</p> <pre><code>class BaseClass: def __init__(self, specifics=None): print 'base __init__' self.common1() if specifics is not None: specifics() self.finalizeInitialization() def common1(self): print 'common 1' def finalizeInitialization(self): print 'finalizeInitialization [common2]' class Subclass1(BaseClass): def __init__(self): BaseClass.__init__(self, self.specific) def specific(self): print 'specific' </code></pre>
8
2009-04-28T01:17:47Z
[ "python", "inheritance", "initialization" ]
How to perform common post-initialization tasks in inherited Python classes?
795,190
<p>The initialization process of group of classes that share a common parent can be divided into three parts: common part1, class-specific part, common part2. Currently the first two parts are called from the __init__ function of each child class, but the second common part has to be called separately For example:</p> <pre><code>class BaseClass: def __init__(self): print 'base __init__' self.common1() def common1(self): print 'common 1' def finalizeInitialization(self): print 'finalizeInitialization [common2]' class Subclass1(BaseClass): def __init__(self): BaseClass.__init__(self) self.specific() def specific(self): print 'specific' if __name__ == '__main__': s = Subclass1() #Don't forget to finalize the initialization s.finalizeInitialization() # now the object is fully initialized </code></pre> <p>Is there a way to not to have to call finalizeInitialization()?</p> <p><em>EDIT</em> one can transfer the call to finalizeInitialization() into Subclass1's __init__ (as in <a href="http://stackoverflow.com/questions/795190/how-to-perform-common-post-initialization-tasks-in-inherited-python-classes/795213#795213">S.Lott's answer</a>). This makes the life easier, but still one has to remember to complete the initialization, this time inside the "constructor". Either way there is no way to enforce full initialization, which is what I'm looking for.</p>
4
2009-04-27T20:38:03Z
795,978
<p>Similar to S. Lott's approach, except there's no way (short of overriding <code>__init__</code>) for the derived classes to override (or even call) the common methods:</p> <pre><code>class BaseClass: def __init__(self): def common(): print "common initialization..." def final(): print "common finalization..." common() self.specific() final() def final_init(self): print "BaseClass.final_init" class Subclass1(BaseClass): def specific(self): print "Subclass1.specific" </code></pre> <p>You might want to provide a default implementation of <code>specific</code> in <code>BaseClass</code> if it's not okay to raise an <code>AttributeError</code> when you create an instance of any subclass that doesn't provide its own implementation.</p>
1
2009-04-28T02:10:17Z
[ "python", "inheritance", "initialization" ]
python versus java runtime footprint
795,241
<p>Can anyone point to serious comparison of Python runtime footprint versus Java?</p> <p>Thanks, Avraham</p>
6
2009-04-27T20:49:30Z
35,581,985
<p>I can't compare memory footprint because it really depends on classes what you load/use. But what I can tell you that Python (IronPython 2.7 in particular) has real memory leak problems. Especially with third party well used ones like Financial. When Java application/server runs without issues with rare cases which could be identified with common tools Python grows in memory constantly. </p> <p>Memory dumps shows that Python itself as well as most of packages don't pay attention for common classes like String and keep them in different parts of the execution modules. It is hard and unwise to go through all these sources and fix all leaks.</p> <p>I was trying a lot to fix the issues but finally gave in and simply restart application when it reaches some memory threshold.</p>
1
2016-02-23T15:47:38Z
[ "java", "python", "footprint", "memory-footprint" ]
How to compare value of 2 fields in Django QuerySet?
795,310
<p>I have a django model like this:</p> <pre><code>class Player(models.Model): name = models.CharField() batting = models.IntegerField() bowling = models.IntegerField() </code></pre> <p>What would be the Django QuerySet equivalent of the following SQL?</p> <pre><code>SELECT * FROM player WHERE batting &gt; bowling; </code></pre>
7
2009-04-27T21:13:51Z
795,322
<p>In django 1.1 you can do the following:</p> <pre><code>players = Player.objects.filter(batting__gt=F('bowling')) </code></pre> <p>See the <a href="http://stackoverflow.com/questions/433294/column-comparison-in-django-queries">other question</a> for details</p>
15
2009-04-27T21:17:30Z
[ "python", "django", "model" ]
Is there an easy way to tell how much time is spent waiting for the Python GIL?
795,405
<p>I have a long-running Python service and I'd like to know how much cumulative wall clock time has been spent by any runnable threads (i.e., threads that weren't blocked for some other reason) waiting for the GIL. Is there an easy way to do this? E.g., perhaps I could periodically dump some counter to its log file.</p> <p>My underlying motivation is to rule out the GIL as a source of mystery response latency from these long-running processes. There is no particular reason to suspect the GIL (other than that it would fit the symptoms), but other forms of logging haven't turned up anything yet, so, <em>if it is easy</em>, it would be nice to have this information.</p>
4
2009-04-27T21:42:12Z
797,218
<p>I don't think there's an easy way. There's probably an awkward way, involving rebuilding Python to traverse the PyThreadState list and count the threads each time the lock is acquired, but I doubt it's worth the effort!</p> <p>I know this is a speculative question but if you are even moderately concerned about there being delays caused by threading it may be prudent to move to a multiprocessing model instead of a multithreading model. Since processes are both safer and more scalable in Python they are almost always the best choice if practical.</p>
3
2009-04-28T10:19:59Z
[ "python", "multithreading" ]
Correlate one set of vectors to another in numpy?
795,570
<p>Let's say I have a set of vectors (readings from sensor 1, readings from sensor 2, readings from sensor 3 -- indexed first by timestamp and then by sensor id) that I'd like to correlate to a separate set of vectors (temperature, humidity, etc -- also all indexed first by timestamp and secondly by type).</p> <p>What is the cleanest way in numpy to do this? It seems like it should be a rather simple function...</p> <p>In other words, I'd like to see:</p> <pre><code>&gt; a.shape (365,20) &gt; b.shape (365, 5) &gt; correlations = magic_correlation_function(a,b) &gt; correlations.shape (20, 5) </code></pre> <p>Cheers, /YGA</p> <p>P.S. I've been asked to add an example. </p> <p>Here's what I would like to see:</p> <pre><code>$ In [27]: x $ Out[27]: array([[ 0, 0, 0], [-1, 0, -1], [-2, 0, -2], [-3, 0, -3], [-4, 0.1, -4]]) $ In [28]: y $ Out[28]: array([[0, 0], [1, 0], [2, 0], [3, 0], [4, 0.1]]) $ In [28]: magical_correlation_function(x, y) $ Out[28]: array([[-1. , 0.70710678, 1. ] [-0.70710678, 1. , 0.70710678]]) </code></pre> <p>Ps2: whoops, mis-transcribed my example. Sorry all. Fixed now.</p>
2
2009-04-27T22:43:38Z
795,649
<p>As David said, you should define the correlation you're using. I don't know of any definitions of correlation that gives sensible numbers when correlating empty and non-empty signals.</p>
0
2009-04-27T23:11:40Z
[ "python", "numpy" ]
Correlate one set of vectors to another in numpy?
795,570
<p>Let's say I have a set of vectors (readings from sensor 1, readings from sensor 2, readings from sensor 3 -- indexed first by timestamp and then by sensor id) that I'd like to correlate to a separate set of vectors (temperature, humidity, etc -- also all indexed first by timestamp and secondly by type).</p> <p>What is the cleanest way in numpy to do this? It seems like it should be a rather simple function...</p> <p>In other words, I'd like to see:</p> <pre><code>&gt; a.shape (365,20) &gt; b.shape (365, 5) &gt; correlations = magic_correlation_function(a,b) &gt; correlations.shape (20, 5) </code></pre> <p>Cheers, /YGA</p> <p>P.S. I've been asked to add an example. </p> <p>Here's what I would like to see:</p> <pre><code>$ In [27]: x $ Out[27]: array([[ 0, 0, 0], [-1, 0, -1], [-2, 0, -2], [-3, 0, -3], [-4, 0.1, -4]]) $ In [28]: y $ Out[28]: array([[0, 0], [1, 0], [2, 0], [3, 0], [4, 0.1]]) $ In [28]: magical_correlation_function(x, y) $ Out[28]: array([[-1. , 0.70710678, 1. ] [-0.70710678, 1. , 0.70710678]]) </code></pre> <p>Ps2: whoops, mis-transcribed my example. Sorry all. Fixed now.</p>
2
2009-04-27T22:43:38Z
797,939
<p>The simplest thing that I could find was using the scipy.stats package</p> <pre><code>In [8]: x Out[8]: array([[ 0. , 0. , 0. ], [-1. , 0. , -1. ], [-2. , 0. , -2. ], [-3. , 0. , -3. ], [-4. , 0.1, -4. ]]) In [9]: y Out[9]: array([[0. , 0. ], [1. , 0. ], [2. , 0. ], [3. , 0. ], [4. , 0.1]]) In [10]: import scipy.stats In [27]: (scipy.stats.cov(y,x) /(numpy.sqrt(scipy.stats.var(y,axis=0)[:,numpy.newaxis])) /(numpy.sqrt(scipy.stats.var(x,axis=0)))) Out[27]: array([[-1. , 0.70710678, -1. ], [-0.70710678, 1. , -0.70710678]]) </code></pre> <p>These aren't the numbers you got, but you've mixed up your rows. (Element [0,0] should be 1.)</p> <p>A more complicated, but purely numpy solution is</p> <pre><code>In [40]: numpy.corrcoef(x.T,y.T)[numpy.arange(x.shape[1])[numpy.newaxis,:] ,numpy.arange(y.shape[1])[:,numpy.newaxis]] Out[40]: array([[-1. , 0.70710678, -1. ], [-0.70710678, 1. , -0.70710678]]) </code></pre> <p>This will be slower because it computes the correlation of each element in x with each other element in x, which you don't want. Also, the advanced indexing techniques used to get the subset of the array you desire can make your head hurt.</p> <p>If you're going to use numpy intensely, get familiar with the rules on <a href="http://www.scipy.org/EricsBroadcastingDoc" rel="nofollow">broadcasting</a> and <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">indexing</a>. They will help you push as much down to the C-level as possible.</p>
2
2009-04-28T13:28:54Z
[ "python", "numpy" ]
Correlate one set of vectors to another in numpy?
795,570
<p>Let's say I have a set of vectors (readings from sensor 1, readings from sensor 2, readings from sensor 3 -- indexed first by timestamp and then by sensor id) that I'd like to correlate to a separate set of vectors (temperature, humidity, etc -- also all indexed first by timestamp and secondly by type).</p> <p>What is the cleanest way in numpy to do this? It seems like it should be a rather simple function...</p> <p>In other words, I'd like to see:</p> <pre><code>&gt; a.shape (365,20) &gt; b.shape (365, 5) &gt; correlations = magic_correlation_function(a,b) &gt; correlations.shape (20, 5) </code></pre> <p>Cheers, /YGA</p> <p>P.S. I've been asked to add an example. </p> <p>Here's what I would like to see:</p> <pre><code>$ In [27]: x $ Out[27]: array([[ 0, 0, 0], [-1, 0, -1], [-2, 0, -2], [-3, 0, -3], [-4, 0.1, -4]]) $ In [28]: y $ Out[28]: array([[0, 0], [1, 0], [2, 0], [3, 0], [4, 0.1]]) $ In [28]: magical_correlation_function(x, y) $ Out[28]: array([[-1. , 0.70710678, 1. ] [-0.70710678, 1. , 0.70710678]]) </code></pre> <p>Ps2: whoops, mis-transcribed my example. Sorry all. Fixed now.</p>
2
2009-04-27T22:43:38Z
799,834
<p>Will this do what you want?</p> <pre><code>correlations = dot(transpose(a), b) </code></pre>
0
2009-04-28T21:10:06Z
[ "python", "numpy" ]
Google AppEngine: how to count a database's entries beyond 1000?
795,817
<p><strong>Duplicate of</strong> <a href="http://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine">"how does one get a count of rows in a datastore model in google appengine?"</a></p> <hr> <p>I want to know how many users I have. Previously, I achieved this with the following code: </p> <pre><code>users = UserStore.all() user_count = users.count() </code></pre> <p>But now I have more than 1,000 users and this method continues to return 1,000.</p> <p>Is there an efficient programmatic way of knowing how many users I have?</p>
12
2009-04-28T00:44:43Z
795,849
<p>Use pagination like these examples <a href="http://google-appengine.googlegroups.com/web/efficient%5Fpaging%5Fusing%5Fkey%5Finstead%5Fof%5Fa%5Fdedicated%5Funique%5Fproperty.txt" rel="nofollow">here</a>.</p>
2
2009-04-28T01:00:12Z
[ "python", "google-app-engine", "count" ]
Google AppEngine: how to count a database's entries beyond 1000?
795,817
<p><strong>Duplicate of</strong> <a href="http://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine">"how does one get a count of rows in a datastore model in google appengine?"</a></p> <hr> <p>I want to know how many users I have. Previously, I achieved this with the following code: </p> <pre><code>users = UserStore.all() user_count = users.count() </code></pre> <p>But now I have more than 1,000 users and this method continues to return 1,000.</p> <p>Is there an efficient programmatic way of knowing how many users I have?</p>
12
2009-04-28T00:44:43Z
796,588
<p>It is indeed a duplicate and the other post describes how to theoretically do it, but I'd like to stress that you should really not be doing counts this way. The reason being that BigTable by its distributed nature is really bad for aggregates. What you probably want to do is add a transactional counter to that entity, and if there are lots of transactions a sharded counter. See: <a href="http://code.google.com/appengine/articles/sharding_counters.html" rel="nofollow">http://code.google.com/appengine/articles/sharding_counters.html</a></p> <p>UPDATE: Since 1.3.1 cursors make stuff like this a lot easier: <a href="http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html#Query_Cursors" rel="nofollow">http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html#Query_Cursors</a> </p>
14
2009-04-28T07:15:18Z
[ "python", "google-app-engine", "count" ]
Google AppEngine: how to count a database's entries beyond 1000?
795,817
<p><strong>Duplicate of</strong> <a href="http://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine">"how does one get a count of rows in a datastore model in google appengine?"</a></p> <hr> <p>I want to know how many users I have. Previously, I achieved this with the following code: </p> <pre><code>users = UserStore.all() user_count = users.count() </code></pre> <p>But now I have more than 1,000 users and this method continues to return 1,000.</p> <p>Is there an efficient programmatic way of knowing how many users I have?</p>
12
2009-04-28T00:44:43Z
3,547,366
<p>I have write this method to count a query, but how said Nick Johnson maybe it's a bad idea...</p> <pre><code>def query_counter (q, cursor=None, limit=500): if cursor: q.with_cursor (cursor) count = q.count (limit=limit) if count == limit: return count + query_counter (q, q.cursor (), limit=limit) return count </code></pre>
0
2010-08-23T12:11:44Z
[ "python", "google-app-engine", "count" ]
Google AppEngine: how to count a database's entries beyond 1000?
795,817
<p><strong>Duplicate of</strong> <a href="http://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine">"how does one get a count of rows in a datastore model in google appengine?"</a></p> <hr> <p>I want to know how many users I have. Previously, I achieved this with the following code: </p> <pre><code>users = UserStore.all() user_count = users.count() </code></pre> <p>But now I have more than 1,000 users and this method continues to return 1,000.</p> <p>Is there an efficient programmatic way of knowing how many users I have?</p>
12
2009-04-28T00:44:43Z
3,548,760
<p>Since version <a href="http://googleappengine.blogspot.com/2010/08/multi-tenancy-support-high-performance_17.html" rel="nofollow">1.3.6</a> of the SDK the limit of 1000 on the count function has been removed. So a call to the count function will now return the exact number of entities, even if there are more than 1000. Only limitation would be if you had so many entities that the count function would not return before the request has a timeout.</p>
2
2010-08-23T14:58:22Z
[ "python", "google-app-engine", "count" ]
Google AppEngine: how to count a database's entries beyond 1000?
795,817
<p><strong>Duplicate of</strong> <a href="http://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine">"how does one get a count of rows in a datastore model in google appengine?"</a></p> <hr> <p>I want to know how many users I have. Previously, I achieved this with the following code: </p> <pre><code>users = UserStore.all() user_count = users.count() </code></pre> <p>But now I have more than 1,000 users and this method continues to return 1,000.</p> <p>Is there an efficient programmatic way of knowing how many users I have?</p>
12
2009-04-28T00:44:43Z
12,845,268
<p>For Python GAE SDK, you can increase the argument "limit" of the count method: <a href="https://developers.google.com/appengine/docs/python/datastore/queryclass#Query_count" rel="nofollow">https://developers.google.com/appengine/docs/python/datastore/queryclass#Query_count</a></p>
0
2012-10-11T17:32:29Z
[ "python", "google-app-engine", "count" ]
How do you open and transfer a file on the filesystem in mod_python?
795,837
<p>I'm new to mod_python and Apache, and I'm having trouble returning a file to a user after a GET request. I've got a very simple setup right now, and was hoping to simply open the file and write it to the response:</p> <pre><code>from mod_python import apache def handler(req): req.content_type = 'application/octet-stream' fIn = open('response.bin', 'rb') req.write(fIn.read()) fIn.close() return apache.OK </code></pre> <p>However, I'm getting errors when I use open(), saying that the file doesn't exist (even though I've checked a dozen times that it does). This happens when using relative and absolute filepaths.</p> <p>I've got two questions: </p> <ul> <li>Why isn't open() finding the right files?</li> <li>What is the best way to return a file from the filesystem? (I ask to make sure I'm not missing some better way to use mod_python to return a file.)</li> </ul> <p>Thanks</p> <p>Edit: After finding this thread: <a href="http://www.programmingforums.org/thread12384.html" rel="nofollow">http://www.programmingforums.org/thread12384.html</a> I discovered that open() works for me if I move the file to another directory outside of home (I was aliasing out of /home/myname/httpdocs, but it works if I use /data). Any ideas why that works?</p> <p>Edit 2: Part of my debug error, as requested:</p> <pre><code>MOD_PYTHON ERROR ProcessId: 13642 Interpreter: '127.0.1.1' ServerName: '127.0.1.1' DocumentRoot: '/var/www' URI: '/test/mptest.py' Location: None Directory: '/home/myname/httpdocs/' Filename: '/home/myname/httpdocs/mptest.py' PathInfo: '' Phase: 'PythonHandler' Handler: 'mptest' Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1229, in _process_target result = _execute_target(config, req, object, arg) File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1128, in _execute_target result = object(arg) File "/home/myname/httpdocs/mptest.py", line 13, in handler fIn = open('/home/myname/httpdocs/files/response.bin', 'rb') IOError: [Errno 2] No such file or directory: '/home/myname/httpdocs/files/response.bin' </code></pre>
1
2009-04-28T00:53:59Z
795,876
<p>To debug this kind of thing, you need to gather all information from the running mod_python instance.</p> <p>Stop messing with "checking a dozen times that it [exists]". Some assumption isn't correct.</p> <p>Do something like this to get some debugging information.</p> <pre><code>def handler(req): req.content_type = 'text/plain' req.write(os.environ) req.write(os.getcwd()) # etc. return apache.OK </code></pre> <p><hr /></p> <p><strong>Edit</strong></p> <p>Now you have a glimpse of the <strong>Important Stuff</strong>. In this case it might be permissions -- you'll need to use os.filestat to be sure. Apache runs mod_python as a user who has almost no usable permissions. Apache does not like links, either, but this shouldn't affect mod_python. If your file doesn't have read-by-everybody and isn't in the right directory you'll have problems.</p> <p>You might want to switch to <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a>.</p>
4
2009-04-28T01:16:48Z
[ "python", "file-io", "mod-python" ]
How do you open and transfer a file on the filesystem in mod_python?
795,837
<p>I'm new to mod_python and Apache, and I'm having trouble returning a file to a user after a GET request. I've got a very simple setup right now, and was hoping to simply open the file and write it to the response:</p> <pre><code>from mod_python import apache def handler(req): req.content_type = 'application/octet-stream' fIn = open('response.bin', 'rb') req.write(fIn.read()) fIn.close() return apache.OK </code></pre> <p>However, I'm getting errors when I use open(), saying that the file doesn't exist (even though I've checked a dozen times that it does). This happens when using relative and absolute filepaths.</p> <p>I've got two questions: </p> <ul> <li>Why isn't open() finding the right files?</li> <li>What is the best way to return a file from the filesystem? (I ask to make sure I'm not missing some better way to use mod_python to return a file.)</li> </ul> <p>Thanks</p> <p>Edit: After finding this thread: <a href="http://www.programmingforums.org/thread12384.html" rel="nofollow">http://www.programmingforums.org/thread12384.html</a> I discovered that open() works for me if I move the file to another directory outside of home (I was aliasing out of /home/myname/httpdocs, but it works if I use /data). Any ideas why that works?</p> <p>Edit 2: Part of my debug error, as requested:</p> <pre><code>MOD_PYTHON ERROR ProcessId: 13642 Interpreter: '127.0.1.1' ServerName: '127.0.1.1' DocumentRoot: '/var/www' URI: '/test/mptest.py' Location: None Directory: '/home/myname/httpdocs/' Filename: '/home/myname/httpdocs/mptest.py' PathInfo: '' Phase: 'PythonHandler' Handler: 'mptest' Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1229, in _process_target result = _execute_target(config, req, object, arg) File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1128, in _execute_target result = object(arg) File "/home/myname/httpdocs/mptest.py", line 13, in handler fIn = open('/home/myname/httpdocs/files/response.bin', 'rb') IOError: [Errno 2] No such file or directory: '/home/myname/httpdocs/files/response.bin' </code></pre>
1
2009-04-28T00:53:59Z
795,896
<p>Could you paste the error(s) you get?</p> <p>It's likely to be a permission error (if you tried using the full path to the file). Remember the script runs as the user running the web-server process - so you will be accessing the file as "www-data", or "nobody" usually.</p> <p>Check the permissions of the folder <code>/home/myname/httpdocs/files/</code> also. The folder should be <code>+x</code> for the <code>www-data</code> user:</p> <pre><code>$ mkdir blah $ echo works &gt; blah/response.bin $ chmod 000 blah/ $ cat blah/response.bin cat: blah/response.bin: Permission denied $ chmod +x blah/ $ cat blah/response.bin works </code></pre> <p>You could eliminate Apache/your-script from the equation by doing the following:</p> <pre><code>you:~$ sudo su - www-data www-data:~$ file /home/myname/httpdocs/files/response.bin </code></pre> <p>(the su may not work, depending on what OS/distribution you are using, for example OS X prevents you logging in as it's <code>www</code> user)</p> <p>File permissions aside, why is the script dependant on a file in your home folder anyway? Can <code>response.bin</code> be moved to the same folder as your Python script? Or possibly even moved into a database? (perhaps SQLite? Might be unnecessary/excessive, depending on what is in <code>response.bin</code> and how much it changes)</p>
0
2009-04-28T01:27:47Z
[ "python", "file-io", "mod-python" ]
Is there anything in the Django / Python world equivalent to SimplePie Plugin for Wordpress?
795,976
<p>I know that SimplePie itself is derived from UFP, but the features I'm wondering about are the post-processing features that are available in SimplePie for WordPress plugin:</p> <p><a href="http://simplepie.org/wiki/plugins/wordpress/simplepie_plugin_for_wordpress/processing" rel="nofollow">http://simplepie.org/wiki/plugins/wordpress/simplepie_plugin_for_wordpress/processing</a></p> <p>Can I find something similar to this for my Django application?</p> <p>Can this be accomplished using Django inclusion tags?</p>
1
2009-04-28T02:09:21Z
795,990
<p><a href="http://www.djangosnippets.org/tags/rss/" rel="nofollow">http://www.djangosnippets.org/tags/rss/</a></p>
0
2009-04-28T02:19:12Z
[ "python", "django", "rss", "django-templates", "simplepie" ]
Is there anything in the Django / Python world equivalent to SimplePie Plugin for Wordpress?
795,976
<p>I know that SimplePie itself is derived from UFP, but the features I'm wondering about are the post-processing features that are available in SimplePie for WordPress plugin:</p> <p><a href="http://simplepie.org/wiki/plugins/wordpress/simplepie_plugin_for_wordpress/processing" rel="nofollow">http://simplepie.org/wiki/plugins/wordpress/simplepie_plugin_for_wordpress/processing</a></p> <p>Can I find something similar to this for my Django application?</p> <p>Can this be accomplished using Django inclusion tags?</p>
1
2009-04-28T02:09:21Z
1,819,895
<p>You are looking for <a href="http://feedparser.org" rel="nofollow">the universal feed parser</a>.</p>
1
2009-11-30T13:42:07Z
[ "python", "django", "rss", "django-templates", "simplepie" ]
Wrapping a script with subprocess.Popen()
795,977
<p>I have a script that's provided with another software package - which I would not like to modify in any way. I need to execute this script, provide a password, and then interact with it from the terminal (using raw_input, etc.).</p>
0
2009-04-28T02:09:29Z
795,984
<p><a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">pexpect</a> is what you want to use.</p> <blockquote> <p>Pexpect is a Python module for spawning child applications and controlling them automatically. Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup scripts for duplicating software package installations on different servers. It can be used for automated software testing. It should work on any platform that supports the standard Python pty module. The Pexpect interface focuses on ease of use so that simple tasks are easy.</p> </blockquote>
2
2009-04-28T02:14:58Z
[ "python", "scripting" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone unaware timestamps, which results in me getting this error:</p> <pre><code>TypeError: can't subtract offset-naive and offset-aware datetimes </code></pre> <p>Is there a way to avoid this (preferably without a third-party module being used).</p> <p>EDIT: Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG and always insert using:</p> <pre><code>NOW() AT TIME ZONE 'UTC' </code></pre> <p>That way all my timestamps are UTC by default (even though it's more annoying to do this).</p> <p>Hopefully I can eventually find a fix for this.</p>
105
2009-04-28T02:28:08Z
796,019
<p>have you tried to remove the timezone awareness?</p> <p>from <a href="http://pytz.sourceforge.net/">http://pytz.sourceforge.net/</a></p> <pre><code>naive = dt.replace(tzinfo=None) </code></pre> <p>may have to add time zone conversion as well.</p>
133
2009-04-28T02:36:07Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone unaware timestamps, which results in me getting this error:</p> <pre><code>TypeError: can't subtract offset-naive and offset-aware datetimes </code></pre> <p>Is there a way to avoid this (preferably without a third-party module being used).</p> <p>EDIT: Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG and always insert using:</p> <pre><code>NOW() AT TIME ZONE 'UTC' </code></pre> <p>That way all my timestamps are UTC by default (even though it's more annoying to do this).</p> <p>Hopefully I can eventually find a fix for this.</p>
105
2009-04-28T02:28:08Z
797,233
<p>Is there some pressing reason why you can't handle the age calculation in PostgreSQL itself? Something like</p> <pre><code>select *, age(timeStampField) as timeStampAge from myTable </code></pre>
1
2009-04-28T10:24:24Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone unaware timestamps, which results in me getting this error:</p> <pre><code>TypeError: can't subtract offset-naive and offset-aware datetimes </code></pre> <p>Is there a way to avoid this (preferably without a third-party module being used).</p> <p>EDIT: Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG and always insert using:</p> <pre><code>NOW() AT TIME ZONE 'UTC' </code></pre> <p>That way all my timestamps are UTC by default (even though it's more annoying to do this).</p> <p>Hopefully I can eventually find a fix for this.</p>
105
2009-04-28T02:28:08Z
17,752,647
<p>The psycopg2 module has its own timezone definitions, so I ended up writing my own wrapper around utcnow:</p> <pre><code>def pg_utcnow(): import psycopg2 return datetime.utcnow().replace( tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)) </code></pre> <p>and just use <code>pg_utcnow</code> whenever you need the current time to compare against a PostgreSQL <code>timestamptz</code></p>
4
2013-07-19T18:01:44Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone unaware timestamps, which results in me getting this error:</p> <pre><code>TypeError: can't subtract offset-naive and offset-aware datetimes </code></pre> <p>Is there a way to avoid this (preferably without a third-party module being used).</p> <p>EDIT: Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG and always insert using:</p> <pre><code>NOW() AT TIME ZONE 'UTC' </code></pre> <p>That way all my timestamps are UTC by default (even though it's more annoying to do this).</p> <p>Hopefully I can eventually find a fix for this.</p>
105
2009-04-28T02:28:08Z
23,370,174
<p>I know this is old, but just thought I would add my solution just in case someone finds it useful.</p> <p>I wanted to compare the local naive datetime with an aware datetime from a timeserver. I basically created a new naive datetime object using the aware datetime object. It's a bit of a hack and doesn't look very pretty but gets the job done.</p> <pre><code>import ntplib import datetime from datetime import timezone def utc_to_local(utc_dt): return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None) try: ntpt = ntplib.NTPClient() response = ntpt.request('pool.ntp.org') date = utc_to_local(datetime.datetime.utcfromtimestamp(response.tx_time)) sysdate = datetime.datetime.now() </code></pre> <p>...here comes the fudge...</p> <pre><code> temp_date = datetime.datetime(int(str(date)[:4]),int(str(date)[5:7]),int(str(date)[8:10]),int(str(date)[11:13]),int(str(date)[14:16]),int(str(date)[17:19])) dt_delta = temp_date-sysdate except Exception: print('Something went wrong :-(') </code></pre>
0
2014-04-29T16:24:36Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone unaware timestamps, which results in me getting this error:</p> <pre><code>TypeError: can't subtract offset-naive and offset-aware datetimes </code></pre> <p>Is there a way to avoid this (preferably without a third-party module being used).</p> <p>EDIT: Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG and always insert using:</p> <pre><code>NOW() AT TIME ZONE 'UTC' </code></pre> <p>That way all my timestamps are UTC by default (even though it's more annoying to do this).</p> <p>Hopefully I can eventually find a fix for this.</p>
105
2009-04-28T02:28:08Z
25,662,061
<p>The correct solution is to <em>add</em> the timezone info e.g., to get the current time as an aware datetime object in Python 3:</p> <pre><code>from datetime import datetime, timezone now = datetime.now(timezone.utc) </code></pre> <p>On older Python versions, you could define the <code>utc</code> tzinfo object yourself (example from datetime docs):</p> <pre><code>from datetime import tzinfo, timedelta, datetime ZERO = timedelta(0) class UTC(tzinfo): def utcoffset(self, dt): return ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return ZERO utc = UTC() </code></pre> <p>then:</p> <pre><code>now = datetime.now(utc) </code></pre>
27
2014-09-04T09:37:14Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone unaware timestamps, which results in me getting this error:</p> <pre><code>TypeError: can't subtract offset-naive and offset-aware datetimes </code></pre> <p>Is there a way to avoid this (preferably without a third-party module being used).</p> <p>EDIT: Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG and always insert using:</p> <pre><code>NOW() AT TIME ZONE 'UTC' </code></pre> <p>That way all my timestamps are UTC by default (even though it's more annoying to do this).</p> <p>Hopefully I can eventually find a fix for this.</p>
105
2009-04-28T02:28:08Z
30,971,376
<p>I know some people use Django specifically as an interface to abstract this type of database interaction. Django provides utilities that can be used for this:</p> <pre><code>from django.utils import timezone now_aware = timezone.now() </code></pre> <p>You do need to set up a basic Django settings infrastructure, even if you are just using this type of interface.</p> <p>By itself, this is probably nowhere near enough to motivate you to use Django as an interface, but there are many other perks. On the other hand, if you stumbled here because you were mangling your Django app (as I did), then perhaps this helps... </p>
16
2015-06-22T02:28:47Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone unaware timestamps, which results in me getting this error:</p> <pre><code>TypeError: can't subtract offset-naive and offset-aware datetimes </code></pre> <p>Is there a way to avoid this (preferably without a third-party module being used).</p> <p>EDIT: Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG and always insert using:</p> <pre><code>NOW() AT TIME ZONE 'UTC' </code></pre> <p>That way all my timestamps are UTC by default (even though it's more annoying to do this).</p> <p>Hopefully I can eventually find a fix for this.</p>
105
2009-04-28T02:28:08Z
32,926,239
<p>Holá<br> I found a very simple solution</p> <pre><code>tz_info = your_timezone_aware_variable.tzinfo diff = datetime.datetime.now(tz_info)-your_timezone_aware_variable </code></pre> <p>As explained by Sebastian you must add the timezone info to your now() time.<br> But you must add the same timezone of the variable not timezone.utc</p>
1
2015-10-03T18:51:24Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone unaware timestamps, which results in me getting this error:</p> <pre><code>TypeError: can't subtract offset-naive and offset-aware datetimes </code></pre> <p>Is there a way to avoid this (preferably without a third-party module being used).</p> <p>EDIT: Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG and always insert using:</p> <pre><code>NOW() AT TIME ZONE 'UTC' </code></pre> <p>That way all my timestamps are UTC by default (even though it's more annoying to do this).</p> <p>Hopefully I can eventually find a fix for this.</p>
105
2009-04-28T02:28:08Z
35,548,516
<p>I also faced the same problem. Then I found a solution after a lot of searching .</p> <p>The problem was that when we get the datetime object from model or form it is <strong>offset aware</strong> and if we get the time by system it is <strong>offset naive</strong>.</p> <p>So what I did is I got the current time using <strong>timezone.now()</strong> and import the timezone by <strong>from django.utils import timezone</strong> and put the <strong>USE_TZ = True</strong> in your project settings file.</p>
3
2016-02-22T08:01:18Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone unaware timestamps, which results in me getting this error:</p> <pre><code>TypeError: can't subtract offset-naive and offset-aware datetimes </code></pre> <p>Is there a way to avoid this (preferably without a third-party module being used).</p> <p>EDIT: Thanks for the suggestions, however trying to adjust the timezone seems to give me errors.. so I'm just going to use timezone unaware timestamps in PG and always insert using:</p> <pre><code>NOW() AT TIME ZONE 'UTC' </code></pre> <p>That way all my timestamps are UTC by default (even though it's more annoying to do this).</p> <p>Hopefully I can eventually find a fix for this.</p>
105
2009-04-28T02:28:08Z
38,576,091
<p>I've found <code>timezone.make_aware(datetime.datetime.now())</code> is helpful in django (I'm on 1.9.1). Unfortunately you can't simply make a <code>datetime</code> object offset-aware, then <code>timetz()</code> it. You have to make a <code>datetime</code> and make comparisons based on that.</p>
0
2016-07-25T19:39:16Z
[ "python", "postgresql", "datetime", "timezone" ]
IronPython - Convert int to byte array
796,197
<p>What is the correct way to get the length of a string in Python, and then convert that int to a byte array? What is the right way to print that to the console for testing?</p>
2
2009-04-28T04:19:47Z
796,222
<p>using .Net: </p> <pre><code>byte[] buffer = System.BitConverter.GetBytes(string.Length) print System.BitConverter.ToString(buffer) </code></pre> <p>That will output the bytes as hex. You may have to clean up the syntax for IronPython.</p>
1
2009-04-28T04:29:20Z
[ ".net", "python", "ironpython", "bytearray" ]
IronPython - Convert int to byte array
796,197
<p>What is the correct way to get the length of a string in Python, and then convert that int to a byte array? What is the right way to print that to the console for testing?</p>
2
2009-04-28T04:19:47Z
796,254
<p>Use <a href="http://docs.python.org/library/struct" rel="nofollow">struct</a>.</p> <pre><code>import struct print struct.pack('L', len("some string")) # int to a (long) byte array </code></pre>
3
2009-04-28T04:40:15Z
[ ".net", "python", "ironpython", "bytearray" ]
How to limit choice field options based on another choice field in django admin
796,466
<p>I have the following models:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) class Demo(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) item = models.ForeignKey(Item) </code></pre> <p>In the admin interface when creating a new Demo, after user picks category from the dropdown, I would like to limit the number of choices in the "items" drop-down. If user selects another category then the item choices should update accordingly. I would like to limit item choices right on the client, before it even hits the form validation on the server. This is for usability, because the list of items could be 1000+ being able to narrow it down by category would help to make it more manageable.</p> <p>Is there a "django-way" of doing it or is custom JavaScript the only option here?</p>
9
2009-04-28T06:28:14Z
796,510
<p>Am thinking JavaScript/AJAX will be the best approach for this problem.</p>
0
2009-04-28T06:47:24Z
[ "javascript", "python", "django", "django-admin" ]
How to limit choice field options based on another choice field in django admin
796,466
<p>I have the following models:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) class Demo(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) item = models.ForeignKey(Item) </code></pre> <p>In the admin interface when creating a new Demo, after user picks category from the dropdown, I would like to limit the number of choices in the "items" drop-down. If user selects another category then the item choices should update accordingly. I would like to limit item choices right on the client, before it even hits the form validation on the server. This is for usability, because the list of items could be 1000+ being able to narrow it down by category would help to make it more manageable.</p> <p>Is there a "django-way" of doing it or is custom JavaScript the only option here?</p>
9
2009-04-28T06:28:14Z
796,567
<p>Here is some javascript (JQuery based) to change the item option values when category changes:</p> <pre><code>&lt;script charset="utf-8" type="text/javascript"&gt; $(function(){ $("select#id_category").change(function(){ $.getJSON("/items/",{id: $(this).val(), view: 'json'}, function(j) { var options = '&lt;option value=""&gt;--------&amp;nbsp;&lt;/option&gt;'; for (var i = 0; i &lt; j.length; i++) { options += '&lt;option value="' + j[i].optionValue + '"&gt;' + j[i].optionDisplay + '&lt;/option&gt;'; } $("#id_item").html(options); $("#id_item option:first").attr('selected', 'selected'); }) $("#id_category").attr('selected', 'selected'); }) }) &lt;/script&gt; </code></pre> <p>You need a view to be called on the /items/ URL that supplies a JSON list of the valid items.</p> <p>You can hook this into your admin by using <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions">model admin media definitions</a>.</p>
10
2009-04-28T07:07:33Z
[ "javascript", "python", "django", "django-admin" ]
How to limit choice field options based on another choice field in django admin
796,466
<p>I have the following models:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) class Demo(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) item = models.ForeignKey(Item) </code></pre> <p>In the admin interface when creating a new Demo, after user picks category from the dropdown, I would like to limit the number of choices in the "items" drop-down. If user selects another category then the item choices should update accordingly. I would like to limit item choices right on the client, before it even hits the form validation on the server. This is for usability, because the list of items could be 1000+ being able to narrow it down by category would help to make it more manageable.</p> <p>Is there a "django-way" of doing it or is custom JavaScript the only option here?</p>
9
2009-04-28T06:28:14Z
797,007
<p>You will need to have some kind of non-server based mechanism of filtering the objects. Either that, or you can reload the page when the selection is made (which is likely to be done in JavaScript anyway).</p> <p>Otherwise, there is no way to get the subset of data from the server to the client.</p>
0
2009-04-28T09:30:30Z
[ "javascript", "python", "django", "django-admin" ]
How to limit choice field options based on another choice field in django admin
796,466
<p>I have the following models:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) class Demo(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) item = models.ForeignKey(Item) </code></pre> <p>In the admin interface when creating a new Demo, after user picks category from the dropdown, I would like to limit the number of choices in the "items" drop-down. If user selects another category then the item choices should update accordingly. I would like to limit item choices right on the client, before it even hits the form validation on the server. This is for usability, because the list of items could be 1000+ being able to narrow it down by category would help to make it more manageable.</p> <p>Is there a "django-way" of doing it or is custom JavaScript the only option here?</p>
9
2009-04-28T06:28:14Z
18,093,010
<p>There is <a href="https://github.com/digi604/django-smart-selects" rel="nofollow">django-smart-selects</a>:</p> <p>If you have the following model:</p> <pre><code>class Location(models.Model) continent = models.ForeignKey(Continent) country = models.ForeignKey(Country) area = models.ForeignKey(Area) city = models.CharField(max_length=50) street = models.CharField(max_length=100) </code></pre> <p>And you want that if you select a continent only the countries are available that are located on this continent and the same for areas you can do the following:</p> <pre><code>from smart_selects.db_fields import ChainedForeignKey class Location(models.Model) continent = models.ForeignKey(Continent) country = ChainedForeignKey( Country, chained_field="continent", chained_model_field="continent", show_all=False, auto_choose=True ) area = ChainedForeignKey(Area, chained_field="country", chained_model_field="country") city = models.CharField(max_length=50) street = models.CharField(max_length=100) </code></pre>
2
2013-08-07T01:06:07Z
[ "javascript", "python", "django", "django-admin" ]
python method to extract content (excluding navigation) from an HTML page
796,490
<p>Of course an HTML page can be parsed using any number of python parsers, but I'm surprised that there don't seem to be any public parsing scripts to extract meaningful content (excluding sidebars, navigation, etc.) from a given HTML doc. </p> <p>I'm guessing it's something like collecting DIV and P elements and then checking them for a minimum amount of text content, but I'm sure a solid implementation would include plenty of things that I haven't thought of.</p>
8
2009-04-28T06:40:28Z
796,530
<p>What is meaningful and what is not, it depends on the semantic of the page. If the semantics is crappy, your code won't "guess" what is meaningful. I use readability, which you linked in the comment, and I see that on many pages I try to read it does not provide any result, not talking about a decent one.</p> <p>If someone puts the content in a table, you're doomed. Try readability on a phpbb forum you'll see what I mean.</p> <p>If you want to do it, go with a regexp on <code>&lt;p&gt;&lt;/p&gt;</code>, or parse the DOM.</p>
1
2009-04-28T06:52:49Z
[ "python", "html", "parsing", "semantics", "html-content-extraction" ]
python method to extract content (excluding navigation) from an HTML page
796,490
<p>Of course an HTML page can be parsed using any number of python parsers, but I'm surprised that there don't seem to be any public parsing scripts to extract meaningful content (excluding sidebars, navigation, etc.) from a given HTML doc. </p> <p>I'm guessing it's something like collecting DIV and P elements and then checking them for a minimum amount of text content, but I'm sure a solid implementation would include plenty of things that I haven't thought of.</p>
8
2009-04-28T06:40:28Z
796,810
<p>Try the <a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> library for Python. It has very simple methods to extract information from an html file.</p> <p>Trying to generically extract data from webpages would require people to write their pages in a similar way... but there's an almost infinite number of ways to convey a page that looks identical let alone all the conbinations you can have to convey the same information.</p> <p>Was there a particular type of information you were trying to extract or some other end goal?</p> <p>You could try extracting any content in 'div' and 'p' markers and compare the relative sizes of all the information in the page. The problem then is that people probably group information into collections of 'div's and 'p's (or at least they do if they're writing well formed html!).</p> <p>Maybe if you formed a tree of how the information is related (nodes would be the 'p' or 'div or whatever and each node would contain the associated text) you could do some sort of analysis to identify the smallest 'p' or 'div' that encompases what appears to be the majority of the information.. ?</p> <p><strong>[EDIT]</strong> Maybe if you can get it into the tree structure I suggested, you could then use a similar points system to spam assassin. Define some rules that attempt to classify the information. Some examples:</p> <pre><code>+1 points for every 100 words +1 points for every child element that has &gt; 100 words -1 points if the section name contains the word 'nav' -2 points if the section name contains the word 'advert' </code></pre> <p>If you have a lots of low scoring rules which add up when you find more relevent looking sections, I think that could evolve into a fairly powerful and robust technique.</p> <p><strong>[EDIT2]</strong> Looking at the readability, it seems to be doing pretty much exactly what I just suggested! Maybe it could be improved to try and understand tables better?</p>
5
2009-04-28T08:28:45Z
[ "python", "html", "parsing", "semantics", "html-content-extraction" ]
python method to extract content (excluding navigation) from an HTML page
796,490
<p>Of course an HTML page can be parsed using any number of python parsers, but I'm surprised that there don't seem to be any public parsing scripts to extract meaningful content (excluding sidebars, navigation, etc.) from a given HTML doc. </p> <p>I'm guessing it's something like collecting DIV and P elements and then checking them for a minimum amount of text content, but I'm sure a solid implementation would include plenty of things that I haven't thought of.</p>
8
2009-04-28T06:40:28Z
797,700
<p>Have a look at templatemaker: <a href="http://www.holovaty.com/writing/templatemaker/" rel="nofollow">http://www.holovaty.com/writing/templatemaker/</a></p> <p>It's written by one of the founders of Django. Basically you feed it a few example html files and it will generate a "template" that you can then use to extract just the bits that are different (which is usually the meaningful content).</p> <p>Here's an example from the <a href="http://code.google.com/p/templatemaker/" rel="nofollow">google code page</a>:</p> <pre> <code> # Import the Template class. >>> from templatemaker import Template # Create a Template instance. >>> t = Template() # Learn a Sample String. >>> t.learn('&lt;b&gt;this and that&lt;/b&gt;') # Output the template so far, using the "!" character to mark holes. # We've only learned a single string, so the template has no holes. >>> t.as_text('!') '&lt;b&gt;this and that&lt;/b&gt;' # Learn another string. The True return value means the template gained # at least one hole. >>> t.learn('&lt;b&gt;alex and sue&lt;/b&gt;') True # Sure enough, the template now has some holes. >>> t.as_text('!') '&lt;b&gt;! and !&lt;/b&gt;' </code> </pre>
4
2009-04-28T12:43:09Z
[ "python", "html", "parsing", "semantics", "html-content-extraction" ]
python method to extract content (excluding navigation) from an HTML page
796,490
<p>Of course an HTML page can be parsed using any number of python parsers, but I'm surprised that there don't seem to be any public parsing scripts to extract meaningful content (excluding sidebars, navigation, etc.) from a given HTML doc. </p> <p>I'm guessing it's something like collecting DIV and P elements and then checking them for a minimum amount of text content, but I'm sure a solid implementation would include plenty of things that I haven't thought of.</p>
8
2009-04-28T06:40:28Z
4,239,655
<p>You might use the <a href="http://boilerpipe-web.appspot.com/" rel="nofollow">boilerpipe Web application</a> to fetch and extract content on the fly.</p> <p>(This is not specific to Python, as you only need to issue a HTTP GET request to a page on Google AppEngine).</p> <p>Cheers,</p> <p>Christian</p>
3
2010-11-21T18:59:34Z
[ "python", "html", "parsing", "semantics", "html-content-extraction" ]
python method to extract content (excluding navigation) from an HTML page
796,490
<p>Of course an HTML page can be parsed using any number of python parsers, but I'm surprised that there don't seem to be any public parsing scripts to extract meaningful content (excluding sidebars, navigation, etc.) from a given HTML doc. </p> <p>I'm guessing it's something like collecting DIV and P elements and then checking them for a minimum amount of text content, but I'm sure a solid implementation would include plenty of things that I haven't thought of.</p>
8
2009-04-28T06:40:28Z
24,899,593
<p><a href="https://github.com/grangier/python-goose" rel="nofollow">Goose</a> is just the library for this task. To quote their README:</p> <blockquote> <p>Goose will try to extract the following information:</p> <ul> <li>Main text of an article </li> <li>Main image of article</li> <li>Any Youtube/Vimeo movies embedded in article </li> <li>Meta Description </li> <li>Meta tags</li> </ul> </blockquote>
0
2014-07-22T23:39:26Z
[ "python", "html", "parsing", "semantics", "html-content-extraction" ]
CGI & Python
796,906
<p>here is my problem... I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision ! Now I have to implement a web interface, and here comes the problems ... I created an htm file with a simple form that, once the user "submits" he passes the parameters to a cgi script that contains just one line and runs my python program ! And seems to work ... My question is : if it happens that the program needs to ask the user for a choice, how can I return this value to my python script ! To prompt the user for a choice I need to create a webpage with the possible choices ... Does anybody know how can I open a webpage with python ? The second and most important question is: how can I return a value from a web page to my "original" python module ?? In python I would simply make a </p> <p>return choice</p> <p>but with a web page I have no idea how to do it !!</p> <p>Recap: 1. Starting from a web page, I run a cgi script ! Done</p> <ol> <li><p>This CGI script runs my python program... Done</p></li> <li><p>If the program is not able to take a decision,</p> <p>3a create a web page with the possible choices I can do it</p> <p>3b display the created web page ????????</p> <p>3c return the responce to the original pyhon module ????????</p></li> </ol> <p>thanks in advance</p>
0
2009-04-28T09:02:13Z
797,041
<p>Web pages don't return values, and they aren't programs - a web page is just a static collection of HTML or something similar which a browser can display. Your CGI script can't wait for the user to send a response - it must send the web page to the user and terminate.</p> <p>However, if the browser performs a second query to your CGI program (or a different CGI program) based on the data in that page, then you can collect the information that way and continue from that point.</p>
0
2009-04-28T09:39:17Z
[ "python", "cgi" ]
CGI & Python
796,906
<p>here is my problem... I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision ! Now I have to implement a web interface, and here comes the problems ... I created an htm file with a simple form that, once the user "submits" he passes the parameters to a cgi script that contains just one line and runs my python program ! And seems to work ... My question is : if it happens that the program needs to ask the user for a choice, how can I return this value to my python script ! To prompt the user for a choice I need to create a webpage with the possible choices ... Does anybody know how can I open a webpage with python ? The second and most important question is: how can I return a value from a web page to my "original" python module ?? In python I would simply make a </p> <p>return choice</p> <p>but with a web page I have no idea how to do it !!</p> <p>Recap: 1. Starting from a web page, I run a cgi script ! Done</p> <ol> <li><p>This CGI script runs my python program... Done</p></li> <li><p>If the program is not able to take a decision,</p> <p>3a create a web page with the possible choices I can do it</p> <p>3b display the created web page ????????</p> <p>3c return the responce to the original pyhon module ????????</p></li> </ol> <p>thanks in advance</p>
0
2009-04-28T09:02:13Z
797,111
<p>I think you could modify the Python script to return an error if it needs a choice and accept choices as arguments. If you do that, you can check the return value from your cgi script and use that to call the python script appropriately and return the information to the user.</p> <p>Is there a reason why you can't call the python script directly? I suspect you'd end up with a neater implementation if you were to avoid the intermediate CGI.</p> <p>What webserver are you using? What cgi language? Perl maybe?</p>
1
2009-04-28T09:58:42Z
[ "python", "cgi" ]
CGI & Python
796,906
<p>here is my problem... I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision ! Now I have to implement a web interface, and here comes the problems ... I created an htm file with a simple form that, once the user "submits" he passes the parameters to a cgi script that contains just one line and runs my python program ! And seems to work ... My question is : if it happens that the program needs to ask the user for a choice, how can I return this value to my python script ! To prompt the user for a choice I need to create a webpage with the possible choices ... Does anybody know how can I open a webpage with python ? The second and most important question is: how can I return a value from a web page to my "original" python module ?? In python I would simply make a </p> <p>return choice</p> <p>but with a web page I have no idea how to do it !!</p> <p>Recap: 1. Starting from a web page, I run a cgi script ! Done</p> <ol> <li><p>This CGI script runs my python program... Done</p></li> <li><p>If the program is not able to take a decision,</p> <p>3a create a web page with the possible choices I can do it</p> <p>3b display the created web page ????????</p> <p>3c return the responce to the original pyhon module ????????</p></li> </ol> <p>thanks in advance</p>
0
2009-04-28T09:02:13Z
797,129
<p>Probably easier if you write your cgi in python then call your python script from the cgi script.</p> <p>Update your script to separate the UI from the logic. Then it should be relatively easy to interface your script with the (python) cgi script.</p> <p>For python cgi reference: <a href="http://gnosis.cx/publish/programming/feature%5F5min%5Fpython.html" rel="nofollow">Five minutes to a Python CGI</a></p>
0
2009-04-28T10:00:42Z
[ "python", "cgi" ]
CGI & Python
796,906
<p>here is my problem... I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision ! Now I have to implement a web interface, and here comes the problems ... I created an htm file with a simple form that, once the user "submits" he passes the parameters to a cgi script that contains just one line and runs my python program ! And seems to work ... My question is : if it happens that the program needs to ask the user for a choice, how can I return this value to my python script ! To prompt the user for a choice I need to create a webpage with the possible choices ... Does anybody know how can I open a webpage with python ? The second and most important question is: how can I return a value from a web page to my "original" python module ?? In python I would simply make a </p> <p>return choice</p> <p>but with a web page I have no idea how to do it !!</p> <p>Recap: 1. Starting from a web page, I run a cgi script ! Done</p> <ol> <li><p>This CGI script runs my python program... Done</p></li> <li><p>If the program is not able to take a decision,</p> <p>3a create a web page with the possible choices I can do it</p> <p>3b display the created web page ????????</p> <p>3c return the responce to the original pyhon module ????????</p></li> </ol> <p>thanks in advance</p>
0
2009-04-28T09:02:13Z
797,231
<p>"Does anybody know how can I open a webpage with python ? The second and most important question is: how can I return a value from a web page to my "original" python module ??"</p> <p>This is all very simple.</p> <p>However, you need to read about what the web really <em>is</em>. You need to read up on web servers, browsers and the HTTP protocol.</p> <p>Here's the golden rule: <strong>A web server responds to HTTP requests with a web page.</strong></p> <p>The second part of that rules is: <strong>A Request is a URL and a method (GET or POST).</strong> There's more to a request, but that's the important part.</p> <p>That's all that ever happens. So, you have to recast your use case into the above form.</p> <p>Person clicks a bookmark; browser makes an empty request (to a URL of "/") and gets a form. </p> <p>Person fills in the form, clicks the button; browser POST's the request (to the URL in the form) and gets one of two things.</p> <ul> <li><p>If your script worked, they get their page that says it all worked.</p></li> <li><p>If your script needed information, they get another form.</p></li> </ul> <p>Person fills in the form, clicks the button; browser POST's the request (to the URL in the form) and gets the final page that says it all worked.</p> <p>You can do all of this from a "CGI" script. Use mod_wsgi and plug your stuff into the Apache web server.</p> <p>Or, you can get a web framework. Django, TurboGears, web.py, etc. You'll be happier with a framework even though you think your operation is simple.</p>
9
2009-04-28T10:23:47Z
[ "python", "cgi" ]
CGI & Python
796,906
<p>here is my problem... I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision ! Now I have to implement a web interface, and here comes the problems ... I created an htm file with a simple form that, once the user "submits" he passes the parameters to a cgi script that contains just one line and runs my python program ! And seems to work ... My question is : if it happens that the program needs to ask the user for a choice, how can I return this value to my python script ! To prompt the user for a choice I need to create a webpage with the possible choices ... Does anybody know how can I open a webpage with python ? The second and most important question is: how can I return a value from a web page to my "original" python module ?? In python I would simply make a </p> <p>return choice</p> <p>but with a web page I have no idea how to do it !!</p> <p>Recap: 1. Starting from a web page, I run a cgi script ! Done</p> <ol> <li><p>This CGI script runs my python program... Done</p></li> <li><p>If the program is not able to take a decision,</p> <p>3a create a web page with the possible choices I can do it</p> <p>3b display the created web page ????????</p> <p>3c return the responce to the original pyhon module ????????</p></li> </ol> <p>thanks in advance</p>
0
2009-04-28T09:02:13Z
1,635,259
<p><a href="http://docs.python.org/library/cgihttpserver.html" rel="nofollow">http://docs.python.org/library/cgihttpserver.html</a></p> <p>I think first off you need to separate your code from your interface. When you run a script, it spits out a page. You can pass arguments to it using url parameters. Ideally you want to do your logic, and then pass the results into a template that python prints to the cgi.</p>
0
2009-10-28T04:49:21Z
[ "python", "cgi" ]
Is windows's setsockopt broken?
796,957
<p>I want to be able to reuse some ports, and that's why I'm using <strong>setsockopt</strong> on my sockets, with the following code:</p> <pre><code>sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) </code></pre> <p>However, this doesn't really work. I'm not getting a bind error either, but the server socket just isn't responding (it seems to start , but if I try to connect to it, it doesn't enter the select loop). This behaviour appears if the script ended unexpectedly, and if I change the port the server is listening on, everything works again. Can you provide some advice?</p> <p>EDIT: I renamed the socket to sock. It was just a name I chose for this code snippet.</p>
2
2009-04-28T09:14:59Z
797,004
<p><code>setsockopt</code> is a method of a socket object. module <code>socket</code> doesn't have a <code>setsockopt</code> attribute.</p>
1
2009-04-28T09:30:02Z
[ "python", "windows", "sockets", "setsockopt" ]
Is windows's setsockopt broken?
796,957
<p>I want to be able to reuse some ports, and that's why I'm using <strong>setsockopt</strong> on my sockets, with the following code:</p> <pre><code>sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) </code></pre> <p>However, this doesn't really work. I'm not getting a bind error either, but the server socket just isn't responding (it seems to start , but if I try to connect to it, it doesn't enter the select loop). This behaviour appears if the script ended unexpectedly, and if I change the port the server is listening on, everything works again. Can you provide some advice?</p> <p>EDIT: I renamed the socket to sock. It was just a name I chose for this code snippet.</p>
2
2009-04-28T09:14:59Z
2,292,896
<p>It appears that SO_REUSEADDR has different semantics on Windows vs Unix.</p> <p>See this <a href="http://msdn.microsoft.com/en-us/library/ms740621%28VS.85%29.aspx" rel="nofollow">msdn article</a> (particularly the chart below "Using SO_EXCLUSIVEADDRUSE") and this <a href="http://www.developerweb.net/forum/showthread.php?t=2981" rel="nofollow">unix faq</a>.</p> <p>Also, see this <a href="http://bugs.python.org/issue2550" rel="nofollow">python bug discussion</a>, this <a href="http://twistedmatrix.com/trac/ticket/1151" rel="nofollow">twisted bug discussion</a>, and this list of differences <a href="http://itamarst.org/writings/win32sockets.html" rel="nofollow">between Windows and Unix sockets</a>.</p>
3
2010-02-18T23:00:36Z
[ "python", "windows", "sockets", "setsockopt" ]
How to query filter in django without multiple occurrences
796,971
<p>I have 2 models:</p> <p>ParentModel: 'just' sits there</p> <p>ChildModel: has a foreign key to ParentModel</p> <p><code>ParentModel.objects.filter(childmodel__in=ChildModel.objects.all())</code> gives multiple occurrences of ParentModel.</p> <p>How do I query all ParentModels that have at least one ChildModel that's referring to it? And without multiple occurrences...</p>
1
2009-04-28T09:20:54Z
797,013
<p>You almost got it right...</p> <pre><code>ParentModel.objects.filter(childmodel__in=ChildModel.objects.all()).distinct() </code></pre>
4
2009-04-28T09:31:16Z
[ "python", "django" ]
How to query filter in django without multiple occurrences
796,971
<p>I have 2 models:</p> <p>ParentModel: 'just' sits there</p> <p>ChildModel: has a foreign key to ParentModel</p> <p><code>ParentModel.objects.filter(childmodel__in=ChildModel.objects.all())</code> gives multiple occurrences of ParentModel.</p> <p>How do I query all ParentModels that have at least one ChildModel that's referring to it? And without multiple occurrences...</p>
1
2009-04-28T09:20:54Z
808,051
<p>You might want to avoid using <code>childmodel__in=ChildModel.objects.all()</code> if the number of <code>ChildModel</code> objects is large. This will generate SQL with all <code>ChildModel</code> id's enumerated in a list, possibly creating a huge SQL query.</p> <p>If you can use <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/#topics-db-aggregation" rel="nofollow">Django 1.1 with aggregation</a> support, you could do something like:</p> <pre><code>ParentModel.objects.annotate(num_children=Count('child')).filter(num_children__gte=1) </code></pre> <p>which should generate better SQL.</p>
0
2009-04-30T17:12:31Z
[ "python", "django" ]
string formatting
797,132
<p>I am not getting why the colon shifted left in the second time </p> <pre><code>&gt;&gt;&gt; print '%5s' %':' : &gt;&gt;&gt; print '%5s' %':' '%2s' %':' : : </code></pre> <p>Help me out of this please</p>
0
2009-04-28T10:01:34Z
797,156
<p>What are you trying to do?</p> <pre><code>&gt;&gt;&gt; print '%5s' % ':' : &gt;&gt;&gt; print '%5s%2s' % (':', ':') : : </code></pre> <p>You could achieve what you want by mixing them both into a single string formatting expression.</p>
2
2009-04-28T10:05:45Z
[ "python", "string", "format" ]
string formatting
797,132
<p>I am not getting why the colon shifted left in the second time </p> <pre><code>&gt;&gt;&gt; print '%5s' %':' : &gt;&gt;&gt; print '%5s' %':' '%2s' %':' : : </code></pre> <p>Help me out of this please</p>
0
2009-04-28T10:01:34Z
797,167
<p>In Python, juxtaposed strings are concatenated:</p> <pre><code>&gt;&gt;&gt; t = 'a' 'bcd' &gt;&gt;&gt; t 'abcd' </code></pre> <p>So in your second example, it is equivalent to:</p> <pre><code>&gt;&gt;&gt; print '%5s' % ':%2s' % ':' </code></pre> <p>which by the precedence rules for Python's % operator, is:</p> <pre><code>&gt;&gt;&gt; print ('%5s' % ':%2s') % ':' </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; print ' :%2s' % ':' : : </code></pre>
9
2009-04-28T10:08:15Z
[ "python", "string", "format" ]
import statement fails for one module
797,241
<p>Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help.</p> <p>I have a series of import statements, the last of which will not work. Any idea why? options.py is sitting in the same directory as everything else.</p> <pre><code>from snipplets.main import MainHandler from snipplets.createnew import CreateNewHandler from snipplets.db import DbSnipplet from snipplets.highlight import HighLighter from snipplets.options import Options </code></pre> <p>ImportError: No module named options</p> <p>my __init__.py file in the snipplets directory is blank.</p>
2
2009-04-28T10:26:05Z
797,290
<p>I suspect that one of your other imports redefined <code>snipplets</code> with an assignment statement. Or one of your other modules changed <code>sys.path</code>.</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>"so the flow goes like this: add snipplets packages to path import..." </p> <p>No.</p> <p>Do not modify <code>sys.path</code> -- that way lies problems. Modifying <code>site.path</code> leads to ambiguity about what is -- or is not -- on the path, and what order they are in. </p> <p>The simplest, most reliable, most obvious, most controllable things to do are the following. Pick exactly one.</p> <ul> <li><p>Define <code>PYTHONPATH</code> (once, external to your program). A single, simple environment variable that is nearly identical to installation on site-packages.</p></li> <li><p>Install your package in site-packages.</p></li> </ul>
2
2009-04-28T10:48:42Z
[ "python" ]
import statement fails for one module
797,241
<p>Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help.</p> <p>I have a series of import statements, the last of which will not work. Any idea why? options.py is sitting in the same directory as everything else.</p> <pre><code>from snipplets.main import MainHandler from snipplets.createnew import CreateNewHandler from snipplets.db import DbSnipplet from snipplets.highlight import HighLighter from snipplets.options import Options </code></pre> <p>ImportError: No module named options</p> <p>my __init__.py file in the snipplets directory is blank.</p>
2
2009-04-28T10:26:05Z
797,308
<p>your <a href="http://github.com/woodenbrick/snipplets/tree/68e40dcfa1195cc63d4e1155b8353bb1aa1f8797/snipplets" rel="nofollow">master branch</a> doesn't have <code>options.py</code>. could it be that you dev and master branches are conflicting?</p> <p><a href="http://github.com/woodenbrick/snipplets/blob/2c13a6de0ae5c6cb752bbc37e2620e823e498c97/bin/snipplets" rel="nofollow">if this is your actual code</a> then you have <code>option</code> variable at line 21.</p>
2
2009-04-28T10:58:38Z
[ "python" ]
import statement fails for one module
797,241
<p>Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help.</p> <p>I have a series of import statements, the last of which will not work. Any idea why? options.py is sitting in the same directory as everything else.</p> <pre><code>from snipplets.main import MainHandler from snipplets.createnew import CreateNewHandler from snipplets.db import DbSnipplet from snipplets.highlight import HighLighter from snipplets.options import Options </code></pre> <p>ImportError: No module named options</p> <p>my __init__.py file in the snipplets directory is blank.</p>
2
2009-04-28T10:26:05Z
797,336
<p>Does the following work?</p> <pre><code>import snipplets.options.Options </code></pre> <p>If so, one of your other snipplets files probably sets a global variable named options.</p>
1
2009-04-28T11:05:06Z
[ "python" ]
import statement fails for one module
797,241
<p>Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help.</p> <p>I have a series of import statements, the last of which will not work. Any idea why? options.py is sitting in the same directory as everything else.</p> <pre><code>from snipplets.main import MainHandler from snipplets.createnew import CreateNewHandler from snipplets.db import DbSnipplet from snipplets.highlight import HighLighter from snipplets.options import Options </code></pre> <p>ImportError: No module named options</p> <p>my __init__.py file in the snipplets directory is blank.</p>
2
2009-04-28T10:26:05Z
797,474
<p>Are you on windows? You might want to try defining an <code>__</code>all<code>__</code> list in your <code>__</code>init<code>__</code>.py file like noted <a href="http://docs.python.org/tutorial/modules.html#importing-from-a-package" rel="nofollow">here</a>. It shouldn't make a difference unless you're importing *, but I've seen modules not import unless they were defined there.</p> <p>Secondly, you might try setting up a <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a>. Using a lot of site-wide python packages can lead to these kinds of things.</p> <p>Lastly, make sure the permissions of options are set correctly. I've spent hours trying to figure these things out only to find out it was an issue of me not having permission to import it.</p>
1
2009-04-28T11:50:12Z
[ "python" ]
how can I debug more than one script in pyscripter?
797,754
<p>I installed portable python on my USB drive, and I really like pyscripter a lot. The thing is, after I start debugging a script, the IDE kind of freezes ( waiting for the code to reach a breakpoint ). This means I can't do anything with it ( I can't even save files ). It would be very useful to be able to debug more than one script at a time.</p> <p>I even tried starting a new instance of the IDE, but it comes back to the one open. Is there something I can do to be able to debug more than one script at a given time ?</p>
0
2009-04-28T12:52:22Z
802,044
<p>To solve your problem, use <a href="http://pyscripter.googlepages.com/remotepythonengines" rel="nofollow">Remote Interpreter and Debugger</a> and PyScripter will become much more responsive. Even if something goes wrong, IDE will not crash - just reinitialize remote interpreter and resume working.</p>
1
2009-04-29T12:02:23Z
[ "python", "ide", "debugging", "pyscripter" ]
Python "protected" attributes
797,771
<p>How do I access a private attribute of a parent class from a subclass (without making it public)?</p>
21
2009-04-28T12:55:50Z
797,782
<p>Make an accessor method, unless I am missing something:</p> <pre><code>def get_private_attrib(self): return self.__privateWhatever </code></pre>
0
2009-04-28T12:57:45Z
[ "python" ]
Python "protected" attributes
797,771
<p>How do I access a private attribute of a parent class from a subclass (without making it public)?</p>
21
2009-04-28T12:55:50Z
797,799
<p>if the variable name is "__secret" and the class name is "MyClass" you can access it like this on an instance named "var"</p> <p>var._MyClass__secret</p> <p>The convention to suggest/emulate protection is to name it with a leading underscore: self._protected_variable = 10</p> <p>Of course, anybody can modify it if it really wants.</p>
1
2009-04-28T13:00:58Z
[ "python" ]
Python "protected" attributes
797,771
<p>How do I access a private attribute of a parent class from a subclass (without making it public)?</p>
21
2009-04-28T12:55:50Z
797,814
<p>My understanding of Python convention is</p> <ul> <li>_member is protected</li> <li>__member is private</li> </ul> <p>Options for if you control the parent class</p> <ul> <li>Make it protected instead of private since that seems like what you really want</li> <li>Use a getter (@property def _protected_access_to_member...) to limit the protected access</li> </ul> <p>If you don't control it</p> <ul> <li>Undo the name mangling. If you dir(object) you will see names something like _Class__member which is what Python does to leading __ to "make it private". There isn't truly private in python. This is probably considered evil.</li> </ul>
52
2009-04-28T13:03:31Z
[ "python" ]
Python "protected" attributes
797,771
<p>How do I access a private attribute of a parent class from a subclass (without making it public)?</p>
21
2009-04-28T12:55:50Z
5,682,623
<p>Using <code>@property</code> and <code>@name.setter</code> to do what you want</p> <p>e.g</p> <pre><code>class Stock(object): def __init__(self, stockName): # '_' is just a convention and does nothing self.__stockName = stockName # private now @property # when you do Stock.name, it will call this function def name(self): return self.__stockName @name.setter # when you do Stock.name = x, it will call this function def name(self, name): self.__stockName = name if __name__ == "__main__": myStock = Stock("stock111") myStock.__stockName # It is private. You can't access it. #Now you can myStock.name N = float(raw_input("input to your stock: " + str(myStock.name)+" ? ")) </code></pre>
6
2011-04-15T21:39:30Z
[ "python" ]
Python "protected" attributes
797,771
<p>How do I access a private attribute of a parent class from a subclass (without making it public)?</p>
21
2009-04-28T12:55:50Z
21,217,121
<p>Some language designers subscribe to the following assumption:</p> <blockquote> <p><em>"Many programmers are irresponsible, dim-witted, or both."</em></p> </blockquote> <p>These language designers will feel tempted to protect programmers from each other by introducing a <code>private</code> specifier into their language. Shortly later they recognize that this is often too inflexible and introduce <code>protected</code> as well.</p> <p>Language designers such as Python's Guido van Rossum, in contrast, assume that programmers are responsible adults and capable of good judgment (perhaps not always, but typically). They find that everybody should be able to access the elements of a program if there is a need to do that, so that the language does not get in the way of doing the right thing. (The only programming language that can successfully get in the way of doing the <em>wrong</em> thing is the <a href="http://www.netfunny.com/rhf/jokes/new90/nullang.html">NULL</a> language)</p> <p>Therefore, <code>_myfield</code> in Python means something like "The designer of this module is doing some non-obvious stuff with this attribute, so please do not modify it and stay away from even reading it if you can -- suitable ways to access relevant information have been provided."</p> <p>In case you are not able to stay away from accessing <code>_myfield</code> (such as in special cases in a subclass), you simply access it.</p>
13
2014-01-19T13:06:06Z
[ "python" ]
Django caching - can it be done pre-emptively?
797,773
<p>I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup.</p> <p>This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a significant delay of a few seconds while I go to the external site to parse the new data.</p> <p>Is there any way to load the new data lazily so that no user will ever get that kind of delay? Or is this unavoidable?</p> <p><em>Please note that I am on a shared hosting server, so keep that in mind with your answers.</em></p> <p><strong>EDIT:</strong> thanks for the help so far. However, I'm still unsure as to how I accomplish this with the python script I will be calling. A basic test I did shows that the django cache is not global. Meaning if I call it from an external script, it does not see the cache data going on in the framework. Suggestions?</p> <p><strong>Another EDIT:</strong> coming to think of it, this is probably because I am still using local memory cache. I suspect that if I move the cache to memcached, DB, whatever, this will be solved.</p>
4
2009-04-28T12:56:05Z
797,882
<p>So you want to schedule something to run at a regular interval? At the cost of some CPU time, you can use <a href="http://code.google.com/p/django-cron/wiki/Install">this simple app</a>.</p> <p>Alternatively, if you can use it, the <a href="http://www.thesitewizard.com/general/set-cron-job.shtml">cron job</a> for every 5 minutes is:</p> <pre><code>*/5 * * * * /path/to/project/refresh_cache.py </code></pre> <p>Web hosts provide different ways of setting these up. For cPanel, use the Cron Manager. For Google App Engine, use <a href="http://code.google.com/appengine/docs/python/config/cron.html"><code>cron.yaml</code></a>. For all of these, you'll need to <a href="http://superjared.com/entry/django-and-crontab-best-friends/">set up the environment</a> in <code>refresh_cache.py</code> first.</p> <p>By the way, responding to a user's request is considered lazy caching. This is pre-emptive caching. And don't forget to cache long enough for the page to be recreated!</p>
8
2009-04-28T13:17:09Z
[ "python", "django", "caching" ]
Django caching - can it be done pre-emptively?
797,773
<p>I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup.</p> <p>This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a significant delay of a few seconds while I go to the external site to parse the new data.</p> <p>Is there any way to load the new data lazily so that no user will ever get that kind of delay? Or is this unavoidable?</p> <p><em>Please note that I am on a shared hosting server, so keep that in mind with your answers.</em></p> <p><strong>EDIT:</strong> thanks for the help so far. However, I'm still unsure as to how I accomplish this with the python script I will be calling. A basic test I did shows that the django cache is not global. Meaning if I call it from an external script, it does not see the cache data going on in the framework. Suggestions?</p> <p><strong>Another EDIT:</strong> coming to think of it, this is probably because I am still using local memory cache. I suspect that if I move the cache to memcached, DB, whatever, this will be solved.</p>
4
2009-04-28T12:56:05Z
798,462
<p>"I'm still unsure as to how I accomplish this with the python script I will be calling. "</p> <p>The issue is that your "significant delay of a few seconds while I go to the external site to parse the new data" has nothing to do with Django cache at all.</p> <p>You can cache it everywhere, and when you go to reparse the external site, there's a delay. The trick is to NOT parse the external site while a user is waiting for their page.</p> <p>The trick is to parse the external site <em>before</em> a user asks for a page. Since you can't go back in time, you have to periodically parse the external site and leave the parsed results in a local file or a database or something.</p> <p>When a user makes a request you already have the results fetched and parsed, and all you're doing is presenting.</p>
4
2009-04-28T15:09:15Z
[ "python", "django", "caching" ]
Django caching - can it be done pre-emptively?
797,773
<p>I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup.</p> <p>This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a significant delay of a few seconds while I go to the external site to parse the new data.</p> <p>Is there any way to load the new data lazily so that no user will ever get that kind of delay? Or is this unavoidable?</p> <p><em>Please note that I am on a shared hosting server, so keep that in mind with your answers.</em></p> <p><strong>EDIT:</strong> thanks for the help so far. However, I'm still unsure as to how I accomplish this with the python script I will be calling. A basic test I did shows that the django cache is not global. Meaning if I call it from an external script, it does not see the cache data going on in the framework. Suggestions?</p> <p><strong>Another EDIT:</strong> coming to think of it, this is probably because I am still using local memory cache. I suspect that if I move the cache to memcached, DB, whatever, this will be solved.</p>
4
2009-04-28T12:56:05Z
803,162
<p>You can also use a python script to call your view and write it to a file, then deliver it staticaly with lightpd for example :</p> <pre><code>request = HttpRequest() request.path = url # the url of your view (detail_func, foo, params) = resolve(url) params['gmap_key'] = settings.GMAP_KEY_STATIC detail = detail_func(request, **params) out = open(dir + "index.html", 'w') out.write(detail.content) out.close() </code></pre> <p>then call your script with a cron</p>
0
2009-04-29T16:20:31Z
[ "python", "django", "caching" ]
Django caching - can it be done pre-emptively?
797,773
<p>I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup.</p> <p>This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a significant delay of a few seconds while I go to the external site to parse the new data.</p> <p>Is there any way to load the new data lazily so that no user will ever get that kind of delay? Or is this unavoidable?</p> <p><em>Please note that I am on a shared hosting server, so keep that in mind with your answers.</em></p> <p><strong>EDIT:</strong> thanks for the help so far. However, I'm still unsure as to how I accomplish this with the python script I will be calling. A basic test I did shows that the django cache is not global. Meaning if I call it from an external script, it does not see the cache data going on in the framework. Suggestions?</p> <p><strong>Another EDIT:</strong> coming to think of it, this is probably because I am still using local memory cache. I suspect that if I move the cache to memcached, DB, whatever, this will be solved.</p>
4
2009-04-28T12:56:05Z
804,829
<p>I have no proof, but I've read BeautifulSoup is slow and consumes a lot of memory. You may want to look at using the lxml module instead. lxml is supposed to be much faster and efficient, and can do much more than BeautifulSoup.</p> <p>Of course, the parsing probably isn't your bottleneck here; the external I/O is. </p> <p>First off, use memcached!</p> <p>Then, one strategy that can be used is as follows:</p> <ul> <li>Your cached object, called <code>A</code>, is stored in the cache with a dynamic key (<code>A_&lt;timestamp&gt;</code>, for example).</li> <li>Another cached object holds the current key for <code>A</code>, called <code>A_key</code>.</li> <li>Your app would then get the key for <code>A</code> by first getting the value at <code>A_key</code></li> <li>A periodic process would populate the cache with the <code>A_&lt;timestamp&gt;</code> keys and upon completion, change the value at <code>A_key</code> to the new key</li> </ul> <p>Using this method, all users every 5 minutes won't have to wait for the cache to be updated, they'll just get older versions until the update happens.</p>
4
2009-04-29T23:55:33Z
[ "python", "django", "caching" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I would really appriciate Python solutions because my scripts are written in Python.</p> <ol> <li><p>Does a user make an http request which queries the app for some data and return a result? <strong>Yes</strong></p></li> <li><p>Does the app collect data and store it somewhere? <strong>The app and the HTTP Server both use SQLite database. However the DBs may be different.</strong></p></li> </ol>
2
2009-04-28T12:58:44Z
797,805
<p>a) You can start applications using <b>os.system</b>:</p> <pre><code> os.system("command") </code></pre> <p>or you can use the <b>subprocess</b> module. More information <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">here</a>.</p> <p>b) use sockets</p>
3
2009-04-28T13:01:40Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I would really appriciate Python solutions because my scripts are written in Python.</p> <ol> <li><p>Does a user make an http request which queries the app for some data and return a result? <strong>Yes</strong></p></li> <li><p>Does the app collect data and store it somewhere? <strong>The app and the HTTP Server both use SQLite database. However the DBs may be different.</strong></p></li> </ol>
2
2009-04-28T12:58:44Z
797,824
<p>Depending on what you want to do you can use os.mkfifo to create a named pipe to share data between your two programs.</p> <p><a href="http://mail.python.org/pipermail/python-list/2006-August/568346.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2006-August/568346.html</a></p>
1
2009-04-28T13:04:44Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I would really appriciate Python solutions because my scripts are written in Python.</p> <ol> <li><p>Does a user make an http request which queries the app for some data and return a result? <strong>Yes</strong></p></li> <li><p>Does the app collect data and store it somewhere? <strong>The app and the HTTP Server both use SQLite database. However the DBs may be different.</strong></p></li> </ol>
2
2009-04-28T12:58:44Z
797,825
<p>Before answering, I think we need some more information:</p> <ol> <li>Is there a definable pipeline of information here? <ol> <li>Does a user make an http request which queries the app for some data and return a result?</li> <li>Does the app collect data and store it somewhere?</li> </ol></li> </ol> <p>There are a few options depending on how you're actually using them. Sockets is an option or passing information via a file or a database.</p> <p><strong>[Edit]</strong> Based on your reply I think there's a few ways you can do it:</p> <ol> <li>If you can access the app's database from the web server you could easily pull the information you're after from there. Again it depends what information it is that you want to exchange.</li> <li>If your app just needs to give the http server some results, you could write them into a results table in the http server's db.</li> <li>Use pipe's or sub processes as other people have suggested to exchange data with the background app directly.</li> <li>Use a log file which your app can write to and your http server read from.</li> </ol> <p>Some more questions:</p> <ol> <li>Do you need two-way communication here or is the http server just displaying results?</li> <li>What webserver are you using?</li> <li>What processing languages do you have available on it?</li> </ol> <p>Depending on how reliant the two parts can be, it might be best to write a new app to check the database of your app for changes (using hooks or polling or whatever) and post relevent information into the http server's own database. This has the advantage of leaving the two parts less closely coupled which is often a good thing.</p> <p>I've got a webserver (Apache 2) which talks to a Django app using the fastcgi module. Have a look at <a href="http://www.djangobook.com/en/2.0/chapter12/" rel="nofollow">the section in djangobook on fastcgi</a>. Apache uses sockets (or regular tcp) to talk to the background app (Django).</p> <p><strong>[Edit 2]</strong> Oops - just spotted that your webserver is a python process itself. If it's all python then you could <a href="http://www.tutorialspoint.com/python/python_multithreading.htm" rel="nofollow">launch each in it's own thread</a> and pass them both <a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue</a> objects which allow the two processes to send each other information in either a blocking or non-blocking manner.</p>
2
2009-04-28T13:05:31Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I would really appriciate Python solutions because my scripts are written in Python.</p> <ol> <li><p>Does a user make an http request which queries the app for some data and return a result? <strong>Yes</strong></p></li> <li><p>Does the app collect data and store it somewhere? <strong>The app and the HTTP Server both use SQLite database. However the DBs may be different.</strong></p></li> </ol>
2
2009-04-28T12:58:44Z
797,839
<p>Well, you can probably just use the <a href="http://docs.python.org/library/subprocess.html#module-subprocess" rel="nofollow">subprocess</a> module. For the exchanging data, you may just be able to use the Popen.stdin and Popen.stdout streams. Of course, there's no limit to ways you /could/ do it. <a href="http://omniorb.sourceforge.net/" rel="nofollow">CORBA</a>, <a href="http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html" rel="nofollow">DBUS</a>, <a href="http://semanchuk.com/philip/sysv%5Fipc/" rel="nofollow">shared memory</a>, <a href="http://www.kdedevelopers.org/node/124" rel="nofollow">DCOP</a>, the list goes on. But try the simple way first, which in this case is regular python pipes/streams.</p>
3
2009-04-28T13:07:42Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I would really appriciate Python solutions because my scripts are written in Python.</p> <ol> <li><p>Does a user make an http request which queries the app for some data and return a result? <strong>Yes</strong></p></li> <li><p>Does the app collect data and store it somewhere? <strong>The app and the HTTP Server both use SQLite database. However the DBs may be different.</strong></p></li> </ol>
2
2009-04-28T12:58:44Z
797,938
<p>When I write web applications in Python, I always keep my web server in the same process as my background tasks. I don't know what web server you're using, but I personally use <a href="http://cherrypy.org/" rel="nofollow">CherryPy</a>. Your application can have a bunch of its threads be the web server, with however many other threads you like as background tasks. This way you don't need any kind of complex IPC with sockets, named pipes, etc. Instead you simply access shared, global, synchronized data structures to pass along information, and your different modules can directly call each others functions.</p> <p>EDIT: To clarify, you can use the <a href="http://docs.python.org/library/threading.html" rel="nofollow">threading module</a> to run your CherryPy server in different threads than your other blocking servers. For example:</p> <pre><code>def listener(): sock = get_socket_from_somewhere() while True: client, addr = sock.accept() # send data back to client, etc from threading import Thread t1 = Thread(target=listener) t1.setDaemon(True) t1.start() cherrypy.quickstart() # you'd need actual arguments here </code></pre> <p>This example shows how to have a blocking server in one thread in the same process as a web server (in this case CherryPy, though it could be anything).</p>
0
2009-04-28T13:28:34Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I would really appriciate Python solutions because my scripts are written in Python.</p> <ol> <li><p>Does a user make an http request which queries the app for some data and return a result? <strong>Yes</strong></p></li> <li><p>Does the app collect data and store it somewhere? <strong>The app and the HTTP Server both use SQLite database. However the DBs may be different.</strong></p></li> </ol>
2
2009-04-28T12:58:44Z
797,999
<p>maybe <a href="http://twistedmatrix.com/trac/" rel="nofollow">twisted</a> is what you're looking for</p>
1
2009-04-28T13:42:09Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
798,180
<p>I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read.</p> <p>I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability?</p> <p>Has anyone seen a pretty-printing algorithm that does this already? In Python would be even better.</p>
19
2009-04-28T14:14:24Z
798,251
<p>I personally use <a href="http://www.sqlinform.com/" rel="nofollow">SQL Inform</a> for quick SQL formating, which is written in Java and is unfortunately not open source, so there is no access to the underlying algorithm.</p>
3
2009-04-28T14:25:56Z
[ "python", "sql", "coding-style", "indentation", "pretty-print" ]
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
798,180
<p>I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read.</p> <p>I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability?</p> <p>Has anyone seen a pretty-printing algorithm that does this already? In Python would be even better.</p>
19
2009-04-28T14:14:24Z
798,301
<p>Perhaps part of the difficulty in finding a tool is that there are so many different "standard" SQL formatting conventions. Here are two SO questions that describe people's preferences:</p> <ul> <li><a href="http://stackoverflow.com/questions/519876/sql-formatting-standards">http://stackoverflow.com/questions/519876/sql-formatting-standards</a></li> <li><a href="http://stackoverflow.com/questions/522356/what-sql-coding-standard-do-you-follow">http://stackoverflow.com/questions/522356/what-sql-coding-standard-do-you-follow</a></li> </ul>
2
2009-04-28T14:35:22Z
[ "python", "sql", "coding-style", "indentation", "pretty-print" ]
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
798,180
<p>I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read.</p> <p>I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability?</p> <p>Has anyone seen a pretty-printing algorithm that does this already? In Python would be even better.</p>
19
2009-04-28T14:14:24Z
798,363
<p>Don't know if it answers your question, but I generally use this strategy</p> <pre><code>SELECT what1, what2, etc, FROM table WHERE condition AND condition AND condition ORDER BY whatever </code></pre> <p>But that's just me. I don't think proper automatic tools exist.</p>
-2
2009-04-28T14:49:05Z
[ "python", "sql", "coding-style", "indentation", "pretty-print" ]
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
798,180
<p>I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read.</p> <p>I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability?</p> <p>Has anyone seen a pretty-printing algorithm that does this already? In Python would be even better.</p>
19
2009-04-28T14:14:24Z
798,417
<p>You can try <a href="http://python-sqlparse.googlecode.com">sqlparse</a>. It's a Python module that provides simple SQL formatting. A online demo is available <a href="http://sqlformat.appspot.com">here</a>.</p>
33
2009-04-28T14:59:12Z
[ "python", "sql", "coding-style", "indentation", "pretty-print" ]
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
798,180
<p>I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read.</p> <p>I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability?</p> <p>Has anyone seen a pretty-printing algorithm that does this already? In Python would be even better.</p>
19
2009-04-28T14:14:24Z
16,567,609
<p>I have previously used SQL Complete by Devart for formatting SQL, but now there is a free online SQL beautifier powered by SQL Complete - <a href="http://www.sql-format.com/" rel="nofollow">SQL Formatter</a> it is really feature rich and easy to use even for a beginner. </p>
1
2013-05-15T14:20:42Z
[ "python", "sql", "coding-style", "indentation", "pretty-print" ]
Python tool that builds a dependency diagram for methods of a class
798,389
<p>I'm digging into a huge legacy Python class that has a lot of methods. I eventually break complex ones into smaller pieces so the amount of methods increases even more. I wonder if there is a tool that can scan the Python code and build some kind of dependency diagram for its methods.</p> <p>I define method <code>x()</code> to be a dependency of method <code>y()</code> if <code>x()</code> is called at least once in <code>y()</code>.</p> <p>I could use such a tool to isolate (if possible) subsets of class methods that have no external dependencies (all their dependencies are methods from the same subset).</p> <p>I'm planning to move some functionality into other classes and I think that such an approach would help me to decide which parts to extract from the initial huge class.</p> <p>Edit: I would really like a command-line tool.</p>
16
2009-04-28T14:54:26Z
798,776
<p>Have you tried <a href="http://pydev.sourceforge.net/" rel="nofollow">pydev</a>? It's a python extension for eclipse. I believe it allows you to use the "call hierarchy" feature of Eclipse to view a call graph for a given method. It's not quite what you want but maybe it's enough to get started.</p>
1
2009-04-28T16:26:31Z
[ "python", "refactoring" ]