The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

BartC bc at freeuk.com
Tue Mar 22 08:59:22 EDT 2016


On 22/03/2016 11:15, Chris Angelico wrote:
> On Tue, Mar 22, 2016 at 10:05 PM, BartC <bc at freeuk.com> wrote:
>> But out of interest, how would /you/ write a function that takes a file-spec
>> and turns it into an in-memory string? And what would its use look like?
>
> def read_file(fn, *a, **kw):
>      with open(fn, *a, **kw) as f:
>          return f.read()
>
> Usage:
>
> script = read_file(".bashrc")
> data = read_file("Ellalune_AlicePortrait.jpg", "rb")
> decoded = read_file("greek.srt", encoding="ISO-8859-7")
>
> If there's any problem with reading the file, an exception will be
> raised. Also, thanks to the 'with' block, I'm guaranteed that the file
> will have been closed before read_file() returns, which means I can
> immediately go and write to the file without a conflict.


I'm not sure I follow. Your solution to dealing with the scenarios 
raised by Steven D'Aprano is to:

(1) Not bother with exceptions at all inside the function

(2) Not bother with them in the user code either

(3) Let any errors just crash out (raise a Python system error) (just 
like I did in my original jpeg program which I was called out on)

(4) Or if the user code does want to check for certain errors (like, 
File Not Found, by far the most likely, and so that it can deal with 
that and continue executing), it now has to go and dig out docs for ... 
what? The user code needs to know what is going on inside the supposedly 
opaque function it's calling.

-- 
Bartc




More information about the Python-list mailing list