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

BartC bc at freeuk.com
Tue Mar 22 07:05:01 EDT 2016


On 22/03/2016 01:01, Steven D'Aprano wrote:
> On Tue, 22 Mar 2016 06:43 am, BartC wrote:
>
>> This code was adapted from a program that used:
>>
>>      readstrfile(filename)
>>
>> which either returned the contents of the file as a string, or 0.
>
> What an interesting function. And I don't mean that in a good way.
>
> So if it returns 0, how do you know what the problem is? Mistyped file name?
> Permission denied? File doesn't actually exist? Disk corruption and you
> can't open the file? Some weird OS problem where you can't *close* the
> file? (That can actually happen, although it's never happened to me.) How
> do you debug any problems, given only "0" as a result?
>
> What happens if you read (let's say) a 20GB Blue-Ray disk image?

I think you're making far too much of a throwaway function to grab a 
file off disk and into memory.

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?

> Pythonic code probably uses a lot of iterables:
>
> for value in something:
>      ...

> in preference to Pascal code written in Python:
>
> for index in range(len(something)):
>      value = something[index]

(Suppose you need both the value and its index in the loop? Then the 
one-line for above won't work. For example, 'something' is [10,20,30] 
and you want to print:

  0: 10
  1: 20
  2: 30 )

>      ...
> or worse:
>
> index = 0
> while index < len(something):
>      value = something[index]
>      ...
>      index += 1

> (I don't know where that while-loop idiom comes from. C? Assembly? Penitent
> monks living in hair shirts in the desert and flogging themselves with
> chains every single night to mortify the accursed flesh? But I'm seeing it
> a lot in code written by beginners. I presume somebody, or some book, is
> teaching it to them. "Learn Python The Hard Way" perhaps?)

Are you suggesting 'while' is not needed? Not everything fits into a 
for-loop you know! Why, take my own readtoken() function:

   symbol = anything_other_than_skip_sym

   while symbol != skip_sym:
      symbol = readnextsymbol()

Of course, a repeat-until or repeat-while would suit this better (but I 
don't know how it fits into Python syntax). So there's a case here for 
increasing the number of loop statements not reducing them.


-- 
Bartc



More information about the Python-list mailing list