-
-
Notifications
You must be signed in to change notification settings - Fork 30k
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
Add global instances of int 0 and 1 #74064
Comments
When C code needs to compare Python object with int 0 or add int 1 it either use local reference to PyLong_FromLong(0) and PyLong_FromLong(1) which should be decrefed just after use or module level global variable initialized and cleared during initializing and finalizing the module. Proposed patch adds global variables _PyLong_Zero and _PyLong_One for references to integer objects 0 and 1. This simplifies the code since no need to initialize local variables, check for error the result of PyLong_FromLong() and decref it after use. The patch decreases the total code size by 244 lines. That variables are only for internal use. User code should use PyLong_FromLong(0) and PyLong_FromLong(1). |
I like it. |
+1. Please create a PR for it. |
+1 for this idea. Also consider adding new function PyLong_Increment. This basic operation is small pain using the current API. It may also give a small speed benefit. |
Other common values used in C functions: empty byte string, empty Unicode string, empty tuple. The problem is to make sure that singletons are created in the right order :-/ This issue reminded me an old idea of writing a generalization of the _Py_IDENTIFIER() API. I created an issue bpo-29881: Add a new private API for "static C variables" (_PyStaticVar) to clear them at exit. To be clear: it's related but different to this issue, the two issues are exclusive. |
Yet one idea that can make the code simpler is make PyLong_FromLong(0) and PyLong_FromLong(1) never failing. I.e. require NSMALLPOSINTS not less than 2.
Smaller pain with using _PyLong_One and Py_SETREF(). Py_SETREF(long_obj, PyNumber_Add(long_obj, _PyLong_One)); Agree that with _PyLong_Increment() it can look better and be faster. But I don't know whether incrementing by 1 is enough popular operation. I have counted 5 cases in the stdlib (not counting tests): for enumerate, range and Counter.
Yes, I spent much time for making empty Unicode string singleton always be initialized. It can be accessed at very early stage. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: