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())