pythonic

Pythonic List Comprehension

This seems like a common task, alter some elements of an array, but my solution didn't feel very pythonic. Is there a better way to build urls with list comprehension? links = re.findall(r"(?:https?://|www\.|https?://www\.)[\S]+", text) if len(links) == 0: return text urls = [] for link in links: if link[0:4] == "www.": ...

Does a File Object Automatically Close when its Reference Count Hits Zero?

I was under the impression that file objects are immediately closed when their reference counts hit 0, hence the line: foo = open('foo').read() would get you the file's contents and immediately close the file. However, after reading the answer to http://stackoverflow.com/questions/1832528/is-close-necessary-when-using-iterator-on-a-py...

In Python, is the idiom "from Module import ClassName" typical?

Since I prefer small files, I typically place a single "public" class per Python module. I name the module with the same name as the class it contains. So for example, the class ToolSet would be defined in ToolSet.py. Within a package, if another module needs to instanciate an object of class ToolSet, I use: from ToolSet import ToolSet...

Pythonic way to get the largest item in a list.

Is there a better way of doing this? I don't really need the list to be sorted, just scanning through to get the item with the greatest specified attribute. I care most about readability but sorting a whole list to get one item seems a bit wasteful. >>> import operator >>> >>> a_list = [('Tom', 23), ('Dick', 45), ('Harry', 33)] >>> sor...

Large functionality change based on variables.

I'm in a situation where I've got a project that has a large number of Django views across quite a few different apps. The same codebase and database is being used by a large number of clients. There are a few site-specific use-cases that are coming in and this requires quite a bit of custom code to be written. I'd like to come up with ...

Pythonic way to ignore for loop control variable

A Python program I'm writing is to read a set number of lines from the top of a file, and the program needs to preserve this header for future use. Currently, I'm doing something similar to the following: header = '' header_len = 4 for i in range(1, header_len): header += file_handle.readline() Pylint complains th...

return variable outputs in Python function?

Hi, I have a function that returns a list. When I know the number of elements in the list I can do something like: x,y,z=foo() however, the number of elements in the list can vary. I would like to do something like x,y*=foo() where x would contain the first element in the returned list and y* would contain the remainder of however...

Pythonic way to write a for loop that doesn't use the loop index

This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program. The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev def RandomSample(count): pattern = [] for i in range(coun...

lisp-style style `let` syntax in Python list-comprehensions

Consider the following code: >>> colprint([ (name, versions[name][0].summary or '') for name in sorted(versions.keys()) ]) What this code does is to print the elements of the dictionary versions in ascending order of its keys, but since the value is another sorted list, only the summary of its first element (the 'm...

In Python, use "dict" with keywords or anonymous dictionaries?

Say you want to pass a dictionary of values to a function, or otherwise want to work with a short-lived dictionary that won't be reused. There are two easy ways to do this: Use the dict() function to create a dictionary: foo.update(dict(bar=42, baz='qux')) Use an anonymous dictionary: foo.update({'bar': 42, 'baz': 'qux'}) Which do...

A pythonic way how to find if a value is between two values in a list

Having a sorted list and some random value, I would like to find in which range the value is. List goes like this: [0, 5, 10, 15, 20] And value is, say 8. The standard way would be to either go from start until we hit value that is bigger than ours (like in the example below), or to perform binary search. grid = [0, 5, 10, 15, 20] va...

Shortest way to find if a string matchs an object's attribute value in a list of objects of that type in Python

I have a list with objects of x type. Those objects have an attribute name. I want to find if a string matchs any of those object names. If I would have a list with the object names I just would do if string in list, so I was wondering given the current situation if there is a way to do it without having to loop over the list. ...

Python: How to avoid explicit 'self'?

I have been learning Python by following some pygame tutorials. Therein I found extensive use of the keyword self, and coming from a primarily Java background, I find that I keep forgetting to type self. For example, instead of self.rect.centerx I would type rect.centerx, because, to me, rect is already a member variable of the class. ...

Managing Setup code with TimeIt

As part of a pet project of mine, I need to test the performance of various different implementations of my code in Python. I anticipate this to be something I do alot of, and I want to try to make the code I write to serve this aim as easy to update and modify as possible. It's still in its infancy at the moment, but I've taken to usin...

What is The Pythonic Way for writing matching algorithm

I have this piece of code (should be self-explanatory; if not, just ask): for tr in completed_taskrevs: found = False for nr in completion_noterevs: if tr.description in nr.body: completion_noterevs.remove(nr) found = True break assert found How can I make it more pythonic? ...

A more pythonic way of iterating a list while excluding an element each iteration

I have the following code: items = ["one", "two", "three"] for i in range(0, len(items)): for index, element in enumerate(items): if index != i: # do something with element Basically I want to exclude every element once and iterate the rest. So for the list I have above, I'd like the following iterations: "t...

Python - temporarily modify the current process's environment

I use the following code to temporarily modify environment variables. @contextmanager def _setenv(**mapping): """``with`` context to temporarily modify the environment variables""" backup_values = {} backup_remove = set() for key, value in mapping.items(): if key in os.environ: backup_values[key] = o...

Efficiently search two-tuple

What's the best one-liner replacement for the code below? I'm sure there's a smarter way. choices = ((1, 'ONE'), (2, 'TWO'), (3, 'THREE')) some_int = 2 for choice in choices: if choice[0] == some_int: label = choice[1] break; # label == 'TWO' ...

Returning the product of a list

Is there a more concise, efficient or simply pythonic way to do the following? def product(list): p = 1 for i in list: p *= i return p EDIT: I actually find that this is marginally faster than using operator.mul: from operator import mul # from functools import reduce # python3 compatibility def with_lambda(list...

Pythonic way of summing lists and lists of lists

I'm trying to find a neat way of summing a list and a list of lists in the same function, so far I've got: import operator """ Fails late for item = ['a', 'b'] """ def validate(item): try: return sum(item) == sum(range(1, 10)) except TypeError: return sum(reduce(operator.add, item)) == sum(range(1, 10)) """ ...