#๐Ÿ”’ Dealing with string parameters when maintaining a Python package (typehinting, typechecking)

9 messages ยท Page 1 of 1 (latest)

fervent steppe
#

I'm maintaining a scientific Python package which takes string parameters for some arguments. For example:

def method(...
    interp_method, # options being "cgrid_velocity", "partialslip", "freeslip"
):

I know that I can type annotate these using Literal[...] and define a type alias in a _typing.py file (e.g, InterpMethod = Literal[...]) to avoid repetition. What I want to know is:

  • How could I do runtime typechecking here in a way that promotes a single source of truth? Is there a standard approach here? A lot of methods take interp_method as a parameter and I don't want to repeat myself

Any resources on type guarding in public APIs would be useful.

sonic gullBOT
#

@fervent steppe

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

plucky crown
#

There ain't really runtime typecheck unless you are doing it yourself

#

You can write a function and use TypeGuard to statically and runtime check them

#

!d typing.TypeGuard

sonic gullBOT
#

typing.TypeGuard```
Special typing construct for marking user\-defined type guard functions.

`TypeGuard` can be used to annotate the return type of a user\-defined type guard function. `TypeGuard` only accepts a single type argument. At runtime, functions marked this way should return a boolean.

`TypeGuard` aims to benefit *type narrowing* โ€“ a technique used by static type checkers to determine a more precise type of an expression within a programโ€™s code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a โ€œtype guardโ€:
plucky crown
#

You write a function that promise it type narrow the type to the specific type (which static type checker would believe), and it is your duty to handle it by e.g. raising error

sonic gullBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.