1

In the below example I have two methods: get and get_aio. Is it possible to have have these methods have the same name, so its the same API depending on if it's asyncio or a traditional function?

If it's not possible, what are some suggestions for naming conventions to provide both a traditional and an async API?

import asyncio

class Namespace(object):
    def __init__(self):
        self._set_futures = {}
        self._names = {}

    def get(self, name, default=None):
        return self._names.get(name, default)

    async def get_aio(self, name):
        await self._get_set_future(name)
        return self.get(name)

    def set(self, name, object):
        future = self._get_set_future(name)
        future.set_result(True)
        self._names[name] = object

    def _get_set_future(self, name):
        if name in self._set_futures:
            return self._set_futures[name]
        else:
            f = asyncio.Future()
            self._set_futures[name] = f
            return f

if __name__ == "__main__":
    namespace = Namespace()

    obj = "abc"
    namespace.set("obj", obj)

    get_obj_1 = namespace.get("obj")
    print(get_obj_1)

    async def bob():
        get_obj_2 = await namespace.get_aio("obj")
        print(get_obj_2)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(bob())
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
i_4_got
  • 918
  • 9
  • 10
  • It's technically possible to at least make a guess at if a function is being called as a coroutine or as a normal, synchronous function, but you're better off keeping distinct APIs to avoid ambiguity/confusion/guessing wrong. As far as a naming convention, it's up to you. I haven't seen any sort of standardization in the community around what prefix/suffix to use to differentiate sync/async. – dano Jun 01 '15 at 02:23
  • Thanks dano, I saw from the duplicate post, that it's not recommended, and mostly figured as much. – i_4_got Jun 01 '15 at 02:25

0 Answers0