stan-dev/pystan2

Using StanFit4Model with Python type hints

rgerkin opened this issue · 3 comments

Summary:

It is unclear how I can provide a "StanFit4Model" type hint.

Description:

Suppose I write a function that takes a fit and does something to it, like compute a single number:

def my_func(fit):
   return do_something(fit)

And I would like to provide type hints of the kind supported in Python 3.5 and described in PEP 484.

def my_func(fit: pystan.StanFit4model) -> float:
  return do_something(fit)

However, pystan.StanFit4Model (despite being called exactly this in the docs here) is not actually an importable thing. For example, none of these work from a fresh Python kernel:

from pystan import stanfit4model
from pystan.stanfit4model import StanFit4model)

Basically I just want something I can import, given that PyStan is installed, that will work with type hinting, i.e. a SOMETHING I can import for while the following assertion would pass:
assert isinstance(some_fit_instance, SOMETHING)

Reproducible Steps:

Either of the lines will not work from a fresh Python kernel with pystan installed:

from pystan import stanfit4model
from pystan.stanfit4model import StanFit4model

PyStan Version:

2.19.1.1

Python Version:

3.7

Operating System:

Ubuntu

Hi,

Yes, stanfit4model.pyx is a template file that is filled and then compiled to a module at runtime. So it can not be imported from PyStan.

We would need to write .pyi files for our compiled modules (like we are doing for httpstan / pystan3) --> https://github.com/stan-dev/httpstan/tree/master/httpstan

There are couple of options: Either,

extend PyStan2 with a PR (.pyi for the model)

or

use typing.Any and ignore the type. To assert that the type is correct, you can use the same procedure we use in ArviZ --> test against the class name

https://github.com/arviz-devs/arviz/blob/master/arviz/data/converters.py#L79

assert(some_fit_instance.__class__.__name__ == "StanFit4Model")

Oh yeah, I totally forgot that part.