Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ENH] Replacing bytes(...) with PyBytes_FromObject #6504

Open
jakirkham opened this issue Nov 15, 2024 · 1 comment
Open

[ENH] Replacing bytes(...) with PyBytes_FromObject #6504

jakirkham opened this issue Nov 15, 2024 · 1 comment

Comments

@jakirkham
Copy link
Contributor

jakirkham commented Nov 15, 2024

Is your feature request related to a problem? Please describe.

When writing code like this...

cpdef bytes tobytes(o):
    return bytes(o)

Cython generates code like this

...
  __pyx_t_1 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyBytes_Type)), __pyx_v_o); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 4, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
...

Compare this to

cpdef str tostr(o):
    return str(o)

...which Cython does optimize to use PyObject_Str with the following

...
  __pyx_t_1 = __Pyx_PyObject_Unicode(__pyx_v_o); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 4, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
...

Describe the solution you'd like.

Ideally the same optimization would be extended to bytes(...)

Describe alternatives you've considered.

No response

Additional context

No response

@da-woods
Copy link
Contributor

Looking at the implementation of bytes.__new__, there's some special-casing for anything with a __bytes__ method and some special-casing for ints. So I'm not sure it's really equivalent in a lot of cases.

Obviously we could reimplement some of that, and/or do some substitutions for known types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants