pythonic

Pythonic URL Parsing

There are a number of questions about how to parse a URL in Python, this question is about the best or most Pythonic way to do it. In my parsing I need 4 parts: the network location, the first part of the URL, the path and the filename and querystring parts. http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123 ...

More Pythonic conversion to binary?

Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves. def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('<I', [2])) # Image size. data.append(struct.pack('<II', *self....

A neat way of extending a class attribute in subclasses

Let's say I have the following class class Parent(object): Options = { 'option1': 'value1', 'option2': 'value2' } And a subclass called Child class Child(Parent): Options = Parent.Options.copy() Options.update({ 'option2': 'value2', 'option3': 'value3' }) I want to be able to overrid...

Creating lists of lists in a pythonic way

I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows. mat=[[0]*2]*3 However, when I change the value of one of the items in the matrix, it changes the value of that entry in every row, since the id of each row in mat is the same. For example, after assigning mat[0][0]=1 mat is [[...

What is the best way to get the last element of a list in python?

I found many different ways of getting the last element from a list in python alist[-1] alist[len(alist) -1] Which is the way you would do this? ...

python3.0: imputils

Why was the imputil module removed from python3.0 and what should be used in its place? ...

PEP 302 Example: New Import Hooks

Where can I find an example implementation of the "New Import Hooks" described in PEP 302? I would like to implement a custom finder and loader in the most forward compatible way possible. In other words, the implementation should work in python 2.x and 3.x. ...

Reclassing an instance in Python

I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class. I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway). The fo...

How do you make this code more pythonic?

Could you guys please tell me how I can make the following code more pythonic? The code is correct. Full disclosure - it's problem 1b in Handout #4 of this machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesis. But they use matlab & I'm using scipy Eg one question i have...

Python: most idiomatic way to convert None to empty string?

What is the most idiomatic way to do the following? def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) update: I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, ...

Get the items not repeated in a list

Take two lists, second with same items than first plus some more: a = [1,2,3] b = [1,2,3,4,5] I want to get a third one, containing only the new items (the ones not repeated): c = [4,5] The solution I have right now is: >>> c = [] >>> for i in ab: ... if ab.count(i) == 1: ... c.append(i) >>> c [4, 5] Is there any other way...

python list comprehensions; compressing a list of lists?

Hi, guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. What I'm doing is this. I have a list, A, and I have a function f which takes an item and returns a list. I can use a list comprehension to convert everything in A like so; [f(a) for a in A] But...

Pythonic way to get some rows of a matrix

I was thinking about a code that I wrote a few years ago in Python, at some point it had to get just some elements, by index, of a list of lists. I remember I did something like this: def getRows(m, row_indices): tmp = [] for i in row_indices: tmp.append(m[i]) return tmp Now that I've learnt a little bit more sinc...

Most "pythonic" way of organising class attributes, constructor arguments and subclass constructor defaults?

Being relatively new to Python 2, I'm uncertain how best to organise my class files in the most 'pythonic' way. I wouldn't be asking this but for the fact that Python seems to have quite a few ways of doing things that are very different to what I have come to expect from the languages I am used to. Initially, I was just treating classe...

To calculate the sum of numbers in a list by Python

My data 466.67 465.56 464.44 463.33 462.22 461.11 460.00 458.89 ... I run in Python sum(/tmp/1,0) I get an error. How can you calculate the sum of the values by Python? ...

comparing disimilar types [python]

First the code: class myClass(object): def __cmp__(self, other): return cmp(type(self), type(other)) or cmp(self.__something, other.__something) Does this produce the same ordering as for other types in python? Is there a correct idiom for this? Related question: A bit of looking around on google I found some pertinent...

Python loop counter in a for loop

In my example code below, is the counter = 0 really required, or is there a better, more Python, way to get access to a loop counter? I saw a few PEPs related to loop counters, but they were either deferred or rejected (PEP 212 and PEP 281). This is a simplified example of my problem. In my real application this is done with graphics an...

What is the best way to call a python script from another python script?

I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods etc. I have another script which runs as a service. I want to call test1.py from the script running as a service. eg: test1.py print "I am a test" print "see! I do nothin...

Python - Get relative path of all files and subfolders in a directory

Hi, I am searching for a good way to get relative paths of files and (sub)folders within a specific folder. For my current approach I am using os.walk(). It is working but it does not seem "pythonic" to me: myFolder = "myfolder" fileSet = set() # yes, I need a set() for root, dirs, files in os.walk(myFolder): for fileName in fi...

How to get lxml working under IronPython?

I need to port some code that relies heavily on lxml from a CPython application to IronPython. lxml is very Pythonic and I would like to keep using it under IronPython, but it depends on libxslt and libxml2, which are C extensions. Does anyone know of a workaround to allow lxml under IronPython or a version of lxml that doesn't have th...