Making ugly code more beautiful using Python's with statement
I have before featured Python 2.5's with statement and I am using it more and more. It makes code more readable and beatiful. Yesterday I used it in a beautiful way and I want to highlight it here.
My task was to ensure that the correct language is set when sending out emails. My first iteration used following code: #Remember the current language
current_lang = get_current_lang()
#Set language by uid if possible
user_lang = get_lang_by_uid(uid)
if user_lang:
set_current_lang(user_lang)
#… MAIL CODE …
#Revert back to old language
set_current_lang(current_lang)
Now this is fine and well, but not that clean, especially when you have to use it in multiple places. I knew there must be a better way to do this. After some iterations I came up with this marvel: with set_lang_by_uid(uid):
#… MAIL CODE …
A one liner that I can use everywhere! The implementation of set_lang_by_uidImplementing set_lang_by_uid is trivial - that's the great thing about using the with statement! Here's how it's implemented: from contextlib import contextmanager
@contextmanager
def set_lang_by_uid(uid):
user_lang = get_lang_by_uid(uid)
if user_lang:
current_lang = get_current_lang()
set_current_lang(user_lang)
yield
set_current_lang(current_lang)
else:
yield
More referencesCheck out my older writing on the with statement:
Code
·
Code improvement
·
Code rewrite
·
Python
·
Tips
•
6. Dec 2011
|
|