ramonhagenaars / nptyping

💡 Type hints for Numpy and Pandas
MIT License
576 stars 29 forks source link

Allow simplified syntax: `arr: NDArray["2, 2", int]`? #92

Closed petered closed 1 year ago

petered commented 2 years ago

NPTyping is great, but could be more concise.

The main value of NDArray to me is to have a very concise way of documenting shapes.

I would propose

I'd be happy to make a PR to this effect if it is approved in spirit.

ramonhagenaars commented 2 years ago

Hi @petered ,

Concerning your two proposals:

petered commented 2 years ago

Hi Ramon, thanks for your response.

I don't understand MyPy enough to know the difficulty involved, and honestly probably won't have the time to invest to see if it's doable.

For me - the primary value of nptyping is just to have consistent documentation - I don't even run mypy.

Perhaps, assuming other people are using NDArray like I am - just as a form of documentation, we could add an experimental type that could later be merged into NDArray if mypy allows. Something like:

import numpy as np
from nptyping.experimental import Array

def adjust_brightness(rgb_image: Array["H,W,3", np.uint8], brightness_map: Array["H,W", float]
    ) -> Array["H,W,3", np.uint8]:
    ...

What would you think of this idea?

ramonhagenaars commented 2 years ago

Hi there Peter,

If documentation is the only thing you're after, then maybe aliasing literals may be sufficient for you? It would save you a dependency and you would be free to use Python primitives as well. You could still choose to use the nptyping shape expression syntax:

from typing import Literal as NDArray

arr: NDArray["H, W, 3", int]

What this lacks is that there is no checking of that syntax of course, but you could do that "offline" in a repl.

You could also alias nptyping.Shape to make it a bit less prominent:

from nptyping import NDArray, Int, Shape as _

arr: NDArray[_["H, W, 3", Int]]

I actually plan to promote this last trick for the upcoming nptyping.DataFrame that would look a bit convoluted otherwise.

I don't understand MyPy enough to know the difficulty involved

The difficulty is that MyPy simply regards a piece of string inside any type that is not a typing.Literal invalid. The same goes for IDEs such as Pycharm. If there is a string in a hint, it must be in typing.Literal. Otherwise, type checkers try to interpret the text as a type - e.g. list["int"] works perfectly fine. For this reason, I don't think this is going to change any time soon and therefore I'm a bit hestitant to add the experimental feature that you describe.

ramonhagenaars commented 1 year ago

No more recent activity: closing.