pythonic

What are the cons of returning an Exception instance instead of raising it in Python?

Hi*, I have been doing some work with python-couchdb and desktopcouch. In one of the patches I submitted I wrapped the db.update function from couchdb. For anyone that is not familiar with python-couchdb the function is the following: def update(self, documents, **options): """Perform a bulk update or insertion of the given documen...

Most Pythonic way to concatenate strings

Given this harmless little list: >>> lst = ['o','s','s','a','m','a'] My goal is to pythonically concatenate the little devils using one of the following ways: A. plain ol' string function to get the job done, short, no imports >>> ''.join(lst) 'ossama' B. lambda, lambda, lambda >>> reduce(lambda x, y: x + y, lst) 'ossama' C. g...

Should a class or method which processes a file close the file as a side effect?

I'm wondering which is the more 'Pythonic' / better way to write methods which process files. Should the method which processes the file close that file as a side effect? Should the concept of the data being a 'file' be completely abstracted from the method which is processing the data, meaning it should expect some 'stream' but not nece...

Python looping: idiomatically comparing successive items in a list

I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (I'm using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering if there's some way to do it which is more closely idiomatic. It's Python; shouldn't I be using iterators in some clever way? Simply loo...

What's the pythonic way of declaring variables?

Usually declaring variables on assignment is considered a best practice in VBScript or JavaScript , for example, although it is allowed. Why does Python force you to create the variable only when you use it? Since Python is case sensitive can't it cause bugs because you misspelled a variable's name? How would you avoid such a situat...

Python, next iteration of the loop over a loop

I need to get the next item of the first loop given certain condition, but the condition is in the inner loop. Is there a shorter way to do it than this? (test code) ok = 0 for x in range(0,10): if ok == 1: ok = 0 continue for y in range(0,20): if y == 5: ok = ...

Slicing a list into a list of sub-lists...

What is the simplest and reasonably efficient way to slice a list into a list of the sliced sub-list sections for arbitrary length sub lists. For example, if our source list is: input = [1, 2, 3, 4, 5, 6, 7, 8, 9, ... ] And our sub list length is 3 then we seek: output = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ... ] Likewise if our sub...

How to initialize a dict with keys from a list and empty value in Python?

I'd like to get, from: keys = [1,2,3,4] this: {1: None, 2: None, 3: None} A pythonic way of doing it? This is an ugly one: >>> keys = [1,2,3] >>> dict([(1,2)]) {1: 2} >>> dict(zip(keys, [None]*len(keys))) {1: None, 2: None, 3: None} ...

more pythonic way of finding element in list that maximizes a function

OK, I have this simple function that finds the element of the list that maximizes the value of another positive function. def get_max(f, s): # f is a function and s is an iterable best = None best_value = -1 for element in s: this_value = f(element) if this_value > best_value: best = element...

how to efficiently get the k bigger elements of a list in python

Hi! What´s the most efficient, elegant and pythonic way of solving this problem? Given a list (or set or whatever) of n elements, we want to get the k biggest ones. ( You can assume k<n/2 without loss of generality, I guess) For example, if the list were: l = [9,1,6,4,2,8,3,7,5] n = 9, and let's say k = 3. What's the most efficient a...

Grouping Python tuple list

I have a list of (label, count) tuples like this: [('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), ('apple', 4), ('banana', 3)] From that I want to sum all values with the same label (same labels always adjacent) and return a list in the same label order: [('grape', 103), ('apple', 29), ('banana', 3)] I know I could sol...

Python: find a list within members of another list(in order)

If I have this: a='abcdefghij' b='de' Then this finds b in a: b in a => True Is there a way of doing an similar thing with lists? Like this: a=list('abcdefghij') b=list('de') b in a => False The 'False' result is understandable - because its rightly looking for an element 'de', rather than (what I happen to want it to do) 'd' ...

Exclude object's field from pickling in python

I would like to avoid pickling of certain fields in an instance of a class. Currently, before pickling I just set those fields to None, but I wonder whether there's more elegant solution? ...

Python 3 object construction: which is the most Pythonic / the accepted way?

Having a background in Java, which is very verbose and strict, I find the ability to mutate Python objects as to give them with fields other than those presented to the constructor really "ugly". Trying to accustom myself to a Pythonic way of thinking, I'm wondering how I should allow my objects to be constructed. My instinct is to hav...

best way to do this string conversion in Python

Hi, I need to convert a string to another which has removed anything before the second word Example from this, string = "xyz anything else" string2 = "xyz anything else" string3 = "xyz anything else" to this, string = "anything else" string2 = "anything else" string3 = "anything else" The way I've done it doesnt please me at ...

Returning the lowest index for the first non whitespace character in a string in Python

What's the shortest way to do this in Python? string = " xyz" must return index = 3 ...

What is the most pythonic way to extend a list with the reversal of another?

I have one list that I want to take a slice of, reverse that slice and append each of those items onto the end of another list. The following are the options I have thought of (although if you have others please share), which of these is the most pythonic? # Option 1 tmp = color[-bits:] tmp.reverse() my_list.extend(tmp) # Option 2 my_...

Python methods on an object - which is better?

Hopefully an easy question. If I have an object and I want to call a method on it which is the better approach, A or B? class foo(object): def bar(): print 'bar' # approach A f = foo() f.bar() # approach B foo().bar() ...

Concise way to getattr() and use it if not None in Python

I am finding myself doing the following a bit too often: attr = getattr(obj, 'attr', None) if attr is not None: attr() # Do something, either attr(), or func(attr), or whatever else: # Do something else Is there a more pythonic way of writing that? Is this better? (At least not in performance, IMO.) try: obj.attr() # ...

How can I use functools.partial on multiple methods on an object, and freeze parameters out of order?

I find functools.partial to be extremely useful, but I would like to be able to freeze arguments out of order (the argument you want to freeze is not always the first one) and I'd like to be able to apply it to several methods on a class at once, to make a proxy object that has the same methods as the underlying object except with some o...