{"id":23046469,"url":"https://github.com/francis-clairicia/async-object","last_synced_at":"2025-08-25T00:32:00.170Z","repository":{"id":65149107,"uuid":"584043696","full_name":"francis-clairicia/async-object","owner":"francis-clairicia","description":"async-object let you write classes with async def __init__","archived":false,"fork":false,"pushed_at":"2024-01-29T08:21:13.000Z","size":95,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-12-15T22:28:33.029Z","etag":null,"topics":["asyncio","python","python-async","python-asynchronous","python3"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/francis-clairicia.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-01-01T04:02:19.000Z","updated_at":"2024-11-25T01:23:05.000Z","dependencies_parsed_at":"2023-12-26T17:46:48.658Z","dependency_job_id":"88d3d455-947d-485f-84e8-e84271eb9930","html_url":"https://github.com/francis-clairicia/async-object","commit_stats":{"total_commits":16,"total_committers":2,"mean_commits":8.0,"dds":0.0625,"last_synced_commit":"59ade1c63fb4156126c9953744ab625f411ecce5"},"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/francis-clairicia%2Fasync-object","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/francis-clairicia%2Fasync-object/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/francis-clairicia%2Fasync-object/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/francis-clairicia%2Fasync-object/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/francis-clairicia","download_url":"https://codeload.github.com/francis-clairicia/async-object/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230852606,"owners_count":18290081,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asyncio","python","python-async","python-asynchronous","python3"],"created_at":"2024-12-15T22:24:42.160Z","updated_at":"2024-12-22T15:54:11.188Z","avatar_url":"https://github.com/francis-clairicia.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# async-object\n[![Test](https://github.com/francis-clairicia/async-object/actions/workflows/test.yml/badge.svg)](https://github.com/francis-clairicia/async-object/actions/workflows/test.yml)\n[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit)](https://github.com/pre-commit/pre-commit)\n[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/francis-clairicia/async-object/main.svg)](https://results.pre-commit.ci/latest/github/francis-clairicia/async-object/main)\n\n[![PyPI](https://img.shields.io/pypi/v/async-object)](https://pypi.org/project/async-object/)\n[![PyPI - License](https://img.shields.io/pypi/l/async-object)](https://github.com/francis-clairicia/async-object/blob/main/LICENSE)\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/async-object)\n\n[![Checked with mypy](http://www.mypy-lang.org/static/mypy_badge.svg)](http://mypy-lang.org/)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat\u0026labelColor=ef8336)](https://pycqa.github.io/isort/)\n\n`async-object` let you write classes with `async def __init__`\n\n## Installation\n### From PyPI repository\n```sh\npip install --user async-object\n```\n\n### From source\n```sh\ngit clone https://github.com/francis-clairicia/async-object.git\ncd async-object\npip install --user .\n```\n\n## Usage\nIt is simple, with `async-object` you can do this:\n```py\nfrom async_object import AsyncObject\n\n\nclass MyObject(AsyncObject):\n    async def __init__(self) -\u003e None:\n        await super().__init__()\n\n        # Do some async stuff\n\n\nif __name__ == \"__main__\":\n    import asyncio\n\n    async def main() -\u003e None:\n        instance = await MyObject()\n        assert isinstance(instance, MyObject)\n\n    asyncio.run(main())\n```\n\nThis example uses `asyncio`, but it is compatible with all runner libraries, since this package only uses the language syntax.\n\n## Description\n`async-object` provides a base class `AsyncObject` using `AsyncObjectMeta` metaclass.\n\n`AsyncObjectMeta` overrides the default `type` constructor in order to return a coroutine, which must be `await`-ed to get the instance.\n\n```py\nasync def main() -\u003e None:\n    coroutine = MyObject()\n    print(coroutine)\n    instance = await coroutine\n    print(instance)\n```\n\nReplace the `main` in the [Usage](#usage) example by this one and run it. You should see something like this in your console:\n```\n\u003ccoroutine object AsyncObjectMeta.__call__ at 0x7ff1f28eb300\u003e\n\u003c__main__.MyObject object at 0x7ff1f21a4fd0\u003e\n```\n\n### Arguments\nObviously, arguments can be given to `__init__` and `__new__`.\nThe inheritance logic with \"normal\" constructors is the same here:\n```py\nfrom typing_extensions import Self\n\nclass MyObjectOnlyNew(AsyncObject):\n    def __new__(cls, *args: Any, **kwargs: Any) -\u003e Self:\n        self = super().__new__(cls)\n\n        print(args)\n        print(kwargs)\n\n        return self\n\n\nclass MyObjectOnlyInit(AsyncObject):\n    async def __init__(self, *args: Any, **kwargs: Any) -\u003e None:\n        # await super().__init__()  # Optional if the base class is only AsyncObject (but useful in multiple inheritance context)\n\n        print(args)\n        print(kwargs)\n\n\nclass MyObjectBothNewAndInit(AsyncObject):\n    def __new__(cls, *args: Any, **kwargs: Any) -\u003e Self:\n        self = super().__new__(cls)\n\n        print(args)\n        print(kwargs)\n\n        return self\n\n    async def __init__(self, *args: Any, **kwargs: Any) -\u003e None:\n        # await super().__init__()\n\n        print(args)\n        print(kwargs)\n```\n\n### Inheritance\nTalking about inheritance, there are a few rules to follow:\n- `AsyncObject` or a subclass must appear at least once in the base classes declaration.\n- Non-`AsyncObject` classes can be used as base classes if they do not override `__init__` (in order not to break the [MRO](https://docs.python.org/3/glossary.html#term-method-resolution-order)).\n- To avoid confusion with [awaitable objects](https://docs.python.org/3/glossary.html#term-awaitable), overriding `__await__` is forbidden.\n\n### Abstract base classes\nThere is a metaclass `AsyncABCMeta` deriving from `AsyncObjectMeta` and `abc.ABCMeta` which allows you to declare abstract base classes\n```py\nimport abc\n\nfrom async_object import AsyncObject, AsyncABCMeta\n\n\nclass MyAbstractObject(AsyncObject, metaclass=AsyncABCMeta):\n    @abc.abstractmethod\n    def method(self) -\u003e None:\n        raise NotImplementedError\n\n    @abc.abstractmethod\n    async def async_method(self) -\u003e None:\n        raise NotImplementedError\n\n\nclass MyObject(MyAbstractObject):\n    async def __init__(self) -\u003e None:\n        pass\n\n    def method(self) -\u003e None:\n        pass\n\n    async def async_method(self) -\u003e None:\n        pass\n```\n\nN.B.: There is a shorthand `AsyncABC` like `abc.ABC`.\n```py\nimport abc\n\nfrom async_object import AsyncABC\n\n\nclass MyAbstractObject(AsyncABC):\n    @abc.abstractmethod\n    def method(self) -\u003e None:\n        raise NotImplementedError\n\n    @abc.abstractmethod\n    async def async_method(self) -\u003e None:\n        raise NotImplementedError\n```\n\n## Static type checking: mypy integration\n`mypy` does not like having `async def` for `__init__`, and will not understand `await AsyncObject()`.\n\n`async-object` embeds a plugin which helps `mypy` to understand asynchronous constructors.\n\n### Installation\nFirstly, install the needed dependencies:\n```sh\npip install async-object[mypy]\n```\n\nTo register this plugin in your `mypy.ini`, `pyproject.toml`, or whatever, you must add `async_object.contrib.mypy.plugin` to the plugins list.\n\nIn `mypy.ini`:\n```ini\n[mypy]\nplugins = async_object.contrib.mypy.plugin\n```\n\nIn `pyproject.toml`:\n```toml\n[tool.mypy]\nplugins = [\"async_object.contrib.mypy.plugin\"]\n```\n\nFor more information, see [the mypy documentation](https://mypy.readthedocs.io/en/stable/extending_mypy.html#configuring-mypy-to-use-plugins).\n\n### What is permitted then ?\n#### `__init__` method returning a coroutine is accepted\nThe error `The return type of \"__init__\" must be None` is discarded.\n```py\nclass MyObject(AsyncObject):\n    async def __init__(self, param: int) -\u003e None:\n        await super().__init__()\n```\n\n#### The class instanciation introspection is fixed\n```py\nasync def main() -\u003e None:\n    coroutine = MyObject()\n    reveal_type(coroutine)  # Revealed type is \"typing.Coroutine[Any, Any, __main__.MyObject]\"\n    instance = await coroutine\n    reveal_type(instance)  # Revealed type is \"__main__.MyObject\"\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffrancis-clairicia%2Fasync-object","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffrancis-clairicia%2Fasync-object","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffrancis-clairicia%2Fasync-object/lists"}