* Fix a crash in comparing with float (and maybe other crashes).
* They are now never equal to strings and non-integer numbers.
* Comparison with a large number no longer raises OverflowError.
* Arbitrary exceptions no longer silenced in constructors and comparisons.
* TypeError raised in the constructor contains now the name of the type.
* Accept only ChannelID and int-like objects in channel functions.
* Accept only InterpreterId, int-like objects and str in the InterpreterId constructor.
* Accept int-like objects, not just int in interpreter related functions.
https://bugs.python.org/issue34706
Specifically in the case of a class that does not override its
constructor signature inherited from object.
These are Buck Evan @bukzor's changes cherrypicked from GH-9344.
* Flip equality to use mock calls' __eq__
* bpo-37555: Regression test demonstrating assert_has_calls not working with ANY and spec_set
Co-authored-by: Neal Finne <neal@nealfinne.com>
* Revert "Flip equality to use mock calls' __eq__"
This reverts commit 94ddf54c5a.
* bpo-37555: Add regression tests for mock ANY ordering issues
Add regression tests for whether __eq__ is order agnostic on _Call and _CallList, which is useful for comparisons involving ANY, especially if the ANY comparison is to a class not defaulting __eq__ to NotImplemented.
Co-authored-by: Neal Finne <neal@nealfinne.com>
* bpo-37555: Fix _CallList and _Call order sensitivity
_Call and _CallList depend on ordering to correctly process that an object being compared to ANY with __eq__ should return True. This fix updates the comparison to check both a == b and b == a and return True if either condition is met, fixing situations from the tests in the previous two commits where assertEqual would not be commutative if checking _Call or _CallList objects. This seems like a reasonable fix considering that the Python data model specifies that if an object doesn't know how to compare itself to another object it should return NotImplemented, and that on getting NotImplemented from a == b, it should try b == a, implying that good behavior for __eq__ is commutative. This also flips the order of comparison in _CallList's __contains__ method, guaranteeing ANY will be on the left and have it's __eq__ called for equality checking, fixing the interaction between assert_has_calls and ANY.
Co-author: Neal Finne <neal@neal.finne.com>
* bpo-37555: Ensure _call_matcher returns _Call object
* Adding ACK and news entry
* bpo-37555: Replacing __eq__ with == to sidestep NotImplemented
bool(NotImplemented) returns True, so it's necessary to use ==
instead of __eq__ in this comparison.
* bpo-37555: cleaning up changes unnecessary to the final product
* bpo-37555: Fixed call on bound arguments to respect args and kwargs
* Revert "bpo-37555: Add regression tests for mock ANY ordering issues"
This reverts commit 49c5310ad4.
* Revert "bpo-37555: cleaning up changes unnecessary to the final product"
This reverts commit 18e964ba01.
* Revert "bpo-37555: Replacing __eq__ with == to sidestep NotImplemented"
This reverts commit f295eaca5b.
* Revert "bpo-37555: Fix _CallList and _Call order sensitivity"
This reverts commit 874fb697b8.
* Updated NEWS.d
* bpo-37555: Add tests checking every function using _call_matcher both with and without spec
* bpo-37555: Ensure all assert methods using _call_matcher are actually passing calls
* Remove AnyCompare and use call objects everywhere.
* Revert "Remove AnyCompare and use call objects everywhere."
This reverts commit 24973c0b32.
* Check for exception in assert_any_await
Handle time comparison for cookies with `expires` attribute when `CookieJar.make_cookies` is called.
Co-authored-by: Demian Brecht <demianbrecht@gmail.com>
https://bugs.python.org/issue12144
Automerge-Triggered-By: @asvetlov
- Migrate `Random_Type` to `PyType_FromSpec`
- To simulate an old use of `PyLong_Type.tp_as_number->nb_absolute`, I added
code to the module init function to stash `int.__abs__` for later
use. Ideally we'd use `PyType_GetSlot()` instead, but it doesn't currently
work for static types in CPython, and implementing it just for this case
doesn't seem worth it.
- Do exact check for long and dispatch to PyNumber_Absolute, use vector call when not exact.
The usedforsecurity keyword only argument added to the hash constructors is useful for FIPS builds and similar restrictive environment with non-technical requirements that legacy algorithms be forbidden by their implementations without being explicitly annotated as not being used for any security related purposes. Linux distros with FIPS support benefit from this being standard rather than making up their own way(s) to do it.
Contributed and Signed-off-by: Christian Heimes christian@python.org
* subprocess: Add user, group and extra_groups paremeters to subprocess.Popen
This adds a `user` parameter to the Popen constructor that will call
setreuid() in the child before calling exec(). This allows processes
running as root to safely drop privileges before running the subprocess
without having to use a preexec_fn.
This also adds a `group` parameter that will call setregid() in
the child process before calling exec().
Finally an `extra_groups` parameter was added that will call
setgroups() to set the supplimental groups.
* 1. add test case with wrong behavior
* 2. fix bug when max_length == -1
* 3. allow b"" as valid input data for decompress_buf()
* 4. when max_length >= 0, let needs_input mechanism works
* add more asserts to test case
* Add a note to the PyModule_AddObject docs.
* Correct example usages of PyModule_AddObject.
* Whitespace.
* Clean up wording.
* 📜🤖 Added by blurb_it.
* First code review.
* Add < 0 in the tests with PyModule_AddObject
Now the fields have names! Much easier to keep straight as a
reader than the elements of an 18-tuple.
Runs about 10-15% slower: from 10.8s to 12.3s, on my laptop.
Fortunately that's perfectly fine for this maintenance script.
* bits method and test_bits
* Cleaned up assert string
* blurb
* added docstring
* Faster method, per Eric Smith
* redoing as __format__
* added ipv6 method
* test cases and cleanup
* updated news
* cleanup and NEWS.d
* cleaned up old NEWS
* removed cut and paste leftover
* one more cleanup
* moved to regexp, moved away from v4- and v6-specific versions of __format__
* More cleanup, added ipv6 test cases
* more cleanup
* more cleanup
* cleanup
* cleanup
* cleanup per review, part 1
* addressed review comments around help string and regexp matching
* wrapped v6 test strings. contiguous integers: break at 72char. with underscores: break so that it looks clean.
* 's' and '' tests for pv4 and ipv6
* whitespace cleanup
* Remove trailing whitespace
* Remove more trailing whitespace
* Remove an excess blank line
The >=, checking whether a module index was in already in the module-by-index list, needed to be strict.
Also, fold nested ifs into one and fix some bad spacing.
Summary: This mostly migrates Python-ast.c to PEP384 and removes all statics from the whole file. This modifies the generator itself that generates the Python-ast.c. It leaves in the usage of _PyObject_LookupAttr even though it's not fully PEP384 compatible (this could always be shimmed in by anyone who needs it).
The socket module now has the socket.send_fds() and socket.recv.fds() functions.
Contributed by Joannah Nanjekye, Shinya Okano (original patch)
and Victor Stinner.
Co-Authored-By: Victor Stinner <vstinner@redhat.com>
* bpo-36260: Add pitfalls to zipfile module documentation
We saw vulnerability warning description (including zip bomb) in Doc/library/xml.rst file.
This gave us the idea of documentation improvement.
So, we moved a little bit forward :P
And the doc patch can be found (pr).
* fix trailing whitespace
* 📜🤖 Added by blurb_it.
* Reformat text for consistency.
Before, running deactivate from a bash shell configured to treat undefined variables as errors (`set -u`) would produce a warning:
```
$ python3 -m venv test
$ source test/bin/activate
(test) $ deactivate
-bash: $1: unbound variable
```
* bpo-37972: unittest.mock._Call now passes on __getitem__ to the __getattr__ chaining so that call() can be subscriptable
* 📜🤖 Added by blurb_it.
* Update 2019-08-28-21-40-12.bpo-37972.kP-n4L.rst
added name of the contributor
* bpo-37972: made all dunder methods chainable for _Call
* bpo-37972: delegate only attributes of tuple instead to __getattr__
* bpo-20504 : in cgi.py, fix bug when a multipart/form-data request has no content-length header
* Add Misc/NEWS.d/next file.
* Add rst formatting for NEWS.d/next file
* Reaplce assert by self.assertEqual
* bpo-35168: Documentation about shlex.punctuation_chars now states that it should be set in __init__.py
* bpo-35168: Convert shlex.punctuation_chars to read-only property
* Add NEWS.d entry
* Document `unittest.IsolatedAsyncioTestCase` API
* Add a simple example with respect to order of evaluation of setup and teardown calls.
https://bugs.python.org/issue32972
Automerge-Triggered-By: @asvetlov
bpo-37151: remove special case for PyCFunction from PyObject_Call
Alse, make the undocumented function PyCFunction_Call an alias
of PyObject_Call and deprecate it.
Relative imports use resolve_name to get the absolute target name,
which first seeks the current module's absolute package name from the globals:
If __package__ (and __spec__.parent) are missing then
import uses __name__, truncating the last segment if
the module is a submodule rather than a package __init__.py
(which it guesses from whether __path__ is defined).
The __name__ attempt should fail if there is no parent package (top level modules),
if __name__ is '__main__' (-m entry points), or both (scripts).
That is, if both __name__ has no subcomponents and the module does not seem
to be a package __init__ module then import should fail.
A root cause of bpo-37936 is that it's easy to write a .gitignore
rule that's intended to apply to a specific file (e.g., the
`pyconfig.h` generated by `./configure`) but actually applies to all
similarly-named files in the tree (e.g., `PC/pyconfig.h`.)
Specifically, any rule with no non-trailing slashes is applied in an
"unrooted" way, to files anywhere in the tree. This means that if we
write the rules in the most obvious-looking way, then
* for specific files we want to ignore that happen to be in
subdirectories (like `Modules/config.c`), the rule will work
as intended, staying "rooted" to the top of the tree; but
* when a specific file we want to ignore happens to be at the root of
the repo (like `platform`), then the obvious rule (`platform`) will
apply much more broadly than intended: if someone tries to add a
file or directory named `platform` somewhere else in the tree, it
will unexpectedly get ignored.
That's surprising behavior that can make the .gitignore file's
behavior feel finicky and unpredictable.
To avoid it, we can simply always give a rule "rooted" behavior when
that's what's intended, by systematically using leading slashes.
Further, to help make the pattern obvious when looking at the file and
minimize any need for thinking about the syntax when adding new rules:
separate the rules into one group for each type, with brief comments
identifying them.
For most of these rules it's clear whether they're meant to be rooted
or unrooted, but in a handful of cases I've only guessed. In that
case the safer default (the choice that won't hide information) is the
narrower, rooted meaning, with a leading slash. If for some of these
the unrooted meaning is desired after all, it'll be easy to move them
to the unrooted section at the top.
Fixes a possible hang when using a timeout on subprocess.run() while
capturing output. If the child process spawned its own children or otherwise
connected its stdout or stderr handles with another process, we could hang
after the timeout was reached and our child was killed when attempting to read
final output from the pipes.
This is a restructuring of the datetime documentation to hopefully make
them more user-friendly and approachable to new users without losing any
of the detail.
Changes include:
- Creating dedicated subsections for some concepts such as:
- "Constants"
- "Naive vs Aware"
- "Determining if an Object is Aware"
- Give 'naive vs aware' its own subsection
- Give 'constants' their own subsection
- Overhauling the strftime-strptime section by:
- Breaking it into logical, linkable, and digestable parts
- Adding a high-level comparison table
- Moving the technical detail to bottom: readers come to this
section primarily to remind themselves to things:
- How do I write the format code for X?
- strptime/strftime: which one is which again?
- Touching up fromisoformat + isoformat sections by:
- Revising fromisoformat + isoformat for date, time, and
datetime
- Adding basic examples
- Enforcing consistency about putting formats (i.e. ``HH:MM``)
in double backticks. This was previously done in some places
but not all
- Putting long 'supported formats', on their own line to improve
readability
- Moving the 'seealso' section to the top and add a link to dateutil
Rationale: This doesn't really belong nested under the
'constants' section. Let readers know right away that
datetime is one of several related tools.
- Moving common features of several types into one place:
Previously, each type went out of its way to note separately
that it was hashable and picklable. These can be brought
into one single place that is more prominent.
- Reducing some verbose explanations to improve readability
- Breaking up long paragraphs into digestable chunks
- Displaying longer "equivalent to" examples, as short code blocks
- Using the dot notation for datetime/time classes:
Use :class:`.time` and :class:`.datetime` rather than :class:`time` and
:class:`datetime`; otherwise, the generated links will route to the
respective modules, not classes.
- Rewording the tzinfo class description
The top paragraph should get straight to the point of telling the reader
what subclasses of tzinfo _do_. Previously, that was hidden in a later
paragraph.
- Adding a note on .today() versus .now()
- Rearranging and expanding example blocks, including:
- Moved long, multiline inline examples to standalone examples
- Simplified the example block for timedelta arithmetic:
- Broke the example into two logical sections:
1. normalization/parameter 'merging'
2. timedelta arithmetic
- Reduced the complexity of the some of the examples. Show
reasonable, real-world uses cases that are easy to follow
along with and progres in difficult slightly.
- Broke up the example sections for date and datetime sections by putting
the easy examples first, progressing to more esoteric situations and
breaking it up into logical sections based on what the methods are
doing at a high level.
- Simplified the KabulTz example:
- Put the class definition itself into a non-REPL block since there is
no interactive output involved there
- Briefly explained what's happening before launching into the code
- Broke the example section into visually separate chunks
- Various whitespace, formatting, style and grammar fixes including:
- Consistently using backctics for 'date_string' formats
- Consistently using one space after periods.
- Consistently using bold for vocab terms
- Consistently using italics when referring to params:
See https://devguide.python.org/documenting/#id4
- Using '::' to lead into code blocks
Per https://devguide.python.org/documenting/#source-code, this will
let the reader use the 'expand/collapse' top-right button for REPL
blocks to hide or show the prompt.
- Using consistent captialization schemes
- Removing use of the default role
- Put 'example' blocks in Markdown subsections
This is a combination of 66 commits.
See bpo-36960: https://bugs.python.org/issue36960
The instance destructor for a type is responsible for preparing
an instance for deallocation by decrementing the reference counts
of its referents.
If an instance belongs to a heap type, the type object of an instance
has its reference count decremented while for static types, which
are permanently allocated, the type object is unaffected by the
instance destructor.
Previously, the default instance destructor searched the class
hierarchy for an inherited instance destructor and, if present,
would invoke it.
Then, if the instance type is a heap type, it would decrement the
reference count of that heap type. However, this could result in the
premature destruction of a type because the inherited instance
destructor should have already decremented the reference count
of the type object.
This change avoids the premature destruction of the type object
by suppressing the decrement of its reference count when an
inherited, non-default instance destructor has been invoked.
Finally, an assertion on the Py_SIZE of a type was deleted. Heap
types have a non zero size, making this into an incorrect assertion.
https://github.com/python/cpython/pull/15323
Summary:
Eliminate uses of `_Py_IDENTIFIER` from `_posixsubprocess`, replacing them with interned strings.
Also tries to find an existing version of the module, which will allow subinterpreters.
https://bugs.python.org/issue38069
* PEP-384 _struct
* More PEP-384 fixes for _struct
Summary: Add a couple of more fixes for `_struct` that were previously missed such as removing `tp_*` accessors and using `PyBytesWriter` instead of calling `PyBytes_FromStringAndSize` with `NULL`. Also added a test to confirm that `iter_unpack` type is still uninstantiable.
* 📜🤖 Added by blurb_it.
Change "clean" makefile target to also clean the program guided
optimization (PGO) data. Previously you would have to use "make
clean" and "make profile-removal", or "make clobber".
weakref.WeakValueDictionary defines a local remove() function used as
callback for weak references. This function was created with a
closure. Modify the implementation to avoid the closure.
This is the converse of GH-15353 -- in addition to plenty of
scripts in the tree that are marked with the executable bit
(and so can be directly executed), there are a few that have
a leading `#!` which could let them be executed, but it doesn't
do anything because they don't have the executable bit set.
Here's a command which finds such files and marks them. The
first line finds files in the tree with a `#!` line *anywhere*;
the next-to-last step checks that the *first* line is actually of
that form. In between we filter out files that already have the
bit set, and some files that are meant as fragments to be
consumed by one or another kind of preprocessor.
$ git grep -l '^#!' \
| grep -vxFf <( \
git ls-files --stage \
| perl -lane 'print $F[3] if (!/^100644/)' \
) \
| grep -ve '\.in$' -e '^Doc/includes/' \
| while read f; do
head -c2 "$f" | grep -qxF '#!' \
&& chmod a+x "$f"; \
done