objectref


Nameobjectref JSON
Version 2023.10.20 PyPI version JSON
download
home_page
Summarydeal with object reference notations
upload_time2023-10-20 14:52:05
maintainer
docs_urlNone
authorAaron Tsang
requires_python>=3.7
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # objectref

objectref is a library to parse object references and find referenced objects.

## Notations

Object references are notations to locate modules or objects from the top level of a module.

```text
package.module
package.module:object.attr
```

The first form simply refers a module, while the second form an object in module.
It is also described in [here][1].

This library also supports relative object references (prefixed with dots).

[1]: https://packaging.python.org/en/latest/specifications/entry-points/#data-model

## Usage

* `find(ref: str, package: str | None = None) -> Any`

  The `find` function takes an object reference or `parse()` result,
  and returns the object pointed by the reference.

  The `package` argument must be set when the reference is relative.

  If qualified name is unspecified (the first form), the result is a module (`types.ModuleType` instance).

  `ModuleNotFoundError` is raised if the module cannot be found nor imported;
  `LookupError` if the object is not accessible from the top level of the module.

* `parse(ref: str) -> tuple[str, str | None]`

  The `parse` function takes an object reference,
  and results in a tuple of module name and qualified name.
  The qualified name would be `None` in first form.

  `ValueError` is raised if the reference is invalid.

## Example

```python
import os.path

import objectref

print(objectref.find("os.path") == os.path)  # True
print(objectref.find("os.path:join") == os.path.join)  # True
print(objectref.parse("os.path"))  # ("os.path", None)
print(objectref.parse("os.path:join"))  # ("os.path", "join")

```

## Entrypoint example

There are two main ways to execute a Python program.

* Run `python -m myapp.main` in shells, which executes the module as `__main__` under the hood.
  This relates to the first form of notation.

* Run `myapp` installed by pip. It is generated according to entrypoint defined in the project metadata
  (e.g. `myapp = myapp.main:main`).
  This requires the second form notation with callable objects.

Here is a code snippet to unify these two ways and start a program by its object reference.

```python
import objectref


def run(ref: str, package: str | None = None):
    modname, qualname = objectref.parse(ref)

    if qualname is None:
        # Use runpy to run a module with __name__ = "__main__"
        if modname.startswith("."):
            # runpy does not support relative module name.
            from importlib.util import resolve_name
            modname = resolve_name(modname, package)
        import runpy
        return runpy.run_module(modname, run_name="__main__")

    fn = objectref.find((modname, qualname), package)
    return fn()


if __name__ == "__main__":
    run("this")  # run the "this" module dynamically.

```

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "objectref",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "",
    "author": "Aaron Tsang",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/03/f6/7006fb5f7ce06fa64e825ac59ec5709f644f08f3396d9b4061f31bdb775f/objectref-2023.10.20.tar.gz",
    "platform": null,
    "description": "# objectref\n\nobjectref is a library to parse object references and find referenced objects.\n\n## Notations\n\nObject references are notations to locate modules or objects from the top level of a module.\n\n```text\npackage.module\npackage.module:object.attr\n```\n\nThe first form simply refers a module, while the second form an object in module.\nIt is also described in [here][1].\n\nThis library also supports relative object references (prefixed with dots).\n\n[1]: https://packaging.python.org/en/latest/specifications/entry-points/#data-model\n\n## Usage\n\n* `find(ref: str, package: str | None = None) -> Any`\n\n  The `find` function takes an object reference or `parse()` result,\n  and returns the object pointed by the reference.\n\n  The `package` argument must be set when the reference is relative.\n\n  If qualified name is unspecified (the first form), the result is a module (`types.ModuleType` instance).\n\n  `ModuleNotFoundError` is raised if the module cannot be found nor imported;\n  `LookupError` if the object is not accessible from the top level of the module.\n\n* `parse(ref: str) -> tuple[str, str | None]`\n\n  The `parse` function takes an object reference,\n  and results in a tuple of module name and qualified name.\n  The qualified name would be `None` in first form.\n\n  `ValueError` is raised if the reference is invalid.\n\n## Example\n\n```python\nimport os.path\n\nimport objectref\n\nprint(objectref.find(\"os.path\") == os.path)  # True\nprint(objectref.find(\"os.path:join\") == os.path.join)  # True\nprint(objectref.parse(\"os.path\"))  # (\"os.path\", None)\nprint(objectref.parse(\"os.path:join\"))  # (\"os.path\", \"join\")\n\n```\n\n## Entrypoint example\n\nThere are two main ways to execute a Python program.\n\n* Run `python -m myapp.main` in shells, which executes the module as `__main__` under the hood.\n  This relates to the first form of notation.\n\n* Run `myapp` installed by pip. It is generated according to entrypoint defined in the project metadata\n  (e.g. `myapp = myapp.main:main`).\n  This requires the second form notation with callable objects.\n\nHere is a code snippet to unify these two ways and start a program by its object reference.\n\n```python\nimport objectref\n\n\ndef run(ref: str, package: str | None = None):\n    modname, qualname = objectref.parse(ref)\n\n    if qualname is None:\n        # Use runpy to run a module with __name__ = \"__main__\"\n        if modname.startswith(\".\"):\n            # runpy does not support relative module name.\n            from importlib.util import resolve_name\n            modname = resolve_name(modname, package)\n        import runpy\n        return runpy.run_module(modname, run_name=\"__main__\")\n\n    fn = objectref.find((modname, qualname), package)\n    return fn()\n\n\nif __name__ == \"__main__\":\n    run(\"this\")  # run the \"this\" module dynamically.\n\n```\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "deal with object reference notations",
    "version": "2023.10.20",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c29499aa2e886cb6708a2cc1cc921f8bc522b97d879f2cc09944d600c5af48a4",
                "md5": "37e20a3c6ddeccc413dfe0e2c7fe4dd4",
                "sha256": "9f32e6b376ceb4d1816592c1478a637afc4af0524fc5ec5d74b10c192cc7b30d"
            },
            "downloads": -1,
            "filename": "objectref-2023.10.20-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "37e20a3c6ddeccc413dfe0e2c7fe4dd4",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 4394,
            "upload_time": "2023-10-20T14:52:03",
            "upload_time_iso_8601": "2023-10-20T14:52:03.312245Z",
            "url": "https://files.pythonhosted.org/packages/c2/94/99aa2e886cb6708a2cc1cc921f8bc522b97d879f2cc09944d600c5af48a4/objectref-2023.10.20-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "03f67006fb5f7ce06fa64e825ac59ec5709f644f08f3396d9b4061f31bdb775f",
                "md5": "c656f7f431baee21e774f659659cca1b",
                "sha256": "75d2c12945a9303d037809271c083a1c8b8e1ec71dca66995cba92267ca5f60c"
            },
            "downloads": -1,
            "filename": "objectref-2023.10.20.tar.gz",
            "has_sig": false,
            "md5_digest": "c656f7f431baee21e774f659659cca1b",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 7268,
            "upload_time": "2023-10-20T14:52:05",
            "upload_time_iso_8601": "2023-10-20T14:52:05.353798Z",
            "url": "https://files.pythonhosted.org/packages/03/f6/7006fb5f7ce06fa64e825ac59ec5709f644f08f3396d9b4061f31bdb775f/objectref-2023.10.20.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-20 14:52:05",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "objectref"
}
        
Elapsed time: 1.96474s