Skip to content

What's the right set of declarations here? #755

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

Closed
smontanaro opened this issue Dec 7, 2016 · 2 comments
Closed

What's the right set of declarations here? #755

smontanaro opened this issue Dec 7, 2016 · 2 comments

Comments

@smontanaro
Copy link

I've got a class which takes a port number (int) and hostname (str):

class X(object):
    def __init__(self, port=6600, host="x.y.com"):
        ...

elsewhere, it can be instantiated using values extracted from a dictionary:

if x is not None:
    self.x = X(port=x['port'], host=x['host'])

That dictionary is itself a parameter declared as as mapping strings to strings or ints:

    # type: Dict[str, Union[str, int]]

mypy complains about the call to X(...) because the values in x can be either strings or ints, but the port and host parameters are declared to be one or the other, not the union of the two.

What's the correct way to work around this issue?

@gvanrossum
Copy link
Member

Short-term, your best bet is # type: ignore. You could also use casts but those have runtime costs (it's a Python function call so probably costs way more than than the dict lookups). In the future we'll have a "TypedDict" type that you can use for the type of that dictionary; see python/mypy#985 and search the tracker for TypedDict to find various tasks still open before that's a viable solution.

@smontanaro
Copy link
Author

smontanaro commented Dec 7, 2016 via email

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

No branches or pull requests

2 participants