learning python ...

Greg Ewing greg.ewing at canterbury.ac.nz
Wed May 26 06:54:26 EDT 2021


On 26/05/21 7:15 pm, hw wrote:
> it could at least figure out which, the 
> type or the variable, to use as parameter for a function that should 
> specify a variable type when the name is given.  Obviously, python knows 
> what's expected, so why not chose that.

It knows, but not until *after* the function is called. Not
when the parameters are being evaluated.

Note that not even C does what you're asking for. If you use
a type name where a variable name is expected or vice versa
in C, you get a compile-time error. It doesn't try to
automagically figure out what you mean. The only difference
is that Python gives you the error at run time.

Also, you seem to be thinking only of the case where the type
name appears directly in the call. But what about this:

     int = 42
     type = int
     if isinstance(something, type):
         ...

Would you expect Python to auto-correct this as well?

> Maybe a special 
> syntax for declaring type names which then can not become ambigous so 
> easily would be a good thing?

The fact that types are treated as a form of data is a useful
feature. It means you can use the full power of the language on
them. Dividing names into two kinds, types and non-types, would
severely diminish that power.

> I already wondered that the scope of variables is not limited to the 
> context they are declared within:
> 
> for number in something:
>      # do stuff

This has been a subject of debate for quite a long time.
Many people feel that a for-loop variable should be local to
the loop, but Guido deliberately didn't make it that way.
He felt it was useful to be able to refer to the loop
variable after the loop finishes. That way you can do things
like search for something in a loop, break out early when it's
found, and the loop variable then contains the thing you found.

It also has the benefit of being simple and consistent with
the way scoping and assignments work in the rest of the language.

There are other ways to code a search, of course, but it's been
the way it is from the beginning, and changing it now would be
massively disruptive.

-- 
Greg


More information about the Python-list mailing list