Is a "context expression" as that expression provides the main clue as The expression immediately following the with keyword in the statement It establishes a context manager protocol: PEP 343 goes deeper than providing some simplistic syntactic sugar, however. Possible to factor out standard uses of try/finally statements.įactoring out try/finally statements makes the code simpler and more readable. This PEP adds a new statement "with" to the Python language to make it ![]() In this case PEP 343 - The "with" Statement says it up front in the abstract: The beauty of with is that it actually adheres to both of those principles as I will explain below.Īny time you find yourself in philosophical pondering about a feature in Python it's probably worth looking up the Python Enhancement Proposals (PEPs) to read about the motivation behind the feature. Yes, The Zen of Python states "Flat is better than nested", however it is not the only characteristic we care about it also states "Simple is better than complex". and using just with without the try is what people end up doing in the type of hacky "one use" code where they use f.close() instead of with anyways (which is bad because the file may not be closed if an exception is thrown before their f.close()), so for "hacky" code people just don't use with because, I don't know, I guess they just find it too "fancy" and for well structured code it doesn't bring any benefits anyways, so it seems to me there's no real world use case left for it. Yes, but if you go the with way, your code becomes: try: anyways and thus the benefits of with still elude me, even as I grow to like and understand Python more and (sorry, I can't find a way to write code in comments): (I always find that one more level of indentation pops up in my code every time I use with instead of f.close(). I don't intend to simply waste your time, but: has it occurred to you too, while using Python's with statement that it really is contrary to the 5th line of "The Zen of Python" that goes "Flat is better than nested"? Can any enlightened Python guru share me some of their insights on this?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |