1

Let's say I have a function dict_to_string:

>>> def dict_to_string(d: ??) -> str:
...     return ';'.join(f"{k},{v}" for k, v in vars(d).items())

What type hint is required to ensure that d has __dict__ and not __slots__, (or vice-versa, for future reference).

I know I can just check hasattr(d, '__dict__') and not __slots__, but I would like to know if it is possible to type hint.

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
  • Do you mean you want to ensure that a class *does not* have a `__slots__` attribute, along with checking that it *does* have a `__dict__`? I believe it's possible to do the latter, but I don't think the former is possible. – Carcigenicate Oct 03 '20 at 14:32
  • Yes, I *want to ensure that a class does not have a __slots__ attribute, along with checking that it does have a __dict__* – Sayandip Dutta Oct 03 '20 at 14:36
  • I don't think you can check if a class *doesn't* have an attribute. You could likely do the `__dict__` check using `Protocol` from `typing` though. I think `Protocol` works on attributes as well as methods. – Carcigenicate Oct 03 '20 at 14:37
  • I see, could you post an answer? Not very well versed with `Protocol`. – Sayandip Dutta Oct 03 '20 at 14:40
  • 1
    So, I just spent 10 minutes writing an answer, and it doesn't work for `__dict__`. I can get it to check other attributes properly, but it fails for `__dict__` specifically. I might write a separate Q&A though to address the generalized question here, since I don't think that that's documented anywhere. – Carcigenicate Oct 03 '20 at 14:54
  • Ah! Nevermind. Hopefully will be able to figure out something eventually. Thanks for trying! – Sayandip Dutta Oct 03 '20 at 14:58
  • 1
    See my self Q&A [here](https://stackoverflow.com/questions/64185810/how-can-i-use-static-checking-to-ensure-an-object-has-a-certain-method-attribute/64185811#64185811). You may be able to get something working if you play around with it. – Carcigenicate Oct 03 '20 at 15:23

0 Answers0