[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

checking protocols.

Short question. Checking if a protocol is set up?

Many python improvements are changes to classes that implement a protocol.
There are things you can do to make your own classes work with the protocol
by setting various dunder variables like __iter__, __next__ and writing
appropriate ode including throwing the right error class when done.
Similarly the "with" statement works with objects that implement __enter__
and __exit__. There can be plenty of others like this and more can be
anticipated in the future.

So, several related questions. Tools that help a developer add appropriate
things to an object to implement the protocol or to test if it was done
right. Perhaps a function with a name like is_iterable() that tells if the
protocol can be applied. For the specific case of an iterable, I found
something that seems to work for at least some cases:

from collections import Iterable                                            
item = [1, 2, 3, 4]

isinstance(item, Iterable)

Not sure if it would work on one I created that did the right things or what
it checks.

I am interested in a pointer to something that describes many of the known
protocols or extensions and maybe to modules designed sort of as I said
above. I am aware some protocols may be not-quite standard with parts of the
protocol embedded in different objects like wrappers or objects returned
upon a request to have a proxy and many other techniques that seem to abound
and allow multiple layers of indirection or seemingly almost magical as in
multiple inheritance drop-ins and so on. That is what may make these things
harder if someone uses something like __getattr__ or descriptors to
intercept calls and provide the functionality without any actual sign of the
dunder key normally expected.

And, yes, I am aware of a tried and true method called try ... except ... to
see if it seems to work.