Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type hinting for traces_sampler #1090

Closed
Ogaday opened this issue Apr 16, 2021 · 2 comments · Fixed by #1091
Closed

Type hinting for traces_sampler #1090

Ogaday opened this issue Apr 16, 2021 · 2 comments · Fixed by #1091

Comments

@Ogaday
Copy link
Contributor

Ogaday commented Apr 16, 2021

I'm finding the the type declaration of the traces_sampler argument to the sentry_sdk.init constructor a bit problematic.

Environment

  • Sentry SaaS (sentry.io)
  • Python: sentry-sdk[flask]==0.19.4
  • mypy==0.812
  • mypy-extensions==0.4.3

Steps to Reproduce

I can't get any variations of the following code to appease mypy:

from typing import Any, Dict, Union
import sentry_sdk


def sampler(context: Dict[str, Any]) -> Union[float, bool]:
    return 1.0


sentry_sdk.init(dsn='', traces_sampler=sampler)

I think think the type declaration (... -> Union[float, bool]) here is sensible. However, because of the declaration here, mypy complains as follows:

sentry.py:9: error: Argument "traces_sampler" to "init" has incompatible type "Callable[[Dict[str, Any]], Union[float, bool]]"; expected "Optional[Callable[[Dict[str, Any]], Union[Real, bool]]]"

If I try something like this instead:

from numbers import Real
from typing import Any, Dict, Union
import sentry_sdk


def sampler(context: Dict[str, Any]) -> Union[Real, bool]:
    return 1.0


sentry_sdk.init(dsn='', traces_sampler=sampler)

I get a different error:

sentry.py:7: error: Incompatible return value type (got "float", expected "Union[Real, bool]")

Which makes sense to me. I also can't delare my return type as Real:

    proba: Real = 1.0
    return proba

gives

sentry.py:7: error: Incompatible types in assignment (expression has type "float", variable has type "Real")

So what is the solution here? Is there a reason Real was chosen as the return type instead of float?

Thanks in advance.

@untitaker
Copy link
Member

untitaker commented Apr 16, 2021 via email

@Ogaday
Copy link
Contributor Author

Ogaday commented Apr 16, 2021

Done, please let me know if I need to change anything.

In the mean time, I found a workaround for typing a custom traces_sampler as follows:

def traces_sampler(context: Dict[str, Any]) -> Any:
    ...

Which isn't ideal but at least mypy doesn't complain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants