Commit graph

2686 commits

Author SHA1 Message Date
Adam Reichold c1f4db0a9b Increase use of common get_or_try_init_type_ref helper when caching type objects. 2023-12-21 11:33:25 +01:00
Adam Reichold 7f626b26d4
Merge pull request #3678 from davidhewitt/mapping2
implement `PyMappingMethods`
2023-12-21 09:47:35 +00:00
David Hewitt 43827e39ee
Merge pull request #3677 from davidhewitt/string2
implement `PyStringMethods`
2023-12-20 22:04:23 +00:00
David Hewitt f4f3169cad implement PyStringMethods 2023-12-20 16:19:18 +00:00
David Hewitt 8bd2972201
Merge pull request #3675 from davidhewitt/dict2-try2
implement `PyDictMethods`
2023-12-20 14:59:15 +00:00
David Hewitt 8e7c90733d implement PyMappingMethods 2023-12-20 14:39:40 +00:00
David Hewitt 15d309eb1f implement PyDictMethods 2023-12-20 14:18:45 +00:00
Adam Reichold fd2fc983b1
Merge pull request #3676 from davidhewitt/any-iter
tidy up some Py2 <-> gil-ref conversions
2023-12-20 13:31:15 +00:00
Adam Reichold 1b3dc6d7ac
Merge pull request #3661 from PyO3/iter-output-type
Replace (A)IterNextOutput by autoref-based specialization to allow returning arbitrary value
2023-12-20 12:53:42 +00:00
David Hewitt 5181e35a61 tidy up some Py2 <-> gil-ref conversions 2023-12-20 12:50:15 +00:00
Adam Reichold 5528895f3e Relax the error type in the Result<Option<T>, E>> specializations for __(a)next__. 2023-12-20 13:12:16 +01:00
David Hewitt bc87b7bac6 deprecate PyTryFrom and PyTryInto 2023-12-20 11:28:24 +00:00
Adam Reichold 83697f0c62 Also replace IterANextOutput by autoref-based specialization to allow returning arbitrary values 2023-12-20 09:56:16 +01:00
Adam Reichold ca7d90dcf3 Replace IterNextOutput by autoref-based specialization to allow returning arbitrary values 2023-12-20 09:56:16 +01:00
Tpt 0752942c3f Duration: drops truncation warning 2023-12-20 08:57:26 +01:00
Tpt 8b614745cf Adds std::duration::Duration from/to Python conversions 2023-12-20 08:57:26 +01:00
Adam Reichold ee54132ff6
Merge pull request #3671 from davidhewitt/dh/downcast-error-split
Add `Py2` variants of `PyDowncastError`
2023-12-19 21:31:38 +00:00
David Hewitt 1451418ee4 Add Py2 variants of PyDowncastError 2023-12-19 20:59:57 +00:00
David Hewitt 54ba6e82ca
Merge pull request #3651 from davidhewitt/bytes2
implement `PyBytesMethods` and `PyByteArrayMethods`
2023-12-19 19:56:16 +00:00
David Hewitt 35f7f1a78c use Py2Borrowed to make PyBytesMethods slightly nicer 2023-12-19 19:02:23 +00:00
Adam Reichold 8bb64377b8
Merge pull request #3638 from PyO3/call-op-bool
Try harder by looking for a __bool__ magic method when extracing bool values from Python objects.
2023-12-19 18:52:55 +00:00
Adam Reichold 4177dfcc81 Apply __bool__ conversion only to numpy.bool_ to avoid false positives. 2023-12-19 18:55:28 +01:00
Adam Reichold 57002d2389 Align error message when no method __bool__ is defined with CPython's general style. 2023-12-19 18:55:28 +01:00
Adam Reichold 3e10d64fa2 Avoid attribute lookup overhead for __bool__ if the unlimited API is available. 2023-12-19 18:55:28 +01:00
Adam Reichold 8133aaa5d8 Try harder by looking for a __bool__ magic method when extracing bool values from Python objects.
I decided to not implement the full protocol for truth value testing [1] as it
seems confusing in the context of function arguments if basically any instance
of custom class or non-empty collection turns into `true`.

[1] https://docs.python.org/3/library/stdtypes.html#truth
2023-12-19 18:55:28 +01:00
David Hewitt e727640ef3
Merge pull request #3664 from Tpt/chrono-abi3
Chrono: compatibility with abi3
2023-12-19 17:53:30 +00:00
David Hewitt c5dce0172b implement PyBytesMethods and PyByteArrayMethods 2023-12-19 17:26:52 +00:00
Adam Reichold 68f417fb1c Defend against mutable type objects when extracting their full name. 2023-12-19 16:51:24 +01:00
Adam Reichold 416d3c488f Rename name to qualname and full_name to name to better match Python 2023-12-19 16:51:24 +01:00
Adam Reichold 2fdd52003e Add PyType::full_name which is tp_name and has an abi3 fallback. 2023-12-19 15:47:21 +01:00
Tpt d7eac6527b Chrono: compatibility with abi3 2023-12-19 14:53:14 +01:00
David Hewitt 1dca87972a
Merge pull request #3662 from Tpt/chrono-test
Chrono: makes test independent of datetime C-API
2023-12-19 08:26:21 +00:00
Tpt 0d2387e858 Chrono: makes FromPyObject impl on DateTime generic
ToPyObject was already generic
2023-12-18 20:12:30 +01:00
Tpt 7705181049 Chrono: makes test independent of datetime C-API 2023-12-18 17:12:39 +01:00
Adam Reichold ced97f80d1 Transition is_true to is_truthy to clarify that the test is not based on identity with or equality to the True singleton. 2023-12-16 14:04:37 +01:00
David Hewitt 867a273afc
Merge pull request #3648 from Tpt/timezone-constructor
Adds internal timezone_from_offset function
2023-12-15 16:12:32 +00:00
Tpt dcaed199c7 Adds internal timezone_from_offset function
It allows to build conversions from chrono without direct access to the C API
2023-12-15 17:00:25 +01:00
David Hewitt d7adc74ba5 implement PyBoolMethods 2023-12-15 14:39:04 +00:00
David Hewitt 97cf9b834c
Merge pull request #3653 from davidhewitt/native-type-source
Add `AsRefSource` to `PyNativeType`.
2023-12-14 22:33:49 +00:00
David Hewitt ef8532b175 Add AsRefSource to PyNativeType. 2023-12-14 18:35:06 +00:00
Adam Reichold d1b4b9e7d4
Merge pull request #3650 from davidhewitt/float2
implement `PyFloatMethods`
2023-12-14 18:07:32 +00:00
David Hewitt 8a7c5002bd rename floatob.rs to float.rs 2023-12-14 17:14:17 +00:00
David Hewitt 8bdae345f3 implement PyFloatMethods 2023-12-14 17:12:06 +00:00
David Hewitt 015f028589 hold onto module name properly in PyCFunction::internal_new 2023-12-14 16:23:53 +00:00
David Hewitt 82ac801be4 introduce traits to make ffi ptr handling cleaner 2023-12-14 13:00:45 +00:00
David Hewitt ac4ee2841b implement PySequenceMethods 2023-12-14 13:00:45 +00:00
messense c21a84d999
Add support for extracting Rust set types from frozenset 2023-12-07 20:25:31 +08:00
David Hewitt 07726aefc4
Merge pull request #3609 from wyfo/async_receiver
feat: allow async methods to accept `&self`/`&mut self`
2023-12-07 07:38:25 +00:00
Joseph Perez f34c70c2da
feat: allow async methods to accept &self/&mut self 2023-12-07 07:42:10 +01:00
Adam Reichold 4baf0235c3
Merge pull request #3616 from neachdainn/3615-gilprotected-pyvisit
Enable `GILProtected` access via `PyVisit`
2023-12-05 20:43:38 +00:00
Nathan Kent 3249feb85c
Enable GILProtected access via PyVisit
Closes #3615

This simply adds a new method which uses the existence of a `PyVisit`
object as proof that the GIL is held instead of a `Python` object. This
allows `GILProtected` to be used in instances where contained Python
objects need to participate in garbage collection. Usage in this
situation should be valid since no Python calls are made and this does
not provide any additional mechanism for accessing a `Python` object.
2023-12-05 11:10:00 -08:00
David Hewitt ed87637ebb replace PyTryFrom by splitting PyTypeInfo 2023-12-05 08:01:30 +03:00
David Hewitt 16ae0e2efe
Merge pull request #3608 from wyfo/remove_futures
refactor: drop futures_util dependency
2023-12-04 19:17:43 +00:00
Joseph Perez 2ca9f59d6f
refactor: drop futures_util dependency 2023-12-04 18:56:34 +01:00
David Hewitt e8f852bce7
Merge pull request #3599 from wyfo/coroutine_cancel
feat: add `coroutine::CancelHandle`
2023-12-04 12:44:36 +00:00
Joseph Perez 8a674c2bd3
feat: add coroutine::CancelHandle 2023-12-04 07:46:51 +01:00
Adam Reichold e6457c5e99 Use portable-atomic for targets which lack 64-bit atomics used to check interpreter ID.
I chose to make the dependency mandatory instead of optional as portable-atomic
itself just forwards to the native atomics when they are available so making
that choice part of our build system is not really necessary. Personally, I was
unable to perceive any noticeable compile-time hit from adding it.
2023-12-02 07:57:00 +01:00
Alex Gaynor dd6e0339d3 Refactor create_type_object so that most of the code is monomorphic
In pyca/cryptography this function is the #1 source of lines of generated LLVM IR, because it is duplicated 42x (and growing!). By rewriting it so most of the logic is monomorphic, we reduce the generated LLVM IR for this function by 4x.
2023-11-28 20:09:34 -05:00
David Hewitt 5c6d49084f remove all functionality deprecated in 0.19 2023-11-27 22:02:19 +00:00
David Hewitt d8002c4b2b
Merge pull request #3588 from wyfo/coroutine_name
feat: add coroutine `__name__`/`__qualname__`
2023-11-26 09:23:29 +00:00
Joseph Perez 781b9e3983
feat: add coroutine __name__/__qualname__ and not-awaited warning 2023-11-25 21:51:20 +01:00
Adam Reichold 1203921d5c
Merge pull request #3456 from aldanor/feature/either
Add conversion support for `either::Either`
2023-11-25 09:37:49 +00:00
Adam Reichold 81bc838acd
Merge pull request #3577 from davidhewitt/none-typeinfo
Implement `PyTypeInfo` for `PyEllipsis`, `PyNone`, and `PyNotImplemented`
2023-11-25 09:36:43 +00:00
David Hewitt 9f66846238
Merge pull request #3595 from davidhewitt/ok-wrap
refactor `OkWrap` to not call `.into_py(py)`
2023-11-25 05:43:54 +00:00
David Hewitt cd8526ecc6 Implement PyTypeInfo for PyEllipsis, PyNone, and PyNotImplemented 2023-11-24 22:31:39 +00:00
David Hewitt bead83f4b0 docs: fixup docs for smallvec feature 2023-11-24 22:11:40 +00:00
Ivan Smirnov a75464ee26 add conversion support for either::Either 2023-11-24 22:09:34 +00:00
David Hewitt c814078866 refactor OkWrap to not call .into_py(py) 2023-11-24 10:41:08 +00:00
Joseph Perez 627841f1e2
feat: support async fn in macros with coroutine implementation 2023-11-22 20:25:36 +01:00
David Hewitt 7b07d6d21b
Merge pull request #3578 from davidhewitt/typed-helpers
Change return types of `py.None()`, `py.NotImplemented()` and `py.Ellipsis()` to typed singletons
2023-11-20 07:07:12 +00:00
David Hewitt bd0174aa5d Change return types of py.None(), py.NotImplemented() and py.Ellipsis() to typed singletons 2023-11-17 16:16:19 +00:00
David Hewitt a9305ab389 ci: move lints to new 1.74 cargo.toml tables 2023-11-17 15:41:52 +00:00
Joseph Perez 1fd4090bd4 refactor: remove useless unsafe in get_mut 2023-10-29 13:50:36 +01:00
Joseph Perez bb1cc93797 feat: add take and into_inner methods to GILOnceCell 2023-10-29 08:33:04 +01:00
David Hewitt 572a27d2d3 ci: fix nightly unused import warnings 2023-10-25 23:30:14 +01:00
David Hewitt d895734499 change PyDict::from_sequence to take just &PyAny 2023-10-20 11:59:26 +01:00
David Hewitt 2ca8e573a4 remove comparison to rust-cpython 2023-10-15 22:03:24 +01:00
David Hewitt f12f928bd5
Merge pull request #3514 from messense/memoryview
Add `PyMemoryView` type
2023-10-15 15:08:50 +00:00
David Hewitt aa28cec893
Merge pull request #3507 from orhun/feat/support_smallvec_conversion
Add support for `SmallVec` in conversion traits (#3440)
2023-10-15 14:43:55 +00:00
messense f4e64aadef
Add test cases for new TryFrom impls 2023-10-15 21:53:31 +08:00
messense d4ed66fff0
Add TryFrom impls for PyByteArray and PyMemoryView 2023-10-15 17:39:01 +08:00
messense 5b94241bd7
Add PyMemoryView type 2023-10-15 17:32:09 +08:00
Orhun Parmaksız 31acf0dc6f
Add an entry to features table in lib 2023-10-13 13:35:30 +03:00
David Hewitt cac95f31c7 add Py2 as an internal API for optimization and dogfooding 2023-10-13 08:10:37 +02:00
Orhun Parmaksız dfeae473e5
Add support for SmallVec in conversion traits (#3440) 2023-10-11 17:14:23 +03:00
David Hewitt e1d4173827 Fix bug in default implementation of __ne__ 2023-10-11 09:48:06 +01:00
David Hewitt 76bf521ed0
Merge pull request #3505 from davidhewitt/deprecate_dunder_new
deprecate undocumented `#[__new__]` form of `#[new]`
2023-10-10 21:35:10 +00:00
David Hewitt 6c90325a1c deprecate undocumented #[__new__] form of #[new] 2023-10-10 08:47:03 +01:00
David Hewitt c0b5004cfa
Merge pull request #3455 from davidhewitt/normalized-exceptions
also use `PyErr::SetObject` on Python versions before 3.12
2023-10-10 07:44:39 +00:00
mejrs 6ca573b9d0 Update clippy 2023-10-06 23:31:06 +02:00
David Hewitt 2daddb4734 unify 3.12 and pre-3.12 exception handling pathways 2023-09-30 23:27:27 +01:00
David Hewitt f335f42197
Merge pull request #3446 from davidhewitt/relax-import-check
relax multiple-import check to only prevent subinterpreters
2023-09-29 16:35:31 +00:00
David Hewitt b9e9859082
Merge pull request #3478 from mejrs/auto
Don't let auto trait syntax bleed through on stable Rust
2023-09-29 16:35:05 +00:00
mejrs 0c8ab98760 move it into the inline module. 2023-09-29 17:22:27 +02:00
David Hewitt 1a349c2eb7 adjust cfgs for windows 3.9 2023-09-29 14:23:18 +01:00
David Hewitt 50cb41dd0b
Merge pull request #3458 from davidhewitt/truncate-leap-seconds
truncate leap seconds on `chrono` to `datetime` conversions
2023-09-29 11:47:27 +00:00
David Hewitt 4b5ff05721
Merge pull request #3471 from davidhewitt/normalized-exceptions-2
always normalize exceptions before raising
2023-09-28 20:27:18 +00:00
mejrs d0d4b9d3fb Dont let auto trait syntax bleed through on stable 2023-09-28 12:26:09 +02:00
David Hewitt 0459532f69 truncate leap seconds on chrono to datetime conversions 2023-09-24 20:28:43 +01:00
David Hewitt 673c45aac3
Merge pull request #3470 from davidhewitt/tests-capture-warnings
add `assert_warnings` test helper
2023-09-24 13:09:01 +00:00
David Hewitt 1e8833e15e always normalize exceptions before raising 2023-09-24 13:38:23 +01:00
David Hewitt 7d486bb72a tests/common.rs -> src/tests/common.rs 2023-09-24 13:34:53 +01:00
David Hewitt 42f9cd4476
Merge pull request #3469 from davidhewitt/chrono-tidy-up
refactor chrono implementation to be more DRY
2023-09-24 09:32:43 +00:00
David Hewitt f691a68b46
Merge pull request #3472 from davidhewitt/normalized-exceptions-3
unify 3.12 / non-3.12 error handling branches
2023-09-23 21:45:25 +00:00
David Hewitt d089c92680 unify 3.12 / non-3.12 error handling branches 2023-09-23 22:18:59 +01:00
David Hewitt 97ee5967e0 increase test coverage of chrono feature 2023-09-23 13:51:38 +01:00
David Hewitt 20378a607b
Merge pull request #3466 from davidhewitt/docs-only-prs
docs: skip changelog check for docs-only PRs
2023-09-23 12:26:37 +00:00
David Hewitt c8f82be32c add assert_warnings test helper 2023-09-23 13:14:18 +01:00
David Hewitt ccc22a905d allow invalid_from_utf8 lint in tests 2023-09-23 12:54:53 +01:00
David Hewitt 2d61a73b02 refactor chrono implementation to be more DRY 2023-09-23 12:46:45 +01:00
David Hewitt f17e703167 return existing module on Python 3.9 and up 2023-09-23 11:13:39 +01:00
David Hewitt 1338020511 relax multiple-import check to only prevent subinterpreters 2023-09-23 11:13:39 +01:00
David Hewitt 5798caf1f8 better Some-wrapping for default arguments 2023-09-21 21:14:44 +01:00
David Hewitt 1ec3c5a4fd ci: adjust tests to avoid chrono panics 2023-09-21 08:34:45 +01:00
David Hewitt bcb01049cc
Merge pull request #3404 from davidhewitt/fix-dealloc
call PyObject_GC_Untrack before deallocating
2023-09-11 05:18:34 +00:00
David Hewitt 932c5c7061 workaround BaseException issue on Python versions before 3.11 2023-09-10 22:16:17 +02:00
David Hewitt e28403e772 call PyObject_GC_Untrack before deallocating 2023-09-09 22:29:58 +01:00
David Hewitt 8ddfef04bc add detail to documentation for PyDict::get_item 2023-09-09 12:23:06 +01:00
David Hewitt 8a60540e25 amend code for PyDict::get_item change 2023-09-09 12:23:06 +01:00
David Hewitt 16728c4da2 move PyDict::get_item_with_error to PyDict::get_item 2023-09-09 12:23:06 +01:00
David Hewitt f0f15edc4e remove some redundant explicit doc links 2023-09-08 15:36:24 +01:00
David Hewitt e67b283b25
Merge pull request #3358 from alex/ptr-unsafe-trait
fixes #3325 -- mark `AsPyPointer` as `unsafe trait`
2023-09-04 05:05:56 +00:00
David Hewitt 4c46d81afd simplify thread checker implementation 2023-09-03 14:15:26 +01:00
David Hewitt 9e089a5538 fix chrono deprecation warnings 2023-09-02 20:55:53 +01:00
Ryan Lowe b3cf61cea6 add types for built-in singletons 2023-08-26 08:57:34 -04:00
David Hewitt a5d0a16b21 ci: updates for Rust 1.72 2023-08-25 12:30:34 +01:00
Adam Reichold 12183ad3ed
Merge pull request #3379 from iliya-malecki/main
BigInt speedup
2023-08-19 12:09:28 +00:00
David Hewitt 9604957c72 further refactor num-bigint conversion 2023-08-18 22:27:47 +01:00
Adam Reichold 94f15679ab
Merge pull request #3402 from Tpt/io-err-unwrap
Unwrap the underlying PyErr when converting an io::Error back to a PyErr
2023-08-18 16:56:53 +00:00
David Hewitt 15388fd53b
Merge pull request #3401 from messense/fix-issue-3400
Fix memory leak in `PyTypeBuilder::build`
2023-08-18 14:28:36 +00:00
Alex Gaynor df5aa77800
fixes #3325 -- mark AsPyPointer as unsafe trait 2023-08-18 10:16:34 -04:00
Tpt 6d8e8b302f Unwrap the underlying PyErr when converting an io::Error back to a PyErr
Exposes it directly instead of loosing all information outside the message
2023-08-18 15:56:25 +02:00
messense 2dc1e9a2b7
Fix memory leak in PyTypeBuilder::build 2023-08-18 21:13:13 +08:00
David Hewitt c03c787a91
Merge pull request #3393 from alex/drop-other-trait
Remove usage of `AsPyPointer` in `IntoPy<PyObject>` trait implementation
2023-08-18 12:58:07 +00:00
David Hewitt 7f32ed96db
Merge pull request #3396 from Tpt/IntoInnerError
Uses io::Error code when converting io::IntoInnerError to PyErr
2023-08-18 08:27:35 +00:00
Tpt 1062f244ea Pick a relevant ErrorKind when building an io::Error from a OSError subclass 2023-08-17 18:33:51 +02:00
Tpt 7c366cb930 Uses io::Error code when converting io::IntoInnerError to PyErr 2023-08-17 18:25:36 +02:00
Alex Gaynor 9f1b56b659
Remove usage of AsPyPointer in IntoPy<PyObject> trait implementation 2023-08-17 07:05:52 -04:00
Iliya Malecki d1f0561036 added speedy BigInt extraction 2023-08-17 08:15:50 +01:00
Alex Gaynor c259e77ca2
Remove usage of AsPyPointer in traits for convergint to PyObject
Refs #3358
2023-08-16 07:03:57 -04:00
Alex Gaynor 1a904a7429
Migrate PyIterator::from_object and PyByteArray::from from AsPyPointer to &PyAny 2023-08-15 18:03:56 -04:00
Alex Gaynor 5061b501a9
Remove IntoPyPointer
it wasn't used in any public APIs following #3359
2023-08-14 16:28:20 -04:00
David Hewitt a541925f00
Merge pull request #3359 from davidhewitt/py-pointer-methods
add as_ptr and into_ptr inherent methods
2023-08-11 19:50:22 +00:00
David Hewitt 8031794f2a
Merge pull request #3378 from GoldsteinE/implicit-builtins
add `__builtins__` to globals in `py.run()` if they're missing
2023-08-11 14:11:31 +00:00
Goldstein 0be94a5442
add __builtins__ to globals in py.run() if they're missing
Python code doesn't like to run without `__builtins__`, so adding them
if missing seems to be a good idea. Also that's what CPython >3.10 does.

See https://github.com/python/cpython/pull/24564
Resolves #3370
2023-08-11 15:48:05 +03:00
David Hewitt 64adab1a76 add as_ptr and into_ptr inherent methods 2023-08-11 10:49:42 +01:00
Tpt 1e5a49557d Makes PathBuf FromPyObject implementation work on all os.PathLike
PyOS_FSPath is in abi3-py36
2023-08-08 22:15:56 +02:00
Adam Reichold a371fbe4f8 Implement DoubleEndedIterator for PyListIterator by caching the length while still validating it before access. 2023-08-07 21:37:50 +02:00
Adam Reichold 4ce3e9649f Implement DoubleEndedIterator for PyTupleIterator 2023-08-07 21:37:50 +02:00
David Hewitt ef43731993 update tests of refcounting to use a non-immortal object 2023-07-30 15:37:06 +01:00
David Hewitt 4e957e8bd4 update object.h definitions for Python 3.12 2023-07-30 15:37:06 +01:00
Juniper Tyree 16fe7a83a7 Add a PySlice::full() constructor for :: 2023-07-29 07:39:47 +00:00
David Hewitt e2c88d5a4e optimize float -> f64 conversions on non-abi3 2023-07-28 20:45:37 +01:00
David Hewitt 34881fc952 add PyAny::downcast_exact 2023-07-28 15:11:56 +01:00
David Hewitt a15614844d add PyErr::display 2023-07-24 22:14:55 +01:00
David Hewitt ab078258d1 fix exception handling on Python 3.12 2023-07-19 22:33:25 +01:00
Zak Stucke f2b7e86e2e Prevent traceback loss on conversion to and from PyErr 2023-07-19 12:07:41 +03:00
David Hewitt 2e2dde910a Preserve panic message after exception is normalized 2023-07-18 22:20:41 +01:00
David Hewitt 421e13a89c
Merge pull request #3323 from davidhewitt/pyerr-simplification
merge PyErr internal states for simplicity
2023-07-17 21:46:39 +00:00
David Hewitt 2d1b8e02a8 merge PyErr internal states for simplicity 2023-07-17 22:21:28 +01:00
David Hewitt e5a7400f24
Merge pull request #3319 from davidhewitt/used-underscore-binding
clippy: deny / fix used-underscope-binding lint
2023-07-16 20:53:56 +00:00
David Hewitt 45ff25cd2a clippy: deny / fix used-underscope-binding lint 2023-07-16 20:49:45 +01:00
David Hewitt 6f30215566 collect arrays of objects prior to filling tuple in fixed-size conversions 2023-07-16 20:17:02 +01:00
Adam Reichold 65312b43b2
Merge pull request #3312 from davidhewitt/opt-baseexception
optimize is_instance for PyBaseException
2023-07-14 16:37:24 +00:00
David Hewitt f39dd52cf9 remove concept of "normalize" from PyErr docs 2023-07-14 13:20:48 +01:00
David Hewitt 92b724f64f normalize exception in PyErr::matches and PyErr::get_type 2023-07-14 13:18:30 +01:00
David Hewitt b65cbb958b ci: updates for rust 1.71 2023-07-14 12:10:37 +01:00
David Hewitt 272997555e optimize is_instance for PyBaseException 2023-07-11 21:48:46 +01:00
Adam Reichold ff78b92e77 Start adding a performance section to the guide. 2023-07-09 14:32:59 +02:00
Adam Reichold bd7aed4b12 Add implementation of Iterator::size_hint for PyIterator
When the Python iterator backing `PyIterator` has a `__length_hint__` special
method, we can use this as a lower bound for Rust's `Iterator::size_hint` to
e.g. support pre-allocation of collections.

This is implemented using `PyObject_LengthHint` which is not available in the
stable ABI and hence so is `Iterator::size_hint`. This should be fine since this
is an optimization in any case and the stable ABI is expected to have slightly
worse performance overall.
2023-07-09 10:16:20 +02:00
David Hewitt 81c0328d91 use concrete inner for PyErr:matches 2023-07-04 21:03:24 +01:00
David Hewitt 76f3a395ef move unsafe block inside error_on_minusone calls 2023-07-04 21:03:24 +01:00
David Hewitt 43477a8e30 use error_on_minusone in more cases 2023-07-04 21:03:24 +01:00
David Hewitt 7613f65c89 apply conventions for ffi calls 2023-07-04 21:03:24 +01:00
David Hewitt bf2f441567 prefer inner / _private naming 2023-07-04 21:03:24 +01:00
Adam Reichold 54ab9090be
Merge pull request #3269 from grantslatton/timezone-conversion-bugfix
Fix fixed offset timezone conversion bug.
2023-07-04 18:22:13 +00:00
Alex Gaynor 0b78bb851e
Allow #[new] to return existing instances
fixes #2384
2023-07-02 19:57:53 -04:00
Adam Reichold e006b34b5e Apparently, PySet_Add does not steal a reference, hence we should not forget to clean up ours. 2023-07-02 20:43:43 +02:00
David Hewitt 135535e668
Merge pull request #3280 from davidhewitt/option-to-tz
clarify ownership of opt_to_pyobj helper function
2023-06-28 21:23:33 +00:00
Adam Reichold afc1d4cc42
Merge pull request #3281 from davidhewitt/set-discard
handle exceptions properly in `PySet::discard`
2023-06-28 17:09:01 +00:00
David Hewitt b7d391d994 clarify ownership of opt_to_pyobj helper function 2023-06-28 08:54:56 +01:00
David Hewitt c0b9502c0e handle exceptions properly in PySet::discard 2023-06-28 08:54:06 +01:00
David Hewitt 4867ef8dd3 stop suppressing unrelated exceptions in PyAny::hasattr 2023-06-27 23:20:22 +01:00
David Hewitt 20f909c97f refactor PyDict::get_item[_with_error] implementations 2023-06-25 20:13:52 +01:00
David Hewitt db91642bae add PyDict::get_item_with_error for PyPy 2023-06-25 19:26:08 +01:00
Grant Slatton b1e7ed8a58 Fix fixed offset timezone conversion bug.
See https://github.com/PyO3/pyo3/issues/3267
2023-06-25 11:06:46 -07:00
Adam Reichold 4afa994449 Mark Python::with_pool as safe on stable. 2023-06-21 09:12:10 +02:00
Adam Reichold d7e147509b Add Python::with_pool as a safer alternative to Python::new_pool. 2023-06-21 08:05:19 +02:00
mejrs 686f5eb0ad Simplify doctests macro 2023-06-19 18:12:01 +02:00
Adam Reichold 5eed73f1c0 Rework pyobject_native_type_info! to expect callables
Most native types have static type objects which just need to be turned into a
pointer using addr_of_mut!, but sometimes like for exceptions we do call a
function which lazily initializes a type object.

This makes the pyobject_native_type_info! macro expect callable and passes it
the GIL token so that we do not need to call Python::assume_gil_acquired. The
case of static type objects is handled by the
pyobject_native_static_type_object! helper macro.
2023-06-19 10:30:03 +02:00
Adam Reichold 42bbd52e15 Keep the dynamic borrow checking enabled for debug builds. 2023-06-18 15:38:37 +02:00
Adam Reichold 96ad57d783 We already carefully handle re-entrancy for OWNED_OBJECTS, so let's avoid the runtime checking overhead. 2023-06-18 15:25:46 +02:00
Adam Reichold 85d5b6ee77 Drop reference pool's dirty flag is the additional cost does not outweigh the improvement compared to locking an uncontented mutex. 2023-06-18 15:25:46 +02:00
Adam Reichold cbead1f437 Fix two left-over usages of cfg(addr_of). 2023-06-17 19:35:50 +02:00
Luca Trevisani ab7a65cbb5
Improve PyModule::from_code examples 2023-06-16 23:45:49 +02:00
Adam Reichold ba0c7e15b3
Merge pull request #3156 from adriangb/frozenset-ops
Add `PyFrozenSetBuilder`
2023-06-14 06:06:32 +00:00
David Hewitt 4f3fcdbf0f remove all functionality deprecated in PyO3 0.18 2023-06-13 22:27:43 +01:00
Adrian Garcia Badaracco a28641af68
Add PyFrozenSetBuilder 2023-06-13 15:59:35 -05:00
Adam Reichold a053489c8b
Merge pull request #2709 from davidhewitt/py3.12
ci: add Python 3.12-dev jobs
2023-06-12 08:59:35 +00:00
Adam Reichold b110466c57
Merge pull request #3221 from davidhewitt/msrv-tidy-ups
docs: remove unneeded cfg, fixup internal banner
2023-06-12 06:33:48 +00:00
David Hewitt 199261f436
Merge pull request #3197 from mhils/ipaddr
Add `IpAddr` <-> `ipaddress.IPv(4/6)Address` conversion
2023-06-12 04:00:43 +00:00
David Hewitt 621898b07d ci: add Python 3.12-dev jobs 2023-06-11 21:57:17 +01:00
David Hewitt 7fd59455b1 ci: pool can be dirty from other threads 2023-06-11 21:52:23 +01:00
David Hewitt 46942b9a14 docs: remove workarounds for #[doc = concat!(...)] following msrv bump 2023-06-08 21:04:49 +01:00
Maximilian Hils 980f05a88e Add IpAddr <-> ipaddress.IPv(4/6)Address conversion 2023-06-08 13:17:45 +02:00
Adam Reichold 0d30bb7d3d Bump Rust edition to 2021 and make current Clippy happy. 2023-06-07 21:15:38 +02:00
bors[bot] e1f028f3e5
Merge #3209
3209: Remove the conditional compilation flags which are made redundant  by the MSRV bump r=davidhewitt a=adamreichold



Co-authored-by: Adam Reichold <adam.reichold@t-online.de>
2023-06-05 14:09:05 +00:00
Adam Reichold eb04f54683 Remove cfg min_const_generics made unnecessary by MSRV bump. 2023-06-05 09:42:40 +02:00
Adam Reichold f7bd6ce224 Remove cfg option_insert made unnecessary by MSRV bump. 2023-06-05 09:37:13 +02:00
bors[bot] dbf7b233aa
Merge #3203
3203: support ordering magic methods for `#[pyclass]` r=adamreichold a=davidhewitt

Closes #2089 

This adds `__lt__`, `__le__`, `__eq__`, `__ne__`, `__gt__`, and `__ge__` as per the Python implementations of what we call `__richcmp__`.

There's a UI test confirming that the user cannot implement split forms and `__richcmp__` simultaneously.

There's also a benchmark comparing implementing these split methods against using `__richcmp__`. I couldn't see a meaningful performance difference, so I'm tempted to deprecate `__richcmp__`, given that's not a magic method which exists in Python. Potentially we can provide options such as the opt-in `#[pyclass(eq, ord)]` to avoid boilerplate for people who don't want to implement six different methods.



Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
2023-06-05 07:13:23 +00:00
David Hewitt 5bc3e6f15e fix clippy warnings uncovered by msrv bump 2023-06-05 07:08:27 +01:00
Adam Reichold 5738edfdd4 Bump MSRV to 1.56 2023-06-04 23:02:30 +01:00
David Hewitt 8850d5d384 support ordering magic methods for #[pyclass] 2023-06-04 13:58:18 +01:00
David Hewitt 45b5ede26a remove copyright headers from source files 2023-06-03 22:38:54 +01:00
bors[bot] fa949ff627
Merge #3198
3198: Add abi3 + num_bigint conversion r=davidhewitt a=youknowone

<!--
Please consider adding the following to your pull request:
 - an entry for this PR in newsfragments - see [https://pyo3.rs/main/contributing.html#documenting-changes]
 - docs to all new functions and / or detail in the guide
 - tests for all new or changed functions

PyO3's CI pipeline will check your pull request. To run its tests
locally, you can run ```cargo xtask ci```. See its documentation
 [here](https://github.com/PyO3/pyo3/tree/main/xtask#readme).
-->

Fix #3196

Co-authored-by: Jeong YunWon <jeong@youknowone.org>
2023-06-02 19:06:50 +00:00
Jake Lishman 8d98b4248e
Fix abi3 conversion of __complex__ classes
Python classes that were not `complex` but implemented the `__complex__`
magic would have that method called via `PyComplex_AsCComplex` when
running against the full API, but the limited-API version
`PyComplex_RealAsDouble` does not attempt this conversion.  If the input
object is not already complex, we can call the magic before proceeding.
2023-06-02 10:09:45 +01:00
Jake Lishman 194d0c791f
Add PyAny::lookup_special
`PyAny::lookup_special` is an approximate equivalent to the CPython
internal `_PyObject_LookupSpecial`, which is used to resolve lookups of
"magic" methods.  These are only looked up from the type, and skip the
instance dictionary during the lookup.  Despite this, they are still
required to resolve the descriptor protocol.

Many magic methods have slots on the `PyTypeObject` or respective
subobjects, but these are not necessarily available when targeting the
limited API or PyPy.  In these cases, the requisite logic can be worked
around using safe but likely slower APIs.

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>

Fix up lookup-special
2023-06-02 10:09:45 +01:00
Jeong YunWon 6d830e05cd Add abi3 + num_bigint conversion 2023-06-02 16:17:49 +09:00
Adam Reichold 0f628c942d Be more explicit of the soundness hole implied by tying Ungil to Send and mention the available solution. 2023-05-25 21:37:33 +02:00
Adam Reichold 4fc7b5a6e0 Manually link to the send_wrapper crate to avoid having it as a build dependencies for the docs. 2023-05-25 21:37:33 +02:00
Adam Reichold 90fcc63eda Replace the nightly UI tests by doctests since we cannot keep up with the changing error outputs of nightly in any case. 2023-05-25 21:37:32 +02:00
bors[bot] 32c335e072
Merge #3168 #3176
3168: Do not apply deferred ref count updates and prevent the GIL from being acquired inside of __traverse__ implementations. r=davidhewitt a=adamreichold

Closes #2301
Closes #3165


3176: Prevent dropping unsendable classes on other threads. r=davidhewitt a=adamreichold

Continuing the discussed from https://github.com/PyO3/pyo3/pull/3169#issuecomment-1556571504 and https://github.com/PyO3/pyo3/pull/3169#issuecomment-1556661723:

We already have checks in place to avoid borrowing these classes on other threads but it was still possible to send them to another thread and drop them there (while holding the GIL).
    
This change avoids running the `Drop` implementation in such a case even though Python will still free the underlying memory. This might leak resources owned by the object, but it avoids undefined behaviour due to access the unsendable type from another thread.
    
This does assume that the object was not unsafely integrated into an intrusive data structures which still point to the now freed memory. In that case, the only recourse would be to abort the process as freeing the memory is unavoidable when the tp_dealloc slot is called. (And moving it elsewhere into a new allocation would still break any existing pointers.)

Co-authored-by: Adam Reichold <adam.reichold@t-online.de>
2023-05-25 18:18:46 +00:00
Adam Reichold 7d4d3ca364 Move the check for a locked GIL into a cold function and closer to the locking. 2023-05-25 20:01:35 +02:00
Adam Reichold 18397828e5 Move locking the GIL and handling the resulting panics into a library function. 2023-05-25 20:01:35 +02:00
Adam Reichold 810ad00a76 Do not apply deferred ref count updates and prevent the GIL from being acquired inside of implementations. 2023-05-25 20:01:35 +02:00
Adam Reichold 501ff8a17d Prevent dropping unsendable classes on other threads.
We already have checks in place to avoid borrowing these classes on other
threads but it was still possible to send them to another thread and drop them
there (while holding the GIL).

This change avoids running the `Drop` implementation in such a case even though
Python will still free the underlying memory. This might leak resources owned by
the object, but it avoids undefined behaviour due to access the unsendable type
from another thread.

This does assume that the object was not unsafely integrated into an intrusive
data structures which still point to the now freed memory. In that case, the
only recourse would be to abort the process as freeing the memory is unavoidable
when the tp_dealloc slot is called. (And moving it elsewhere into a new
allocation would still break any existing pointers.)
2023-05-25 19:10:42 +02:00
bors[bot] dfc667fd0e
Merge #3177
3177: RFC: Use a const initializer for `GIL_COUNT` if possible r=adamreichold a=lifthrasiir

Normally [`LocalKey::try_with`](https://doc.rust-lang.org/stable/std/thread/struct.LocalKey.html#method.try_with) needs to check for the initialization flag to lazily initialize the TLS. This behaves badly with a compiler optimization and it seems that multiple calls to `gil_is_acquired()` cannot be correctly eliminated. Rust 1.59 added a `const { ... }` initializer (a special form only allowed here for now) in `thread_local!` which removes the initialization flag, allowing those kind of optimizations.

I should note that the performance impact is probably minimal, because the check branch is extremely well predicted and the optimization is only possible when every PyO3 code that leads to `gil_is_acquired()` is inlined, a pretty uncommon situation. I couldn't demonstrate any consistent improvement or regression from my machine, which performance seems to be flaky as well. But at least we would have one less branch there. I'll leave this as an RFC so that someone else can prove or disprove that this is indeed beneficial.

Co-authored-by: Kang Seonghoon <public+git@mearie.org>
2023-05-24 06:24:12 +00:00
Kang Seonghoon 291fc36d0c Use a const initializer for OWNED_OBJECTS if possible.
Since `Vec::with_capacity` is not a const function, it now does not
allocate any initial memory.
2023-05-24 10:42:07 +09:00
Adam Reichold 62f424b690 Drop EnsureGIL to remove one layer of indirection from the implementation of Python::with_gil 2023-05-23 23:31:47 +02:00
Kang Seonghoon dee45d3644 Use a const initializer for GIL_COUNT if possible. 2023-05-22 11:31:20 +09:00
David Hewitt 82a879ff6b add PyAny::is_exact_instance and PyAny::is_exact_instance_of 2023-05-21 12:44:54 +02:00
David Hewitt 248230b8e4 refactor PyAny::is_instance_of for performance 2023-05-18 22:25:27 +01:00
Adam Reichold b9766cfa11 Add PyClass::get and Py::get for GIL-independent access to frozen classes. 2023-05-18 08:57:55 +02:00
bors[bot] 4a0bea2e93
Merge #3062
3062: Stop panic on `fmt::Display` r=davidhewitt a=samuelcolvin

Closes #3060

Co-authored-by: Samuel Colvin <s@muelcolvin.com>
2023-05-10 05:52:40 +00:00
bors[bot] 633b592ed5
Merge #2593
2593: docs: mention PyBuffer r=adamreichold a=davidhewitt

Uses PEP 688 `types.Buffer` to describe `PyBuffer<T>` in the conversion tables. Will leave as draft until PEP 688 is finalised.

Closes #954 

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
Co-authored-by: Adam Reichold <adam.reichold@t-online.de>
2023-05-09 20:24:37 +00:00
David Hewitt 7c231a2372 docs: mention PyBuffer 2023-05-09 19:53:39 +01:00
Samuel Colvin 5aff2ccc9e stop panic on to_string, report using write_unraisable instead 2023-05-09 12:54:56 +02:00
bors[bot] c27a6333d6
Merge #3029
3029: use dynamic trampoline for all getters and setters r=adamreichold a=davidhewitt

This is an extension to the "trampoline" changes made in #2705 to re-use a single trampoline for all `#[getter]`s (and similar for all `#[setters]`). It works by setting the currently-unused `closure` member of the `ffi::PyGetSetDef` structure to point at a new `struct GetSetDefClosure` which contains function pointers to the `getter` / `setter` implementations.

A universal trampoline for all `getter`, for example, then works by reading the actual getter implementation out of the `GetSetDefClosure`.

Advantages of doing this:
- Very minimal simplification to the macro code / generated code size. It made a 4.4% reduction to `test_getter_setter` generated size, which is an exaggerated result as most code will probably have lots of bulk that isn't just the macro code.

Disadvantages:
- Additional level of complexity in the `getter` and `setter` trampolines and accompanying code.
- To keep the `GetSetDefClosure` objects alive, I've added them to the static `LazyTypeObject` inner.
- Very slight performance overhead at runtime (shouldn't be more than an additional pointer read). It's so slight I couldn't measure it.

Overall I'm happy to either merge or close this based on what reviewers think!

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
2023-05-09 08:50:45 +00:00
David Hewitt 996305ac62 remove other deprecations from 0.17 2023-05-09 09:39:23 +02:00
David Hewitt dd24c9ea71 remove Python::acquire_gil 2023-05-09 09:39:23 +02:00
David Hewitt 1ea57cb9ad use dynamic trampoline for all getters and setters 2023-05-09 08:09:59 +01:00
bors[bot] 6281b47954
Merge #3004
3004: Unwrap dynamic error types when inner is simple `PyErr` r=davidhewitt,adamreichold,mejrs a=BlueGlassBlock

This is the first part of suggested improvements in #2998.

This change will make bubbled `PyErr` wrapped in `eyre::Report` / `anyhow::Error` bubble up unchanged, instead of being wrapped in a `PyRuntimeError`.

Co-authored-by: BlueGlassBlock <blueglassblock@outlook.com>
2023-05-09 06:18:33 +00:00
BlueGlassBlock fdd43d0685 feat: unwrap dyn Err when inner is simple PyErr 2023-05-09 07:17:10 +01:00
Adrian Garcia Badaracco 16d333f9d0
Add BaseExceptionGroup for Python >= 3.11 2023-05-07 15:08:43 -05:00
bors[bot] 1cdac4fde4
Merge #2980
2980: support `text_signature` on `#[new]` r=adamreichold a=davidhewitt

Closes #2866 

This is a breaking change for 0.19.0, because it starts autogenerating `text_signature` for `#[new]`. This could affect runtime behaviour if the user is relying on the class docs at runtime for some reason.

Guide & tests all updated accordingly.

`#[pyclass(text_signature = "...")]` is deprecated by this PR, however if it's set, it will be used in preference to `#[new]`.

(The signature / `text_signature` from `#[new]` will simply be ignored in this case. I figure that when users fix their deprecation warnings by removing `#[pyclass(text_signature = "...")]` then the `#[new]` signatures will start flowing properly, and this is good enough.)

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
Co-authored-by: Adam Reichold <adam.reichold@t-online.de>
2023-05-04 16:51:54 +00:00
bors[bot] 22e77b0213
Merge #3131
3131: Extend lifetime of GIL token associated with PyRef(Mut). r=mejrs a=adamreichold



Co-authored-by: Adam Reichold <adam.reichold@t-online.de>
2023-05-04 11:46:09 +00:00
David Hewitt 8bd17f02c7 support text_signature on #[new] 2023-05-04 07:15:11 +01:00
cfour2 04f129f70f Refine the example for IterNextOutput
* Remove the (eventually) stale ref link;
* Typo: couter -> counter;
* Fix the formatting with `cargo fmt`;
2023-05-02 15:15:55 +08:00
cfour2 1ca1dc3ccb Copy an example for IterNextOutput from pytests with comments 2023-05-02 15:05:53 +08:00
cfour2 559b540b5c Fix a crate doc link for IterNextOutput 2023-05-02 15:05:53 +08:00
Adam Reichold 63a9093510 Extend lifetime of GIL token associated with PyRef(Mut). 2023-05-01 20:57:08 +02:00
Doug Goldstein 8e0bde14c9 implement Decimal to rust_decimal conversions
Implement conversion between rust_decimal::Decimal and decimal.Decimal
from Python's stdlib. The C API does not appear to be exposed on the
Python side so we need to call into it via Python.
2023-04-22 19:55:21 +02:00
David Hewitt eb4ba53251 Rename sequence .list() and .tuple() to .to_list() and .to_tuple() 2023-04-18 20:52:49 +01:00
Adam Reichold 654616ce50 Handle test code that is unused on wasm32. 2023-04-14 18:50:32 +02:00
Adam Reichold 48f79718f9 Fix redundant imports in doc tests thereby fixing the careful CI job. 2023-04-10 08:09:06 +02:00
Solomon Ucko 7e2f732d7a fix typo DateType -> DateTimeType, fixes #3069 2023-03-28 18:45:39 +02:00
bors[bot] ba6261c8e7
Merge #3015
3015: Implement wrapper for `PyASCIIObject.state` bitfield accesses r=davidhewitt a=decathorpe

This is a first draft of my attempt to fix #1824 "properly" by writing a C wrapper for the `PyASCIIObject.state` bitfield accesses, as proposed here: https://github.com/PyO3/pyo3/issues/1824#issuecomment-1406909504

---

The original argument for making these functions `unsafe` is still valid, though - bitfield memory layout is not guaranteed to be stable across different C compilers, as it is "implementation defined" in the C standard. However, short of having CPython upstream provide non-inlined public functions to access this bitfield, this is the next best thing, as far as I can tell.

I've removed the `#[cfg(target_endian = "little")]` attributes from all things that are un-blocked by fixing this issue on big-endian systems, except for three tests, which look like expected failures considering that they do not take bit/byte order into account (for example, when writing to the bitfield).

- `ffi::tests::ascii_object_bitfield`
- `types::string::tests::test_string_data_ucs2_invalid`
- `types::string::tests::test_string_data_ucs4_invalid`

All other tests now pass on both little-endian and big-endian systems.

---

I am aware that some parts of this PR are probably not in a state that's acceptable for merging as-is, which is why I'm filing this as a draft. Feedback about how to better integrate this change with pyo3-ffi would be great. :)

In particular, I'm unsure whether the `#include` statements in the C files are actually correct across different systems. I have only tested this on Fedora Linux so far.

I'm also open to changing the names of the C functions that are implemented in the wrapper. For now I chose the most obvious names that shouldn't cause collisions with other symbols.

Co-authored-by: Fabio Valentini <decathorpe@gmail.com>
2023-03-28 07:27:02 +00:00
Fabio Valentini 40d6d4797f
Add wrapper for PyASCIIObject state bitfield accesses based on bindgen 2023-03-26 17:11:01 +02:00
bors[bot] e5e8c7a6d0
Merge #2975 #3022 #3023
2975: RFC: Add GILProtected synchronization primitive and use it for LazyTypeObjectInner. r=davidhewitt a=adamreichold

I would also like to use that type in rust-numpy and it seems we can avoid ~~both a manual unsafe impl and~~ a full blown mutex if we apply it to `LazyTypeObjectInner`.

One downside might be that it ties us closer to the GIL when we want to enable nogil experimentation, but on the other hand, it may also help by reifying the GIL usage. (This is currently limited to comments in unsafe code in rust-numpy for example.)

3022: Fix function name shadowing r=davidhewitt a=mejrs

Fixes https://github.com/PyO3/pyo3/issues/3017

3023: Emit a better error for bad argument names r=davidhewitt a=mejrs

This will emit a better error for code like 
```rust
#[pyfunction]
fn output([a,b,c]: [u8;3]) {}
```



Co-authored-by: Adam Reichold <adam.reichold@t-online.de>
Co-authored-by: mejrs <59372212+mejrs@users.noreply.github.com>
2023-03-23 08:04:11 +00:00
bors[bot] ebd417c9cc
Merge #3044
3044: Add `PyTuple::to_list` r=davidhewitt a=davidhewitt

Companion to #3043. I've included benchmarks which suggests that this method is indeed about 25% faster on my machine.

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
2023-03-18 21:43:37 +00:00
David Hewitt 2c11b25fee Add PyTuple::to_list 2023-03-18 14:44:45 +00:00
David Hewitt d3f5fed416 PyList::as_tuple() -> PyList::to_tuple() 2023-03-12 16:27:15 +00:00
Samuel Colvin bf500edd16
add as_tuple() method to PyList 2023-03-12 12:42:59 +00:00
bors[bot] dd6498142f
Merge #3014
3014: feat: add #[pyo3(get, set)] for Cell r=davidhewitt a=AntoineRR

This fixes #2659.
The types for which `#[pyo3(get, set)]` should now work are `Cell`, `Arc` and `Box`.

There is one issue regarding `Box`, the implementation of `FromPyObject` conflicts with another one. I could not find what the issue was, especially since the other implementations for `Arc` and `Cell` work as expected. The related code and test has been commented out for now. Maybe someone could help me fix this issue if I don't figure it out myself? There is also the possibility to remove the implementation for `Box` of course.


Co-authored-by: Antoine Romero-Romero <ant.romero2@orange.fr>
2023-03-10 06:13:28 +00:00
David Hewitt cd36c6fc21 fix clippy and ui tests for Rust 1.68 2023-03-09 23:41:26 +00:00
Antoine Romero-Romero a629e8267a feat: add #[pyo3(get, set)] for Cell 2023-03-09 23:09:30 +00:00
Adam Reichold 9534749d8b Add GILProtected synchronization primitive replacement and use it for LazyTypeObjectInner. 2023-02-23 09:38:02 +01:00
bors[bot] bbaceb88b4
Merge #2899
2899: RFC: Provide a special purpose FromPyObject impl for byte slices r=davidhewitt a=adamreichold

This enables efficiently and safely getting a byte slice from either bytes or byte arrays.

The main issue I see here is discoverability, i.e. should this be mention in the docs of `PyBytes` and `PyByteArray` or in the guide?

It is also not completely clear whether this really _fixes_ the issue.

Closes #2888 

Co-authored-by: Adam Reichold <adam.reichold@t-online.de>
2023-02-22 22:13:56 +00:00
bors[bot] 7cffc92e69
Merge #2979
2979: allow `create_exception!` to place the exception in a `dotted.module` r=adamreichold a=davidhewitt

Closes #2946 

Credit fully to `@BlueGlassBlock`

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
2023-02-22 21:24:21 +00:00
Adam Reichold 0a48859fc4 Make tests of Cow::<[u8]> compatible with older Python versions by using native code instead inline Python. 2023-02-22 22:12:35 +01:00
Adam Reichold e3e37ac624 Add ToPyObject and IntoPy impl for Cow<[u8]> to support return values as well as function arguments. 2023-02-22 22:07:59 +01:00
Adam Reichold de79ebc5f8 Provide a special purpose FromPyObject impl to efficiently and safely get a byte slice from either bytes or byte arrays. 2023-02-22 22:07:59 +01:00
David Hewitt f239d2d075 allow create_exception! to place the exception in a dotted.module 2023-02-22 20:08:53 +00:00
Adam Reichold 911046c02c Reduce API surface of mod gil to better encapsulate its safety invariants. 2023-02-21 21:08:38 +01:00
bors[bot] bd07ecc91d
Merge #2952
2952: Fix allow_threads segfault r=davidhewitt a=OliverBalfour

Please see the corresponding issue **#2951** for details. This PR adds the failing test from the issue and then a fix for it. The fix simply calls `ReferencePool::update_counts` at the end of `allow_threads` to ensure objects aren't accidentally deleted too soon.

Co-authored-by: Oliver Balfour <oliver.leo.balfour@gmail.com>
2023-02-21 08:46:06 +00:00
Oliver Balfour 83f5fa2902 update reference pool counts at the end of allow_threads to avoid use-after-free 2023-02-21 08:44:48 +00:00
Enyium d700754917
Correct documentation for Py::borrow_mut(). 2023-02-19 21:12:06 +01:00
bors[bot] 3b2c175f8d
Merge #2947
2947: change PyModule::add_class to return an error if class creation fails r=adamreichold a=davidhewitt

Related to #2942 

At the moment there are panics deep in the `#[pyclass]` machinery when initialising the type fails. This PR adjusts a number of these functions to return `PyResult` instead, so that we can handle the error more appropriately further down the pipeline.

For example, take the following snippet:

```rust
#[pyclass(extends = PyBool)]
struct ExtendsBool;

#[pymodule]
fn pyo3_scratch(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<ExtendsBool>()?;
    Ok(())
}
```

Currently, importing this module will fail with a panic:

```
TypeError: type 'bool' is not an acceptable base type
thread '<unnamed>' panicked at 'An error occurred while initializing class ExtendsBool', /Users/david/Dev/pyo3/src/pyclass.rs:412:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/david/.virtualenvs/pyo3/lib/python3.10/site-packages/pyo3_scratch/__init__.py", line 1, in <module>
    from .pyo3_scratch import *
pyo3_runtime.PanicException: An error occurred while initializing class ExtendsBool
```

After this PR, this import still fails, but with a slightly cleaner, more Pythonic error:

```
TypeError: type 'bool' is not an acceptable base type

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/david/.virtualenvs/pyo3/lib/python3.10/site-packages/pyo3_scratch/__init__.py", line 1, in <module>
    from .pyo3_scratch import *
RuntimeError: An error occurred while initializing class ExtendsBool
```

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
Co-authored-by: Adam Reichold <adam.reichold@t-online.de>
2023-02-18 16:12:17 +00:00
David Hewitt c7cc48f8e4 use PyO3 types within LazyTypeObject 2023-02-18 09:06:36 +00:00
bors[bot] c858ced8d4
Merge #2944
2944: optimize sequence conversion for list and tuple r=adamreichold a=davidhewitt

closes #2943 

Avoid using `PyObject_IsInstance` for checking if lists or tuples are sequences, as we know they are always sequences.

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
2023-02-15 23:16:35 +00:00
David Hewitt ff48b0f18e optimize sequence conversion for list and tuple 2023-02-15 08:28:29 +00:00
David Hewitt 40709db801 optimize mapping conversion for dict 2023-02-15 08:27:18 +00:00
David Hewitt 00ddd21535 change PyModule::add_class to return an error if class creation fails 2023-02-14 22:08:35 +00:00
David Hewitt dbeb3b4453 move some private internals out of public implementation 2023-02-11 21:28:27 +00:00
bors[bot] 806eed5b07
Merge #2914
2914: correct ffi definition of PyIter_Check r=davidhewitt a=davidhewitt

Closes #2913 

It looks like what is happening is that PyO3 was relying on an outdated macro form of `PyIter_Check` which is now a CPython implementation detail, which would explain why it was behaving inconsistently on different platforms (likely due to differences in linkers / implementations).

The test I've pushed succeeds, but fails to compile due to a hygiene bug! I'm done for tonight so I'll take a look at that soon and then rebase this after.

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
2023-02-03 20:51:15 +00:00
David Hewitt 5bab0e9409 use simplified PyIter_Check on CPython 3.7 2023-02-03 07:55:44 +00:00
bors[bot] 141cbeaa2c
Merge #2912
2912: Add `PyDict.update()` and `PyDict.update_if_missing()` r=davidhewitt a=samuelcolvin

Fix #2910

Note, I'd also be happy to remove the `override_` argument from merge and perhaps rename it to `update_missing` or similar to give a cleaner API. LMK what you think.

Please consider adding the following to your pull request:
 - [x] an entry for this PR in newsfragments
 - [x] docs to all new functions and / or detail in the guide
 - [x] tests for all new or changed functions


Co-authored-by: Samuel Colvin <s@muelcolvin.com>
2023-02-03 06:32:52 +00:00
Samuel Colvin c09dfcd4e0 add PyDict.update() and PyDict.update_if_missing() 2023-02-03 06:32:01 +00:00
bors[bot] cb38ff0111
Merge #2889
2889: Added support for PyErr_WriteUnraisable r=davidhewitt a=mitsuhiko

Fixes #2884

Co-authored-by: Armin Ronacher <armin.ronacher@active-4.com>
2023-01-29 20:28:00 +00:00
Armin Ronacher 066880e7d5 Added support for PyErr_WriteUnraisable 2023-01-29 20:01:22 +00:00
David Hewitt f4953224d8 correct ffi definition of PyIter_Check 2023-01-29 19:43:33 +00:00
bors[bot] 165062e6bd
Merge #2907
2907: Update `downcast` documentation r=adamreichold a=mejrs

This was outdated (!)


Co-authored-by: mejrs <59372212+mejrs@users.noreply.github.com>
Co-authored-by: Adam Reichold <adam.reichold@t-online.de>
2023-01-28 17:46:34 +00:00
mejrs cadcabaf04 Feedback 2023-01-28 15:35:31 +01:00
bors[bot] d118ee3a73
Merge #2923 #2924
2923: hygiene: fix `#[pymethods(crate = "...")]` r=davidhewitt a=davidhewitt

Got to the bottom of the hygiene issue in test of #2914 

Turns out that `#[pymethods] #[pyo3(crate = "...")]` works, but `#[pymethods(crate = "...")]` was ignoring the argument.

Added a tweak to fix this and a snippet in the hygiene test (which fails on `main`). 

2924: remove unneeded into_iter calls r=davidhewitt a=davidhewitt

Clippy complaining about these to me this morning locally.

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
2023-01-27 09:31:20 +00:00
bors[bot] 083dd5fe29
Merge #2904 #2921
2904: refactor docstring generation code r=mejrs a=davidhewitt

As a first step towards #2866 this is a tweak to the macro code which generates Python docstrings. This PR refactors the behaviour so that instead of always creating a `concat!` expression to generate a nul-terminated string, this will only happen if a Rust 1.54+ macro doc is present (e.g. `#[doc = include_str!(...)]`).

The default case now just collects all the `#[doc]` attributes into a single string.

This should make it easier to factor out the `text_signature` formatting, and avoids wasting compile time invoking the `concat!` macro when not necessary.

2921: Check to see if object is `None` before traversing r=davidhewitt a=neachdainn

Closes #2915

When using the C API directly, the intended way to call `visitproc` is via the `Py_VISIT` macro, which checks to see that the provided pointer is not null before passing it along to `visitproc`. Because PyO3 isn't using the macro, it needs to manually check that the pointer isn't null. Without this check, calling `visit.call(&obj)` where `let obj = None;` will segfault.


Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
Co-authored-by: Nate Kent <nate@nkent.net>
2023-01-27 07:52:03 +00:00
Samuel Colvin 3c9ace03d8 add Ellipsis() and is_ellipsis() methods, fix #2906 2023-01-27 06:40:02 +00:00
David Hewitt 5667a095d6 hygiene: fix #[pymethods(crate = "...")] 2023-01-27 06:34:12 +00:00
Nate Kent f38841a8e2
Check to see if object is None before traversing
Closes #2915

When using the C API directly, the intended way to call `visitproc` is
via the `Py_VISIT` macro, which checks to see that the provided pointer
is not null before passing it along to `visitproc`. Because PyO3 isn't
using the macro, it needs to manually check that the pointer isn't null.
Without this check, calling `visit.call(&obj)` where `let obj = None;`
will segfault.
2023-01-26 15:55:58 -08:00
mejrs fe7b1eed04 Update downcast documentation 2023-01-24 19:15:32 +01:00
David Hewitt 255d9bacce tidy up implementation of pyclass tp_dealloc 2023-01-19 21:31:59 +00:00
bors[bot] dbb108c2c5
Merge #2893
2893: rename `wrap_pyfunction` impl to `wrap_pyfunction_impl` r=messense a=davidhewitt

I mistyped the other day and wrote `wrap_pyfunction(f, py)` without the `!` to invoke the macro, and `rust-analyzer` imported the hidden symbol `pyo3::impl_::pyfunction::wrap_pyfunction`. Took me a moment to realise the compilation failure was because I'd forgotten the `!`.

This PR just renames that hidden symbol to `pyo3::impl_::pyfunction::wrap_pyfunction_impl` so it doesn't clash with the user-facing macro.

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
2023-01-19 20:08:59 +00:00
David Hewitt 586fed2c4b send errors in __releasebuffer__ to sys.unraisablehook 2023-01-19 19:10:06 +00:00
David Hewitt 89d4ae1dbf rename wrap_pyfunction impl to wrap_pyfunction_impl 2023-01-19 08:51:44 +00:00
bors[bot] 72c561ce13
Merge #2882
2882: inspect: gate behind `experimental-inspect` feature r=davidhewitt a=davidhewitt

This is the last thing I want to do before preparing 0.18 release.

The `pyo3::inspect` functionality looks useful as a first step towards #2454. However, we don't actually make use of this anywhere within PyO3 yet (we could probably use it for better error messages). I think we also have open questions about the traits which I'd like to resolve before committing to these additional APIs. (For example, this PR adds `IntoPy::type_output`, which seems potentially misplaced to me, the `type_output` function probably wants to be on a non-generic trait e.g. `ToPyObject` or maybe #2316.) 

As such, I propose putting these APIs behind an `experimental-inspect` feature gate for now, and invite users who find them useful to contribute a finished-off design.

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
2023-01-17 07:31:09 +00:00
David Hewitt 20ca3be659 inspect: gate behind experimental-inspect feature 2023-01-15 12:41:23 +00:00
David Hewitt 8f48d157d6 deprecate required arguments after option arguments without signature 2023-01-15 10:17:20 +00:00
bors[bot] 8af48bbb53
Merge #2796
2796: Forward cfgs on pyclass fields to the method defs r=davidhewitt a=mejrs

With this and the cfg_attr PR, I don't need cfg_eval at all anymore :)


- [x] needs some more tests

Co-authored-by: mejrs <>
2022-12-29 16:28:26 +00:00
bors[bot] cedb5aecb2
Merge #2843
2843: remove functionality deprecated in 0.16 r=davidhewitt a=davidhewitt

Simple cleanup to remove all functionality marked deprecated in the 0.16 releases.

Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
2022-12-28 12:24:59 +00:00
David Hewitt f2608a923c remove functionality deprecated in 0.16 2022-12-28 12:23:53 +00:00
bors[bot] c2adf14f69
Merge #2842
2842: Stop leaking in `new_closure` r=adamreichold a=davidhewitt

This is a rebase of #2690 which simplifies the `MaybeLeaked` abstraction from that PR with just `Cow<'static, CStr>`.

This enabled me to annotate with `FIXME` all the places where we still leak; I wonder if we could potentially use `GILOnceCell` in future and statics to avoid those. As those callsities are in `#[pyclass]` and `#[pyfunction]` these are effectively in statics anyway, but it would be nice to tidy up.


Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
2022-12-28 08:13:58 +00:00
David Hewitt 1e8206c0b8 Stop leaking in new_closure 2022-12-28 07:51:50 +00:00
David Hewitt 24032fe110 pypy: re-enable PyFunction on 3.8+ 2022-12-27 14:32:43 +00:00
David Hewitt 30c66fdb8b ci: fix flaky test_pyobject_drop_without_gil_doesnt_decrease_refcnt 2022-12-27 00:49:54 +01:00
David Hewitt a47079d858 move GILOnceCell initialization detail to the type-level docs 2022-12-26 20:38:25 +00:00
Benoît du Garreau 01fcfedbe5 Add GILOnceCell::get_or_try_init 2022-12-26 20:28:18 +00:00
David Hewitt 010dd509d7 pypy: enable PyList::get_item_unchecked 2022-12-25 08:45:36 +00:00
David Hewitt 33871b7aea allow **kwargs to take arguments which conflict with positional-only parameters 2022-12-17 07:22:28 +00:00
mejrs 44310ec7e0 Forward cfgs on pyclass fields to the method defs 2022-12-06 22:38:32 +01:00
David Hewitt 3295e35a4b accept any iterator for PySet::new and PyFrozenSet::new 2022-12-04 09:54:34 +00:00
Shantanu 95f041281f
Mention into_py in docs for PyTuple::new
I'm new to Rust / PyO3, and it took me a little bit to figure this out :-)
2022-11-23 16:34:59 -08:00
Georg Brandl 717e09be13 Fix coding style in docstrings. 2022-11-23 07:42:17 +01:00
bors[bot] 40340062b2
Merge #2769
2769: PySlice: fix isize->long truncation in initialization r=davidhewitt a=birkenfeld



Co-authored-by: Georg Brandl <georg@python.org>
2022-11-22 19:04:30 +00:00
Georg Brandl cbae47d171 PySlice: fix isize->long truncation in initialization
Fixes #2768
2022-11-22 12:04:32 +01:00
Georg Brandl 99c8dea30e Use Python::get_type() instead of PyTypeInfo::type_object()
The former needs one less import and uses a familiar object.
2022-11-20 15:16:18 +01:00
Georg Brandl 21fd1a91d0 Make downcast() methods inline 2022-11-20 13:14:54 +01:00
Georg Brandl 249c0209fd Add {Py,PyAny}::downcast_unchecked to replace try_from_unchecked calls 2022-11-18 07:00:40 +01:00
Georg Brandl d6ac4d51b7 Replace explicit try_from usage by downcast 2022-11-18 07:00:40 +01:00
Georg Brandl 7d4dfc32b3 PyAny::downcast(): relax lifetime bounds 2022-11-18 07:00:40 +01:00
Georg Brandl c489809938 Py/PyAny: deprecate cast_as() in favor of downcast()
They are (practically) identical on PyAny, and `downcast()` is the more
useful name.
2022-11-18 07:00:40 +01:00
Georg Brandl 1d20f2a531
Export warning classes and add PyErr::warn_explicit() (#2742) 2022-11-17 19:30:48 +01:00
Adam Reichold f5735614fb
Merge pull request #2744 from PyO3/chrono-expect-value-error
Replace hidden panics on invalid values passed to chrono by ValueError.
2022-11-17 06:47:19 +01:00
Georg Brandl 62e2d6094e
crate doc: add missing links to chrono subpage/crate doc (#2743) 2022-11-16 20:39:59 +00:00
Adam Reichold f8ce3408f4 Replace hidden panics on invalid values passed to chrono by ValueError. 2022-11-16 20:23:00 +01:00
Adam Reichold 4ffe0963b8 Make Clippy happy again by avoid deprecated constructors from chrono. 2022-11-15 22:06:02 +01:00
Adam Reichold 694ef1ea39 Make Clippy happy again by removing supposedly unnecessary casts. 2022-11-15 21:50:29 +01:00
Chih Wang d060a19303
Add support for std::num::NonZero integer types (#2730) 2022-11-13 10:54:55 +00:00
Alex Gaynor f7a487b809
Use a TypeError, rather than a ValueError, when refusing to treat a str as a Vec
This is far more consistent with how these exceptions are usually used
2022-11-07 07:48:13 -05:00
Bruno Kolenbrander 6766d9f93b
Merge pull request #2686 from dalcde/closure-name-doc
Support passing name and doc to new_closure.
2022-11-06 17:35:20 +01:00
messense 736e97556d
Disable PyModule::filename on PyPy 2022-10-31 15:45:50 +08:00
Dexter Chua 9201a7dd48 Support passing name and doc to PyCFunction::new_closure. Fixes #2665 2022-10-29 12:26:09 +08:00
David Hewitt 8e8b484169
add #[pyo3(signature = (...))] attribute (#2702) 2022-10-25 07:23:21 +01:00
David Hewitt 747d791f1f
introduce trampolines for methods (#2705) 2022-10-25 07:22:36 +01:00
David Hewitt 1c3c5f2c5f
Merge pull request #2661 from davidhewitt/std-conversions
refactor: move std conversions into common module
2022-10-20 07:58:02 +01:00
David Hewitt 39a68cf7ac
Merge pull request #2687 from saethlin/main
Avoid calling slice::from_raw_parts with a null pointer
2022-10-20 07:34:39 +01:00
David Hewitt fb34ed1694 add more coverage 2022-10-20 07:29:42 +01:00
David Hewitt c76916a084 refactor: move std conversions into common module 2022-10-19 21:36:39 +01:00
Ben Kimock 7ff5ab770a Avoid calling slice::from_raw_parts with a null pointer 2022-10-18 17:09:27 -04:00
Georg Brandl 676227d2a1
Make is_instance() and is_subclass() take &PyAny (#2695) 2022-10-18 19:22:23 +02:00
Bruno Kolenbrander 4a04603c2c
Don't use intocallback in method macros (#2664)
* Don't use intocallback in method macros

Co-authored-by: mejrs <>
2022-10-16 10:35:58 +01:00
David Hewitt 125af9b7de
Merge pull request #2676 from PyO3/exact-iter
Add more implementations of ExactSizeIterator when iterating built-in Python data structures.
2022-10-13 21:28:04 +01:00