Question about math.pi is mutable

Steven D'Aprano steve at pearwood.info
Sun Nov 8 19:58:11 EST 2015


On Sun, 8 Nov 2015 11:39 pm, BartC wrote:


>> shutil.copyfileobj(Source(), Dest())
>> ========================================================================
> 
> OK, so here, it is necessary to resolve "copyfileobj" by seeing if
> "shutil" is something that contains a name "copyfileobj" that happens to
> be a method.

Correct.

> Is this the lookup you're talking about, and is it done using the actual
> string "copyfileobj"? If so, does it need to be done every single time
> this line is executed? It would extraordinarily inefficient if that was
> the case.

That's not what Marko was referring to, but you are correct, it is done
using the string "copyfileobj". And it has to be done every single time,
since you cannot be sure that the lookup will always return the same
object, or even whether it will always succeed. For example, here is a
self-destructing method:


class X:
    counter = 0
    def method(self):
        self.counter += 1
        if self.counter == 3:
            del X.method
        msg = "This method will self-destruct in %d calls."
        return msg % (3 - self.counter)


But you are wrong to describe this as "extraordinarily inefficient". It is
certainly efficient enough to be practical: inefficient or not, Python is
used for many thousands of practical applications. It is only about a
factor of 100 times slower than C or Java, and the PyPy optimizing compiler
averages ten times faster (and, occasionally, approaches or even exceeds
the speed of similar C or Java code). When performance is critical, you can
often locate the bottlenecks and turn that into C or Fortran code.

Ruby, which is even more flexible than Python in some ways, is even slower,
and yet even Ruby is still fast enough to be practical for many tasks.

And remember too that some of the speed of Java (and especially C) is gained
at the expense of:

- prohibiting the developer from doing certain things;
- restricting the range of values you can use;
- making significant assumptions about correctness;
- avoiding actually checking those assumptions;
- and in the case of C, by outright *ignoring the code you write* if you
inadvertently violate those assumptions.



-- 
Steven




More information about the Python-list mailing list