-
-
Notifications
You must be signed in to change notification settings - Fork 31.8k
re.sub appears not to check count optional argument for integerness #73091
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
Comments
This comes from diagnosing a beginner's question on Python-tutor. https://mail.python.org/pipermail/tutor/2016-December/110066.html It appears that re.sub is not checking whether the count argument is integer or not, and silently accepts a nonsensical argument. For example: >>> import re
>>> s = "AAAcBBB\nAAAdBBB"
>>> print(re.sub(r'^AAA', "aaa", s, re.MULTILINE))
aaacBBB
AAAdBBB Of course, the user intended to pass re.MULTILINE to flags, not to count, but the fact that this isn't raising a TypeError is error-prone. |
Ugh. I suddenly realize that this is complicated by the fact that flag values are themselves represented as integers, and Python's type system isn't rich enough to label flag values as a distinct type for the purposes. It may be worthwhile to add a warning in the documentation about this, as it is an easy mistake to make. |
Alternatively, change the representation of flag values from integers to some class extension that supports the common bitwise operators. As a very rough sketch: >>> class FlagInt(int):
... def __or__(self, other):
... return FlagInt(int(self) | int(other))
...
>>> f1 = FlagInt(1)
>>> f2 = FlagInt(2)
>>> f1 | f2
3
>>> isinstance(3, FlagInt)
False
>>> isinstance(f1 | f2, FlagInt)
True That way, flag arguments can be determined at runtime to have derived from the proper flag values. This kind of approach may have some backwards-incompatibility, unfortunately, since other folks have been hardcoding integers rather than use the flag constants. Other concerns might include serialization, in case someone tries to save a FlagInt somewhere and pull it out at some other time. |
See bpo-28082. |
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: