#๐ how do i type hint accepting a generator
40 messages ยท Page 1 of 1 (latest)
@unborn bear
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.
So, generators are just iterators, basically
and you type hint an iterator with typing.Iterator[return_value]
so you'd want
from typing import Any, Iterator
def board_gen(board: Any) -> Iterator[tuple[int, int]]:
...
yield (1, 1)
Btw for type hint help I recommend https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html
(apologies, I used parens rather than square brackets for the type hint - this is now fixed)
but i pass an arg to create the generator AFTER i accepted it as an arg
i need to hint accepting it
I'm feeling dumb - sorry - is the parameter itself the generator?
maybe i dont really got whats the generator the instance the function or what
in the example i have to hint board_gen itself
But I did type hint that
OK - so then that's a callable that passes in a board and returns an iterator
and ill need in the init to pass self.board to the p1
from typing import Any, Iterator, Callable
class Board:
pass
class Game:
def __init__(self, p1):
pass
def board_gen(board: Board) -> Iterator[tuple[int, int]]:
...
yield (1, 1)
p1: Callable[[Board], Iterator[tuple[int, int]]] = board_gen
g = Game(p1 = board_gen)
whats the diff between typing.Generator and Iterator?
you really ought to use collections.abc.Generator; typing.Generator is deprecated
The difference is I didn't know that existed - I just used the cheat sheets hints XD
but you can use typing.Generator as well
but Generator can receive values from yield, not just produce them
what? i didnt even know that
that may be what im looking for tho
most of the time this aspect of generators is not used
they're usually just used as fancy iterators
how do i code that accepting part?
assign the yielded value to a local variable
and then you'd have to use the send() method in the generator object
is this what you're really after though?
i have a player/bot and i could eiter pass a reference at start to the board or pass the snapshots as thair turn starts
it's best if you didn't use generators until you're sure that's what you need
passing a snapshot aka .copy() would be best bc than they cant do illegal steps
and i need to define the players ssepearatly so i can do pvp bvp bvb anything
!close
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.