jeudi 27 juillet 2017

Python 3: best way to reuse the code in project, when need to expose both classic + asyncio interfaces to user

The project is Python 3 library (package), implementing custom stream binary protocol. Think of pair of stream processing classes:

MyEncodingWriter(dst_stream) - translates Python objects to raw byte stream MyDecodingReader(src_stream) - translates raw encoded bytes to messages or Python objects

I need to support both blocking sync streams and asyncio StreamReader + StreamWriter, (probably, with subclassing from them)

I understand I can't use coroutines as regular sync functions directly.

I think to mimic asyncio reader/writer API's (read(), readexactly(),...) in my classes MyEncodingWriter() and MyDecodingReader(), so the only differences will be extra async/await keywords in asyncio version.

It's strange for me I will have two copies or repos with very similar code which I can't reuse.

For now I have only this idea... ...try to generate dynamically sync code from async (by stripping async/wait keywords) with help of metaclass, maybe?

It there some better approach?

TYA for any suggestions or beautiful sampes/repos of a such dual implementation.

Aucun commentaire:

Enregistrer un commentaire