Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to type hint a homogenous Queue in Python3.6 (especially for PyCharm)?

I'm writing a fractal generator in Python 3.6, and I use multiprocessing.Queues to pass messages from the main thread to the workers. This is what I've tried so far, but PyCharm doesn't seem to be able to infer attribute types for items taken from the queues:

from typing import NamedTuple, Any, Generic, TypeVar, Tuple
from multiprocessing import Process, Queue

T = TypeVar()


class Message(NamedTuple):
    method: str
    id: str
    data: Any = None


class TypedQueue(Generic[T]):
    def get(self) -> T:
        ...
    def put(self, m: T) -> None:
        ...


MessageQ = TypedQueue[Message]


class FractalWorker(Process):
    def __init__(self, work: MessageQ, results: MessageQ)
        super().__init__()
        self.work = work
        self.results = results

    @staticmethod
    def make_queues() -> Tuple[MessageQ, MessageQ]:
        work = cast(MessageQ, Queue())
        results = cast(MessageQ, Queue())
        return work, results

I want PyCharm to be able to tell that the attributes of the result of self.work.get have the types specified by the Message class. I also want to know if there is a standard way of type hinting Queues similar to this.

like image 513
Broseph Avatar asked Feb 23 '18 21:02

Broseph


People also ask

How do you type hints in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

Should I use type hinting in Python?

Type hints help you build and maintain a cleaner architecture. The act of writing type hints forces you to think about the types in your program. While the dynamic nature of Python is one of its great assets, being conscious about relying on duck typing, overloaded methods, or multiple return types is a good thing.

What are type hints?

Type hinting is a formal solution to statically indicate the type of a value within your Python code. It was specified in PEP 484 and introduced in Python 3.5. Here's an example of adding type information to a function.


1 Answers

Old Question, but I just found

P: "Queue[Path]" = Queue()

to work with both queue.Queue and multiprocessing.Queue in PyCharm

like image 158
Xtrem532 Avatar answered Oct 11 '22 11:10

Xtrem532