Sitelet https://github.com/python/cpython/issues/93741
Skip to content

Add C API for importing an attribute from a module #93741

Description

@serhiy-storchaka

It is common (more than 30 cases) in the C code to access a function or a variable from other module. For example:

    functools = PyImport_ImportModule("functools");
    if (!functools)
        goto error;
    st->partial = PyObject_GetAttrString(functools, "partial");
    Py_CLEAR(functools);

I propose to add a private helper function which combines PyImport_ImportModule() and PyObject_GetAttrString().

    st->partial = _PyImport_GetModuleAttrString("functools", "partial");

It will save 4-6 lines of code and a variable on every use.

Activity

  1. added a commit that references this issue on Jun 12, 2022
  2. kumaraditya303 commented on Jun 13, 2022

    @kumaraditya303
    Contributor

    Since this will be private API, how about using statically allocated string identifiers to avoid memory allocations?

  3. serhiy-storchaka commented on Jun 13, 2022

    @serhiy-storchaka
    MemberAuthor

    The PR adds also function _PyImport_GetModuleAttr() which takes PyObject* arguments. You can use it with statically allocated string identifiers.

  4. added 5 commits that reference this issue on Jun 14, 2022
  5. added 2 commits that reference this issue on Jun 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions