I think:- type hints are ugly
- they make the language harder to understand- particularly for beginners
def zipmap(f: Callable[[int, int], int], xx: List[int],yy: List[int]) -> List[Tuple[int, int, int]]:
No doubt this has occurred to everyone that's been working on them. There is a cost. But the benefits make it worthwhile.
It sounds like the people that will benefit are Google and other "Enterprise" users, IDE vendors, and the people that will pay for it in sweat and confusion are beginners and John Q. Mediocre Programmer.
My worry is that once type hinting gets standardised, then they will become a "best practice”
there's a particular personality type out there that's going to start wanting to add type hints to every function they write. Similarly to mindlessly obeying PEP8 while ignoring its intentions, hobgoblin-of-little-minds style, I think we're very likely to see type hints appearing in a lot of python source, or a lot of pre-commit-hook checkers.
Pretty soon it will be hard to find any open source library code that doesn't have type hints, or any project style guide that doesn't require them.
Sounds great right? Everybody will be happy! So let's nail it down!
* standardise the syntax for type hints in 3.5, as per PEP484* but: recommend the use of stub files as the preferred place to store hints* and: deprecate function annotations in the core language* remove them from the core language altogether in 3.6
Since it was mentioned in a different e-mail in this thread: yes, the standard library is not getting any type annotations. When we decide to ship type hints with Python 3.6, they will be added as stubs.
Yeah, so agreed, this is pretty busy. For such cases, reformatting makes it less confusing (see: Screenshot 1).
This is indeed ugly as hell and I certainly would not want to see this
in any Python file I'm working with.
However, I always assumed that whatever tools consume these annotations
are expected to be good enough at automatic type inference that
something like this would never be necessary?
In practice, I would hope that the above simplifies to
def zipmap(f, xx: List[int], yy: List[int]):
because (just picking a probably buggy random implementation)
zz = [] # --> z must be List[A]
for i in range(min(len(xx), len(yy))):
x = xx[i] # --> x must be int
y = xx[i] # --> y must be int
z = f(x,y) # --> f must be Callable[(int,int], B]
zz[i] = (x,y,z) # --> A must be Tuple[int,int,B]
return zz # --> return value must be List[Tuple[int,int,B]]
it doesn't catch that B = int, but I think that's acceptable.
Is this not the case? Are we really expecting people to write stuff like
the above?
Best,
-Nikolaus
--
GPG encrypted emails preferred. Key id: 0xD113FCAC3C4E599F
Fingerprint: ED31 791B 2C5C 1613 AF38 8B8A D113 FCAC 3C4E 599F
»Time flies like an arrow, fruit flies like a Banana.«
On 21 April 2015 at 08:07, Guido van Rossum <gu...@python.org> wrote:
> The situation is possibly even bleaker (or happier, depending on your
> position :-) for inline type hints in 3rd party packages -- few package
> authors will be satisfied with supporting only Python 3.5 and later. True,
> you can support Python 3.2 and up by declaring the 3rd party typing package
> as a dependency (unless Python 3.5+ is detected), but I don't expect this to
> become a popular approach overnight.
mypy has a codec for 2.x which strips type annotations -
https://github.com/JukkaL/mypy/tree/master/mypy/codec - while you
can't run mypy under 2.x, you can run it under 3.x to perform the
analysis, and ones code still runs under 2.x.
Another route - the one I've been experimenting with as I get familiar
with mypy - is to just use type comments exclusively. Function type
comments currently break, but that seems like a fairly shallow bug to
me, rather than something that shouldn't work. The advantage of that
route is that editors which make comments appear in subtle colours,
makes the type hints be unobtrusive without specific syntax colouring
support.
Sounds great right? Everybody will be happy! So let's nail it down! If I was in charge, here's what I'd do:* standardise the syntax for type hints in 3.5, as per PEP484* but: recommend the use of stub files as the preferred place to store hints* and: deprecate function annotations in the core language* remove them from the core language altogether in 3.6
On 21 April 2015 at 08:10, Eric Snow <ericsnow...@gmail.com> wrote:
>
>
>
> While it helps, this sort of best-practice is still unsettled (and apparently not obvious). In the short term it would make more sense to recommend using stub files for all the reason Harry enumerated. Once the best practices are nailed down through experience with stub files, then we can make recommendations regarding inline type hints.
>
> -eric
Forgive my ignorance, but can stub files can't annotate variables
within functions? E.g. AIUI if there is a stub file, it is used in the
static analysis instead of the actual source. Likely I've got it
modelled wrong in my head :)
-Rob
> "I hate stub files. [...] in my opinion, [it] just about guarantees a maintenance burden that will fall by the side of the road.I'm not so pessimistic. It's not like documentation or docstrings or comments -- the whole point is that it should be very easy to have an automated check for whether your stubs are in sync with your source, because both are in code. Unlike docs or comments which can easily become out of date, because there's no automated process to tell you they need updating... I'm thinking of it as a thing your editor will warn you of. Like pyflakes warnings about unused variables & co, I'm never happy until I've silenced them all in a file, and similarly, your editor will keep bugging you until you've got your stubs inline with your code...
--------------------------------
Harry J.W. Percival
------------------------------
Twitter: @hjwp
Mobile: +44 (0) 78877 02511
Skype: harry.percival
> stub files are only used to type-check *users* of a module. If you want a module itself to be type-checked you have to use inline type hintsis this a fundamental limitation, or just the current state of tooling?
I think while the authors are currently seeing stubs as a necessary *evil* they're missing points where they're a better backwards compatible solution for people who want to give users with capable IDEs the ability to use stub (or hint) files.
On 21 April 2015 at 08:50, Harry Percival <harry.p...@gmail.com> wrote:
>> stub files are only used to type-check *users* of a module. If you want a
>> module itself to be type-checked you have to use inline type hints
>
> is this a fundamental limitation, or just the current state of tooling?
AIUI its the fundamental design. Stubs don't annotate python code,
they *are* annotated code themselves. They aren't merged with the
observed code at all.
Could they be? Possibly. I don't know how much work that would be.
_______________________________________________
Python-Dev mailing list
Pytho...@python.org
https://mail.python.org/mailman/listinfo/python-dev
> On Tue, Apr 21, 2015 at 9:41 AM, Jack Diederich <jack...@gmail.com> wrote:
> > * It is not optional. Please stop saying that. The people promoting
> > it would prefer that everyone use it. If it is approved it will be
> > optional in the way that PEP8 is optional. If I'm reading your
> > annotated code it is certainly /not/ optional that I understand the
> > annotations.
[…]
>
> Maybe I'm completely misreading everything here […]
I think you've misunderstood the complaint.
> When you're writing a library, it can be a great help to provide type
> annotations, because every application that uses your library can
> benefit. When you're writing an application, you can completely ignore
> them, but still get the benefit of everyone else's.
Jack is not complaining only about *writing* code. He's complaining
about the effect this will have on code that we all are expected to
*read*.
Programmers spend a great deal of time reading code written by other
people. The costs of this proposal are only partly on the writers of the
code; they are significantly borne by the people *reading* that code.
For them, it is not optional.
> I have no fears for my own code. Are you afraid for yours?
Jack, if I understand correctly, fears for the code that will be written
by others in conformance with this proposal, that he will then have to
read and understand.
--
\ “The opposite of a correct statement is a false statement. But |
`\ the opposite of a profound truth may well be another profound |
_o__) truth.” —Niels Bohr |
Ben Finney
Ahh. Yes, that's a concern. When you go digging into that library to
find out how it works, yes, you'd be face-to-face with their type
annotations.
I doubt the worst-case complex ones are going to come up all that
often, though. Sure, you might declare that something returns a list
of dictionaries mapping tuples of integers and strings to list of sets
of atoms, but that's hardly common. (And chances are you can just
declare that it returns List[Dict] and have done with it.)
Maybe it'd be of value to have a quick "code stripper" that takes away
all the annotations, plus any other junk/framing that you're not
interested in, and gives you something you can browse in a text
editor? It could take away all the Sphinx adornments from docstrings,
any source control versioning markers, all that kind of thing. Then
you could read through the code in a simpler form, while still having
type annotations there for you if you need them.
ChrisA
On 20 Apr 2015 14:44, "Barry Warsaw" <ba...@python.org> wrote:
>
> On Apr 20, 2015, at 07:30 PM, Harry Percival wrote:
>
> >tldr; type hints in python source are scary. Would reserving them for stub
> >files be better?
>
> I think so. I think PEP 8 should require stub files for stdlib modules and
> strongly encourage them for 3rd party code.
+1
Having stub files take precedence over inline annotations would also neatly deal with the annotation compatibility problem (you can use a stub file to annotate code using annotations for another purpose).
Another point in favour of that approach: stub files could be evaluated holistically rather than statement at a time, permitting implicit forward references.
Cheers,
Nick.
>
> Cheers,
> -Barry
> _______________________________________________
> Python-Dev mailing list
> Pytho...@python.org
> https://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: https://mail.python.org/mailman/options/python-dev/ncoghlan%40gmail.com
A very, very strong -1 to that.
Stub files are a necessary evil. Except where absolutely necessary,
they should be strongly discouraged. A quote from the Go FAQs:
Dependency management is a big part of software development
today but the “header files” of languages in the C tradition
are antithetical to clean dependency analysis—and fast
compilation.
http://golang.org/doc/faq#What_is_the_purpose_of_the_project
Things that go together should be together. A function parameter and
its type information (if any) go together: the type is as much a part
of the parameter declaration as the name and the default. Putting them
together is the best situation:
def func(n: Integer): ...
and should strongly be prefered as best practice for when you choose to
use type hinting at all. Alternatives are not as good. Second best is to
put them close by, as in a decorator:
@typing(n=Integer) # Don't Repeat Yourself violation
def func(n): ...
A distant third best is a docstring. Not only does it also violate DRY,
but it also increases the likelyhood of errors:
def func(n):
"""Blah blah blah
blah blah blah
Arguments:
m: Integer
"""
Keeping documentation and code in synch is hard, and such mistakes are
not uncommon.
Putting the type information in a stub file is an exponentially more
distant fourth best, or to put it another way, *the worst* solution for
where to put type hints. Not only do you Repeat Yourself with the name
of the parameter, but also the name of the function (or method and
class) AND module. The type information *isn't even in the same file*,
which increases the chance of it being lost, forgotten, deleted, out of
date, unmaintained, etc.
Twelve years ago a wise man said to me "I suggest that you also propose a new name for the resulting language"
I talked with many of you at PyCon about the costs of PEP 484. There are plenty of people who have done a fine job promoting the benefits.
* It is not optional. Please stop saying that. The people promoting it would prefer that everyone use it. If it is approved it will be optional in the way that PEP8 is optional. If I'm reading your annotated code it is certainly /not/ optional that I understand the annotations.
* Uploading stubs for other people's code is a terrible idea. Who do I contact when I update the interface to my library? The random Joe who "helped" by uploading annotations three months ago and then quit the internet? I don't even want to think about people maliciously adding stubs to PyPI.
* The cognitive load is very high. The average function signature will double in length. This is not a small cost and telling me it is "optional" to pretend that every other word on the line doesn't exist is a farce.
* Every company's style guide is about to get much longer. That in itself is an indicator that this is a MAJOR language change and not just some "optional" add-on.
* People will screw it up. The same people who can't be trusted to program without type annotations are also going to be *writing* those type annotations.
* Teaching python is about to get much less attractive. It will not be optional for teachers to say "just pretend all this stuff over here doesn't exist"
* "No new syntax" is a lie. Or rather a red herring. There are lots of new things it will be required to know and just because the compiler doesn't have to change doesn't mean the language isn't undergoing a major change.
If this wasn't in a PEP and it wasn't going to ship in the stdlib very few people would use it. If you told everyone they had to install a different python implementation they wouldn't. This is much worse than that - it is Python4 hidden away inside a PEP.
There are many fine languages that have sophisticated type systems. And many bondage & discipline languages that make you type things three times to make really really sure you meant to type that. If you find those other languages appealing I invite you to go use them instead.
-Jack
On 21 April 2015 at 10:10, Chris Angelico <ros...@gmail.com> wrote:At this point, you may want to just stop caring about the exact type. Part of the point of gradual typing is that you can short-cut a lot of this. And quite frankly, this isn't really helping anything. Just skip it and say that it's Union[Mapping, Iterable, None].I think this is my problem with the proposal. This change doesn't catch any of the bugs anyone was going to hit (no-one is passing a callable to this parameter), and it doesn't catch any of the bugs someone might actually hit (getting the tuple elements in the wrong order, for example). At this point the type signature is worse than useless.
(ii) can be done with appropriate runtime checks and good error messages.
E.g. (Cory's example) I'm sure it is possible to test somehow if an object is file-like (if only by trying to access it like a file).
Is thorough argument checking and provision of good diagnostics going to be easy for the library author? No. Is it going to be a lot of work to do thoroughly? Almost certainly yes.
But what the hell, writing a production-quality library is not an exercise for newbies.
It seems to me that type hints are attempting to be a silver bullet and to capture in a simple formula what is often, in practice, not simple at all, viz. "Is this passed object suitable?". Attempting - and failing, except in the simplest cases.
Apologies, Guido, but:
There was once a Chinese student who was a marvellous painter. He painted a perfect life-like picture of a snake.
But he was unable to stop and leave it alone. In his zeal he went on to paint feet on the snake. Which of course completely spoiled the picture, as snakes don't have feet.
Hence "to paint feet on the snake": to be unable to resist tinkering with something that is already good. (I suppose "If it ain't broke, don't fix it" is an approximate Western equivalent.)
You see where I'm going with this - adding type hints to Python feels a bit like painting feet on the snake. Or at least turning it into a different language.
Best wishes
Rob Cliffe
_______________________________________________
Python-Dev mailing list
Pytho...@python.org
https://mail.python.org/mailman/listinfo/python-dev
Well,
(i) can be done with good documentation (docstrings etc.).
Documentation is not checked. It often loses sync with the actual code. Docs say one thing, code does another.
> Anyway, I've not posted much to python-dev in quite a while, but this is
> a topic that I would be kicking myself in 5-10 years time when I've had
> to move to Javascript or <insert new language here> because everyone
> else has drifted away from Python as it had become ugly...
Facebook released Flow, a static typechecker for Javascript, to a very
positive reaction. From their announcement:
Flow’s type checking is opt-in — you do not need to type check all
your code at once. However, underlying the design of Flow is the
assumption that most JavaScript code is implicitly statically typed;
even though types may not appear anywhere in the code, they are in
the developer’s mind as a way to reason about the correctness of the
code. Flow infers those types automatically wherever possible, which
means that it can find type errors without needing any changes to
the code at all. On the other hand, some JavaScript code, especially
frameworks, make heavy use of reflection that is often hard to
reason about statically. For such inherently dynamic code, type
checking would be too imprecise, so Flow provides a simple way to
explicitly trust such code and move on. This design is validated by
our huge JavaScript codebase at Facebook: Most of our code falls in
the implicitly statically typed category, where developers can check
their code for type errors without having to explicitly annotate
that code with types.
Quoted here:
http://blog.jooq.org/2014/12/11/the-inconvenient-truth-about-dynamic-vs-static-typing/
More about flow:
Matz is interested in the same sort of gradual type checking for Ruby as
Guido wants to add to Python:
Julia already includes this sort of hybrid dynamic+static type checking:
http://julia.readthedocs.org/en/latest/manual/types/
I could keep going, but I hope I've made my point. Whatever language you
are using in 5-10 years time, it will almost certainly be either mostly
static with some dynamic features like Java, or dynamic with optional
and gradual typing.
--
Steven
_______________________________________________
Python-Dev mailing list
Pytho...@python.org
https://mail.python.org/mailman/listinfo/python-dev
Further, Python's type system is not sufficiently flexible to allow
library authors to adequately specify the types their code actually
works on. I need to be able to talk about interfaces, because
interfaces are the contract around which APIs are build in Python, but
I cannot do that with this system in a way that makes any sense at
all. To even begin to be useful for library authors this PEP would
need to allow some kind of type hierarchy that is *not* defined by
inheritance, but instead by interfaces. We've been discouraging use of
'type' and 'isinstance' for years because they break duck typing, but
that has *nothing* on what this PEP appears to do to duck typing.
I was replying to Steven's message. Did you read it?
> Runtime type checking (run as via "make test", not
> as "production") is much more interesting to catch errors.
Obviously you're giving the word "runtime" a different meaning than I
do. The type checker isn't supposed to actually execute the user's
functions (it's not that it's forbidden, simply that it's not how it
will work in all likelihood): therefore, it doesn't have any handle on
what *actually* happens at runtime, vs. what is declared in the typing
declarations.
But if by "runtime" you mean any action that happens *out-of-band*
during development (such as running pip or a syntax-checking linter),
then sure, fine :-)
> Even more interesting usage is to allow ahead-of-time, and thus
> unbloated, optimization. There're bunch of JITters and AOTters for
> Python language, each of which uses own syntax (via decorators, etc.)
> to annotate functions.
As a developer of one of those tools, I've already said that I find it
unlikely for the PEP to be useful for that purpose. The issue is that
the vocabulary created in the PEP is not extensible enough.
Note I'm not saying it's impossible. I'm just skeptical that in its
current form it will help us. And apparently none of our "competitors"
seems very enthusiastic either (feel free to prove me wrong: I might
have missed something :-)).
> Having language-specified type annotations
> allows for portable syntax for such optimized code.
Only if the annotations allow expressing the subtleties required by the
specific optimizer. For example, "Float" is too vague for Numba: we
would like to know if that is meant to be a single- or double-precision
float.
> Don't block the language if you're stuck
> with an unimaginative implementation, there's much more to Python than
> that.
The Python language doesn't really have anything to do with that. It's
just an additional library with a set of conventions. Which is also why
a PEP wouldn't be required to make it alive, it's just there to make it
an official standard.
If you need to preprocess your source code to make it suitable for human
consumption something is very wrong with your language design. I can't
believe you're seriously suggesting this.
Best,
-Nikolaus
--
GPG encrypted emails preferred. Key id: 0xD113FCAC3C4E599F
Fingerprint: ED31 791B 2C5C 1613 AF38 8B8A D113 FCAC 3C4E 599F
»Time flies like an arrow, fruit flies like a Banana.«
...
Pretty accurate, yeah. Here's how I see it:
def incremental_parser(input: FileLike) -> List[Token]:
tokens = []
data = ""
while True:
if not data:
data = input.read(64)
token = Token(data[0]); data = data[1:]
while token.wants_more():
token.give_more(data[0]); data = data[1:]
tokens.append(token)
if token.is_end_of_stream(): break
input.seek(-len(data), 1)
return tokens
If you were to exhaustively stipulate the requirements on the
file-like object, you'd have to say:
* Provides a read() method which takes an integer and returns up to
that many bytes
* Provides a seek() method which takes two integers
* Is capable of relative seeking by at least 63 bytes backward
* Is open for reading
* Etcetera
That's not the type system's job. Not in Python. Maybe in Haskell,
but
not in Python. So how much _should_ go into the type hint? I'm happy
with "FileLike" or however it's to be spelled; maybe separate readable
files from writable ones, as those are two fairly clear variants, but
that's about all you really need.
If you provide incremental_parser()
with an input file that's non-seekable, it's going to have problems -
and your editor may or may not even be able to detect that (some files
are seekable but only in the forward direction, but they'll have the
exact same seek() method).
On 21.04.2015 05:37, Guido van Rossum wrote:
> On Mon, Apr 20, 2015 at 4:41 PM, Jack Diederich <jack...@gmail.com> wrote:
>> * Uploading stubs for other people's code is a terrible idea. Who do I
>> contact when I update the interface to my library? The random Joe who
>> "helped" by uploading annotations three months ago and then quit the
>> internet? I don't even want to think about people maliciously adding stubs
>> to PyPI.
>>
>
> We're certainly not planning to let arbitrary people upload stubs for
> arbitrary code to PyPI that will automatically be used by the type
> checkers. (We can't stop people from publishing their stubs, just as you
> can't stop people from writing blog posts or stackoverflow answers with
> examples for your library.)
>
> The actual plan is to have a common repository of stubs (a prototype exists
> at https://github.com/JukkaL/typeshed) but we also plan some kind of
> submission review. I've proposed that when submitting stubs for a package
> you don't own, the typeshed owners ask the package owner what their
> position is, and we expect the answers to fall on the following spectrum:
>
> - I don't want stubs uploaded for my package
> - I'll write the stubs myself
> - I want to review all stubs that are uploaded for my package before they
> are accepted
> - Please go ahead and add stubs for my package and let me know when they're
> ready
> - Go ahead, I trust you
>
> This seems a reasonable due diligence policy that avoids the scenarios
> you're worried about. (Of course if you refuse stubs a black market for
> stubs might spring into existence. That sounds kind of exciting... :-)
Hmm, that's the first time I've heard about this. I agree with
Jack that it's a terrible idea to allow this for 3rd party
packages.
If people want to contribute stubs, they should contribute them
to the package in the usual ways, not in a side channel. The important
part missing in the above setup is maintenance and to some extent
an external change of the API definitions.
Both require active participation in the package project,
not the separated setup proposed above, to be effective and
actually work out in the long run.
For the stdlib, typeshed looks like a nice idea to spread the
workload.
On Mon, 20 Apr 2015 20:43:38 -0400
"R. David Murray" <rdmu...@bitdance.com> wrote:
> +1 to this from me too. I'm afraid that means I'm -1 on the PEP.
>
> I didn't write this in my earlier email because I wasn't sure about it,
> but my gut reaction after reading Harry's email was "if type annotations
> are used in the stdlib, I'll probably stop contributing". That doesn't
> mean that's *true*, but that's the first time I've ever had that
> thought, so it is probably worth sharing.
I think it would be nice to know what the PEP means for daily stdlib
development. If patches have to carry typing information each time they
add/enhance an API that's an addition burden. If typing is done
separately by interested people then it sounds like it wouldn't have
much of an impact on everyone else's workflow.
On Mon, 20 Apr 2015 20:43:38 -0400
"R. David Murray" <rdmu...@bitdance.com> wrote:
> +1 to this from me too. I'm afraid that means I'm -1 on the PEP.
>
> I didn't write this in my earlier email because I wasn't sure about it,
> but my gut reaction after reading Harry's email was "if type annotations
> are used in the stdlib, I'll probably stop contributing". That doesn't
> mean that's *true*, but that's the first time I've ever had that
> thought, so it is probably worth sharing.
I think it would be nice to know what the PEP means for daily stdlib
development. If patches have to carry typing information each time they
add/enhance an API that's an addition burden. If typing is done
separately by interested people then it sounds like it wouldn't have
much of an impact on everyone else's workflow.
The correct specification is "read method with this type signature"
and "seek method with this type signature". I would even be prepared
to waive the type signatures on read and seek, given that enforcing
the type hinting on others is not a good idea.
I suspect I have a mismatch with several others in this discussion. My
position is that if I'm going to have a type system, I'd like to have
a powerful one: Haskell, not Java. Otherwise I'll get by with the duck
typing that has worked just fine for us over the last 20 years. I
suspect, however, that many others in this conversation want any type
system at all, so long as they can have one.
That'd be a relief. It didn't sound ironic to me.
> The proposed type annotations are very readable.
[..]
I don't have an informed opinion about that yet. I was just commenting
on the general idea of stripping them away if they're not readable.
Best,
-Nikolaus
--
GPG encrypted emails preferred. Key id: 0xD113FCAC3C4E599F
Fingerprint: ED31 791B 2C5C 1613 AF38 8B8A D113 FCAC 3C4E 599F
»Time flies like an arrow, fruit flies like a Banana.«
Please be respectful rather than inflammatory. If you read what I
wrote, I did not say that I was going to stop contributing, I
specifically talked about that gut reaction being both emotional and
illogical. That doesn't make the reaction any less real, and the fact
that such reactions exist is a data point you should consider in
conducting your PR campaign for this issue. (I don't mean that last as
a negative: this issue *requires* an honest PR campaign.)
I've never done this before, so I might not quite have done it
correctly, but this appears to work just fine:
py> import abc
py> class SeekableReadable(metaclass=abc.ABCMeta):
... @classmethod
... def __subclasshook__(cls, C):
... if hasattr(C, 'seek') and hasattr(C, 'read'):
... return True
... return NotImplemented
...
py> f = open('/tmp/foo')
py> isinstance(f, SeekableReadable)
True
py> from io import StringIO
py> issubclass(StringIO, SeekableReadable)
True
py> issubclass(int, SeekableReadable)
False
That gives you your runtime check for an object with seek() and read()
methods. For compile-time checking, I expect you would define
SeekableReadable as above, then make the declaration:
def read_from_start(f:SeekableReadable, size:int):
f.seek(0)
return f.read(size)
So now you have runtime interface checking via an ABC, plus
documentation for the function parameter type via annotation.
But will the static checker understand that annotation? My guess is,
probably not as it stands. According to the docs, MyPy currently
doesn't support this sort of duck typing, but will:
[quote]
There are also plans to support more Python-style “duck typing”
in the type system. The details are still open.
[end quote]
I expect that dealing with duck typing will be very high on the list
of priorities for the future. In the meantime, for this specific use-case,
you're probably not going to be able to statically check this type hint.
Your choices would be:
- don't type check anything;
- don't type check the read_from_start() function, but type check
everything else;
- don't type check the f parameter (remove the SeekableReadable
annotation, or replace it with Any, but leave the size:int
annotation);
- possibly some type checkers will infer from the function body that f
must have seek() and read() methods, and you don't have to declare
anything (structural typing instead of nominal?);
- (a bad idea, but just for the sake of completeness) leave the
annotation in, and ignore false negatives.
Remember that there is no built-in Python type checker. If you have no
checker, the annotations are just documentation and nothing else will
have changed. If you don't like the checker you have, you'll be able to
replace it with another.
--
Steve
Please be respectful rather than inflammatory.
If you read what I wrote, I did not say that I was going to stop contributing, I specifically talked about that gut reaction being both emotional and illogical. That doesn't make the reaction any less real, and the fact that such reactions exist is a data point you should consider in conducting your PR campaign for this issue. (I don't mean that last as a negative: this issue *requires* an honest PR campaign.)
P.S. I do member a time when tools to easily check for memory leaks in C were new and magical. Looking at the Coverity scans, I'm glad that the old magic is reaping real benefits.
Two areas of clarification would be helpful for me:
1. Optional: What does this really mean in practice? Am I opting in to static type checking and type hints? Or must I opt out of type hints? Having to opt out would probably put more burden on the educational use cases than opting in would for a large corporate project.
2. Clearly, great thought has been put into this PEP. If anyone has a good analysis of the potential impact on Python 3 adoption, please do pass along. I would be interested in reading the information.
At least nobody will be writing type hints in Cyrillic. :-)
On Apr 21, 2015, at 11:23 AM, Guido van Rossum <gu...@python.org> wrote:
2. Clearly, great thought has been put into this PEP. If anyone has a good analysis of the potential impact on Python 3 adoption, please do pass along. I would be interested in reading the information.
I wish I had a crystal ball, but this is hard to predict. Anecdotally, some people believe this will be catnip, while others believe it to be poison. The truth will surely be somewhere in the middle. At this point we don't know what drives Python 3 adoption except time -- it's definitely going up. :-)