5

Is there a way or a trick to implement async constructor in python? I know we can't do the thing I typed below but I mean something with this functionality. If no, what is the concept behind this that doesn't let it be async? thanks in advance.

async def __init__(self, param):
    result = await my_method(param)

async def my_method(param):
    # do something async
Amin Etesamian
  • 3,363
  • 5
  • 27
  • 50
  • 1
    A constructor shouldn't really be doing work so intense that it's asynchronous… – deceze Sep 06 '16 at 14:23
  • 1
    @deceze could you explain to me why such intense works should'nt be done in constructor? – Amin Etesamian Sep 06 '16 at 14:41
  • It's generally a good idea to keep your constructors light. Link to further opinions: http://stackoverflow.com/a/23623981/476 – deceze Sep 06 '16 at 14:47
  • I'm using some async database drivers that return cursors. Would be nice to get all the items with `all_items = await list(cursor)` instead of the current method which is a await loop everywhere and appending to a list. Though 3.6 looks like it's going to introduce `all_items = [i for await i in cursor]` https://www.python.org/dev/peps/pep-0530/ – freebie Sep 09 '16 at 15:20
  • 5
    Note: `__init__` is called initializer, `__new__` is a constructor – webknjaz -- Слава Україні Mar 09 '19 at 13:18
  • I'd recognize __new__ in Python an **allocator** instead of **constructor**. While in C++ new is no doubt a constructor, as you have **placement new** besides allocators. – Compl Yue Apr 20 '20 at 07:52

0 Answers0