Mypy: Allow using modules as subtypes of protocols

Created on 10 May 2018  路  12Comments  路  Source: python/mypy

There is an idea to allow modules be accepted where a protocol is expected. This pattern is sometimes used for configs and option management, for example:

# file default_config.py
timeout = 100
one_flag = True
other_flag = False

# file __main__.py
import default_config
from typing import Protocol

class Options(Protocol):
    timeout: int
    one_flag: bool
    other_flag: bool

def setup(options: Options) -> None:
    ...

setup(default_config)  # OK

This will allow better typing than just types.ModuleType and should be straightforward to implement. Are there any objections against this?

feature priority-1-normal topic-protocols

All 12 comments

SGTM.

(As long as you add it to the PEP -- preferably as a separate PR.)

Sounds good. We should perhaps explicitly specify how module-level functions would work, since they don't take a self argument. Example:

# m.py
def f(x: int) -> None: pass

# main.py
import m
from typing import Protocol

class P(Protocol):
    def f(self, x: int) -> None: ...

p: P = m  # Should be ok?

@JukkaL Yes, I think just dropping the self is what everyone would expect.

Another use case would be interchanging the random module and random.Random objects. (Or numpy.random and numpy.random.RandomState.)

This is a nice way to make functions that either use the global RNG state or support overloading with explicit objects, e.g.,

import random
from typing import Protocol

class Random(Protocol):
    ...  # all methods from random.Random

def random_add(rng: Random = random):
    return rng.rand() + rng.rand()

This is a nice way to make functions that either use the global RNG state or support overloading with explicit objects, e.g.,

Yes, I think everyone is sold on this (there is already a PR to add this to the PEP 544), but we just didn't have time to implement this (even though it is pretty straightforward).

looks like the PEP was merged two years ago, but this is still an open issue. Is there any progress on this?

Is there any progress on this?

Please don't do this. You can see there's been no progress. Nagging only makes the (unpaid, volunteer) maintainers feel stressed and underappreciated. If you really need a feature, the best thing you can do is to dig into the codebase and open a PR.

I understand the etiquette, but from looking at the messages its unclear what the current state is - conversation seems to have just stalled. Its also labeled 'needs discussion'. @ilevkivskyi mentioned its straight forward work, what needs to be done? is it something a newbie can do?

is it something a newbie can do?

Hm, I think this is not the best first issue.

sorry for lecturing :sweat_smile:

Removed the "needs discussion" label since we would definitely want to have this. However, the design of the implementation will still need some discussion :-)

Was this page helpful?
0 / 5 - 0 ratings