#πŸ”’ typing: enforce homogeneous list in function parameter

14 messages Β· Page 1 of 1 (latest)

pale quarry
#

let's say i have a function that takes a homogeneous list and returns one of the items:

def fn[T](xs: list[T]) -> T:
  return xs[0] # just as an example, actual fn is more involved

fn(['a','b','c']) # fine
fn([1,2,3])       # fine
fn([1,2,'c'])     # this should error but doesn't in my editor
  1. is it a problem with my pyright setup?
  2. is there a different way i should be typing this?

python 3.12.2, pyright

formal spindleBOT
#

@pale quarry

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.

jade loom
#

in the last case, T just resolves to int | str or object, so there's no problem

iron bluff
#

you cannot force a non-union

pale quarry
#

i don’t want it to resolve to object or a union though, i want it to be a single type across the list or be an error

iron bluff
#

it's simply not possible with passing a literal like this

pale quarry
#

:/

deep lake
#

You can check if T is an Union (I think?) by using typing.get_origin @pale quarry

iron bluff
#

(although that is runtime, right?)

last basalt
#

πŸ€” Wouldn't that be a runtime check rather than with pyright?

deep lake
#

Oh yeah, I was just thinking in case they didn't find a better solution and wanted to enforce the sameness of T

pale quarry
#

yeah prefer a type check here, thx for the info and suggestions everyone!

disappointing outcome but it is what it is πŸ™ƒ

formal spindleBOT
#
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.