pythonic

Take first successful match from a batch of regexes

I'm trying to extract set of data from a string that can match one of three patterns. I have a list of compiled regexes. I want to run through them (in order) and go with the first match. regexes = [ compiled_regex_1, compiled_regex_2, compiled_regex_3, ] m = None for reg in regexes: m = reg.match(name) if m: break ...

Is it Pythonic to mimic method overloading?

Is it pythonic to mimic method overloading as found in statically typed languages? By that I mean writing a function that checks the types of its arguments and behaves differently based on those types. Here is an example: class EmployeeCollection(object): def find(value): if isinstance(value, str): #find employe...

Concatenating two lists - difference between '+=' and extend()

I've seen there are actually two (maybe more) ways to concatenate lists in Python: One way is to use the extend() method: a = [1, 2] b = [2, 3] b.extend(a) the other to use the plus(+) operator: b += a Now I wonder: Which of those two options is the 'pythonic' way to do list concatenation and is there a difference between the two (...

Which Python projects should I study to learn best practices

What are the best Python projects to study if one wants to look at the codebase and see how well-designed Python projects are structured and coded? Open source is preferred for obvious reasons, but they could be closed-source too. It could be interesting to see how the interface or API is designed. Small projects would be as interestin...

Best way to find max and min of two values

I have a function that is passed two values and then iterates over the range of those values. The values can be passed in any order, so I need to find which one is the lowest first. I had the function written like this: def myFunc(x, y): if x > y: min_val, max_val = y, x else: min_val, max_val = x, y for i i...

why is python inconsistent when interpreting a subtraction when making a list?

I am making a small program and at some point from each row of a matrix I need to subtract the average of the row itself. Quite a standard renormalization procedure. Note in the code def subtractaverage(data): datanormalized=[] for row in data: average_row=sum(row)/len(row) print "average=",average_row # r...

Pythonic way to combine two lists in an alternating fashion?

I have two lists, the first of which is guaranteed to contain exactly one more item than the second. I would like to know the most Pythonic way to create a new list whose even-index values come from the first list and whose odd-index values come from the second list. # example inputs list1 = ['f', 'o', 'o'] list2 = ['hello', 'world'] #...

How do I redefine functions in python?

I got a function in a certain module that I want to redefine(mock) at runtime for testing purposes. As far as I understand, function definition is nothing more than an assignment in python(the module definition itself is a kind of function being executed). As I said, I wanna do this in the setup of a test case, so the function to be rede...

How do I access outer functions variables inside a closure(python 2.6)?

From wikipedia I need to access outer functions variables in a similar manner as using the 'nonlocal' keyword from python 3.x. Is there some way to do that in python 2.6? (Not necessarily using the nonlocal keyword) ...

Best way to create a "reversed" list in Python?

In Python, what is the best way to create a new list whose items are the same as those of some other list, but in reverse order? (I don't want to modify the existing list in place.) Here is one solution that has occurred to me: new_list = list(reversed(old_list)) It's also possible to duplicate old_list then reverse the duplicate in ...

How can I make this code Pythonic

So I have this code for an object. That object being a move you can make in a game of rock papers scissor. Now, the object needs to be both an integer (for matching a protocol) and a string for convenience of writing and viewing. class Move: def __init__(self, setMove): self.numToName = {0:"rock", 1:"paper",2:"scissors"} ...

find largest power of two less than X number?

I m doing this def power_two(n, base = -1): result = 2 ** base if result < n: base += 1 power_two(n, base) else: if result == n: print base else: print base - 1 what is the pythonic way to find largest power of two less than X number? EDIT example: power_two(100) ret...

Pythonic way to modify python path relative to current directory

I have a project that is structured like this (cut down a lot to give the gist)... State_Editor/ bin/ state_editor/ __init__.py main.py features/ __init__.py # .py files io/ __init__.py # .py files # etc. You get the idea. Now say for examp...

More pythonic way to write this?

I have this code here: import re def get_attr(str, attr): m = re.search(attr + r'=(\w+)', str) return None if not m else m.group(1) str = 'type=greeting hello=world' print get_attr(str, 'type') # greeting print get_attr(str, 'hello') # world print get_attr(str, 'attr') # None Which works, but I am not particularly f...

How can I better structure this code?

I have an lxml.objectify data structure I get from a RESTful web service. I need to change a setting if it exists and create it if it doesn't. Right now I have something along the lines of the following, but I feel like it's ugly. The structure I'm looking in has a list of subelements which all have the same structure, so I can't just lo...

(Usage of Class Variables) Pythonic - or nasty habit learnt from java ?

Hello Pythoneers: the following code is only a mock up of what I'm trying to do, but it should illustrate my question. I would like to know if this is dirty trick I picked up from Java programming, or a valid and Pythonic way of doing things: basically I'm creating a load of instances, but I need to track 'static' data of all the instan...

dynamic values in kwargs

I have a layer which helps me populating records from the form to tables and viceversa, it does some input checking, etc. Now several methods of this layer which are called several times in different parts of the webform take the same parameters, so I wanted to pack them at the begining of the codefile. kwargs(): return {"tabla"...

Python comparing two lists

Hello I wanna compare two lists like this a=[1,2] b=10,20] compare(a,b) will return True if each element in a is > corresponding element in b so compare( [1,2] > [3,4] ) is True compare( [1,20] > [3,4] ) is False hiow to do this the pythonic way Cheers ...

UnicodeEncodeError when reading pdf with pyPdf

Guys i had posted a question earlier http://stackoverflow.com/questions/3854963/pypdf-python-tool .dont mark this as duplicate as i get this error indicated below import sys import pyPdf def convertPdf2String(path): content = "" # load PDF file pdf = pyPdf.PdfFileReader(file(path, "rb")) # iterate pages ...

How to create a list or tuple of empty lists in Python?

I need to incrementally fill a list or a tuple of lists. Something that looks like this: result = [] firstTime = True for i in range(x): for j in someListOfElements: if firstTime: result.append([f(j)]) else: result[i].append(j) In order to make it less verbose an more elegant, I thought I wi...