[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

type hinting backward compatibility with python 3.0 to 3.4

On Sat, May 20, 2017 at 11:58 PM, Gregory Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Chris Angelico wrote:
>> They're function metadata. What would the principle of least surprise
>> say about this?
>> print("Spam")
>> def func(arg: print("Foo") = print("Quux")):
>>     print("Blargh")
>> print("Fred")
>> func()
>> print("Eggs")
> Most languages that have static type declarations wouldn't
> let you write something like that in the first place, so the
> fact that Python does is surprising to begin with.

This is true. But since Python _does_ work with dynamic evaluation
(which consequently demands that these kinds of things be expressions
evaluated at compile time), it must by definition be possible to have
side effects. Of course, you would never actually do this in
production code, but I've often made use of the fact that a function's
default argument isn't technically a constant - for example:

DEFAULT_URL = "http://yada.yada.example/";
if testing:
    DEFAULT_URL = "http://yada.yada.localhost/";
if staging:
    DEFAULT_URL = "http://yada.yada.test.example/";


def do_stuff(thing, *, url=DEFAULT_URL):

It has to be evaluated at run time, but from the programmer's point of
view, it's a constant. In C, for instance, this kind of thing would
generally be done with #if and #define.

Like everything in Python, there is a well-defined order of
evaluation, just in case it matters. I wouldn't hazard a guess as to
how often it will, but it's good to know that if it does, you can just
test it once and then be confident :)