idioms

avoiding the tedium of optional parameters

血红的双手。 提交于 2019-11-26 09:42:56
问题 If I have a constructor with say 2 required parameters and 4 optional parameters, how can I avoid writing 16 constructors or even the 10 or so constructors I\'d have to write if I used default parameters (which I don\'t like because it\'s poor self-documentation)? Are there any idioms or methods using templates I can use to make it less tedious? (And easier to maintain?) 回答1: You might be interested in the Named Parameter Idiom. To summarize, create a class that holds the values you want to

`if key in dict` vs. `try/except` - which is more readable idiom?

孤街浪徒 提交于 2019-11-26 09:26:35
问题 I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case: I want to build dictionary A from dictionary B. If a specific key does not exist in B, then do nothing and continue on. Which way is better? try: A[\"blah\"] = B[\"blah\"] except KeyError: pass or if \"blah\" in B: A[\"blah\"] = B[\"blah\"] \"Do and ask for forgiveness\" vs. \"simplicity and explicitness\". Which is better and why? 回答1: Exceptions are not conditionals

How do I manipulate $PATH elements in shell scripts?

纵饮孤独 提交于 2019-11-26 09:17:52
问题 Is there a idiomatic way of removing elements from PATH-like shell variables? That is I want to take PATH=/home/joe/bin:/usr/local/bin:/usr/bin:/bin:/path/to/app/bin:. and remove or replace the /path/to/app/bin without clobbering the rest of the variable. Extra points for allowing me put new elements in arbitrary positions. The target will be recognizable by a well defined string, and may occur at any point in the list. I know I\'ve seen this done, and can probably cobble something together

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

ⅰ亾dé卋堺 提交于 2019-11-26 08:47:20
问题 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, but I want to keep my code relatively simple. def xstr(s): if s is None: return \'\' else: return str(s) 回答1: If you actually want your function to behave like the str() built-in,

What is the pythonic way to detect the last element in a 'for' loop?

纵饮孤独 提交于 2019-11-26 08:44:35
问题 I\'d like to know the best way (more compact and \"pythonic\" way) to do a special treatment for the last element in a for loop. There is a piece of code that should be called only between elements, being suppressed in the last one. Here is how I currently do it: for i, data in enumerate(data_list): code_that_is_done_for_every_element if i != len(data_list) - 1: code_that_is_done_between_elements Is there any better way? Note: I don\'t want to make it with hacks such as using reduce . ;) 回答1:

Python “Every Other Element” Idiom [duplicate]

泪湿孤枕 提交于 2019-11-26 08:08:08
问题 This question already has an answer here: Iterating over every two elements in a list 18 answers I feel like I spend a lot of time writing code in Python, but not enough time creating Pythonic code. Recently I ran into a funny little problem that I thought might have an easy, idiomatic solution. Paraphrasing the original, I needed to collect every sequential pair in a list. For example, given the list [1,2,3,4,5,6] , I wanted to compute [(1,2),(3,4),(5,6)] . I came up with a quick solution at

Pairs from single list

橙三吉。 提交于 2019-11-26 04:39:51
问题 Often enough, I\'ve found the need to process a list by pairs. I was wondering which would be the pythonic and efficient way to do it, and found this on Google: pairs = zip(t[::2], t[1::2]) I thought that was pythonic enough, but after a recent discussion involving idioms versus efficiency, I decided to do some tests: import time from itertools import islice, izip def pairs_1(t): return zip(t[::2], t[1::2]) def pairs_2(t): return izip(t[::2], t[1::2]) def pairs_3(t): return izip(islice(t,None

Get the key corresponding to the minimum value within a dictionary

断了今生、忘了曾经 提交于 2019-11-26 02:39:46
问题 If I have a Python dictionary, how do I get the key to the entry which contains the minimum value? I was thinking about something to do with the min() function... Given the input: {320:1, 321:0, 322:3} It would return 321 . 回答1: Best: min(d, key=d.get) -- no reason to interpose a useless lambda indirection layer or extract items or keys! 回答2: Here's an answer that actually gives the solution the OP asked for: >>> d = {320:1, 321:0, 322:3} >>> d.items() [(320, 1), (321, 0), (322, 3)] >>> #

LBYL vs EAFP in Java?

你说的曾经没有我的故事 提交于 2019-11-26 02:29:12
问题 I was recently teaching myself Python and discovered the LBYL/EAFP idioms with regards to error checking before code execution. In Python, it seems the accepted style is EAFP, and it seems to work well with the language. LBYL ( L ook B efore Y ou L eap): def safe_divide_1(x, y): if y == 0: print \"Divide-by-0 attempt detected\" return None else: return x/y EAFP ( it\'s E asier to A sk F orgiveness than P ermission ): def safe_divide_2(x, y): try: return x/y except ZeroDivisionError: print \

Is there a downside to adding an anonymous empty delegate on event declaration?

…衆ロ難τιáo~ 提交于 2019-11-26 02:07:45
问题 I have seen a few mentions of this idiom (including on SO): // Deliberately empty subscriber public event EventHandler AskQuestion = delegate {}; The upside is clear - it avoids the need to check for null before raising the event. However, I am keen to understand if there are any downsides. For example, is it something that is in widespread use and is transparent enough that it won\'t cause a maintenance headache? Is there any appreciable performance hit of the empty event subscriber call?