index int64 0 0 | repo_id stringclasses 596 values | file_path stringlengths 31 168 | content stringlengths 1 6.2M |
|---|---|---|---|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-runtime/README.md | Coming soon!
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-runtime/LICENSE-MIT | Copyright (c) 2023-present PyO3 Project and Contributors. https://github.com/PyO3
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-runtime/pyproject.toml | [build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "pyo3-runtime"
dynamic = ["version"]
description = ''
readme = "README.md"
requires-python = ">=3.7"
license = "MIT OR Apache-2.0"
keywords = []
authors = [
{ name = "David Hewitt", email = "1939362+davidhewitt@users.noreply.github.com" },
]
classifiers = [
"Development Status :: 4 - Beta",
"Programming Language :: Python",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
dependencies = []
[project.urls]
Homepage = "https://github.com/PyO3/pyo3"
[tool.hatch.version]
path = "src/pyo3_runtime/__init__.py"
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-runtime/src | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-runtime/src/pyo3_runtime/__init__.py | __version__ = "0.0.1"
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/noxfile.py | import nox
import sys
from nox.command import CommandFailed
nox.options.sessions = ["test"]
@nox.session
def test(session: nox.Session):
session.env["MATURIN_PEP517_ARGS"] = "--profile=dev"
session.run_always("python", "-m", "pip", "install", "-v", ".[dev]")
def try_install_binary(package: str, constraint: str):
try:
session.install("--only-binary=:all:", f"{package}{constraint}")
except CommandFailed:
# No binary wheel available on this platform
pass
try_install_binary("numpy", ">=1.16")
# https://github.com/zopefoundation/zope.interface/issues/316
# - is a dependency of gevent
try_install_binary("zope.interface", "<7")
try_install_binary("gevent", ">=22.10.2")
ignored_paths = []
if sys.version_info < (3, 10):
# Match syntax is only available in Python >= 3.10
ignored_paths.append("tests/test_enums_match.py")
ignore_args = [f"--ignore={path}" for path in ignored_paths]
session.run("pytest", *ignore_args, *session.posargs)
@nox.session
def bench(session: nox.Session):
session.install(".[dev]")
session.run("pytest", "--benchmark-enable", "--benchmark-only", *session.posargs)
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/Cargo.toml | [package]
authors = ["PyO3 Authors"]
name = "pyo3-pytests"
version = "0.1.0"
description = "Python-based tests for PyO3"
edition = "2021"
publish = false
[dependencies]
pyo3 = { path = "../", features = ["extension-module"] }
[build-dependencies]
pyo3-build-config = { path = "../pyo3-build-config" }
[lib]
name = "pyo3_pytests"
crate-type = ["cdylib"]
[lints]
workspace = true
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/MANIFEST.in | include pyproject.toml Cargo.toml
recursive-include src *
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/build.rs | fn main() {
pyo3_build_config::use_pyo3_cfgs();
pyo3_build_config::add_extension_module_link_args();
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/README.md | # pyo3-pytests
An extension module built using PyO3, used to test and benchmark PyO3 from Python.
## Testing
This package is intended to be built using `maturin`. Once built, you can run the tests using `pytest`:
```shell
pip install maturin
maturin develop
pytest
```
Alternatively, install nox and run the tests inside an isolated environment:
```shell
nox
```
## Running benchmarks
You can install the module in your Python environment and then run the benchmarks with pytest:
```shell
pip install .
pytest --benchmark-enable
```
Or with nox:
```shell
nox -s bench
```
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/pyproject.toml | [build-system]
requires = ["maturin>=1,<2"]
build-backend = "maturin"
[tool.pytest.ini_options]
addopts = "--benchmark-disable"
[project]
name = "pyo3_pytests"
version = "0.1.0"
classifiers = [
"License :: OSI Approved :: MIT License",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Programming Language :: Rust",
"Operating System :: POSIX",
"Operating System :: MacOS :: MacOS X",
]
[project.optional-dependencies]
dev = [
"hypothesis>=3.55",
"pytest-asyncio>=0.21",
"pytest-benchmark>=3.4",
# pinned < 8.1 because https://github.com/CodSpeedHQ/pytest-codspeed/issues/27
"pytest>=7,<8.1",
"typing_extensions>=4.0.0"
]
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/conftest.py | import sysconfig
import sys
import pytest
FREE_THREADED_BUILD = bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
gil_enabled_at_start = True
if FREE_THREADED_BUILD:
gil_enabled_at_start = sys._is_gil_enabled()
def pytest_terminal_summary(terminalreporter, exitstatus, config):
if FREE_THREADED_BUILD and not gil_enabled_at_start and sys._is_gil_enabled():
tr = terminalreporter
tr.ensure_newline()
tr.section("GIL re-enabled", sep="=", red=True, bold=True)
tr.line("The GIL was re-enabled at runtime during the tests.")
tr.line("")
tr.line("Please ensure all new modules declare support for running")
tr.line("without the GIL. Any new tests that intentionally imports ")
tr.line("code that re-enables the GIL should do so in a subprocess.")
pytest.exit("GIL re-enabled during tests", returncode=1)
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_path.py | import pathlib
import pytest
import pyo3_pytests.path as rpath
def test_make_path():
p = rpath.make_path()
assert p == "/root"
def test_take_pathbuf():
p = "/root"
assert rpath.take_pathbuf(p) == p
def test_take_pathlib():
p = pathlib.Path("/root")
assert rpath.take_pathbuf(p) == str(p)
def test_take_pathlike():
assert rpath.take_pathbuf(PathLike("/root")) == "/root"
def test_take_invalid_pathlike():
with pytest.raises(TypeError):
assert rpath.take_pathbuf(PathLike(1))
def test_take_invalid():
with pytest.raises(TypeError):
assert rpath.take_pathbuf(3)
class PathLike:
def __init__(self, path):
self._path = path
def __fspath__(self):
return self._path
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_buf_and_str.py | from pyo3_pytests.buf_and_str import BytesExtractor, return_memoryview
def test_extract_bytes():
extractor = BytesExtractor()
message = b'\\(-"-;) A message written in bytes'
assert extractor.from_bytes(message) == len(message)
def test_extract_str():
extractor = BytesExtractor()
message = '\\(-"-;) A message written as a string'
assert extractor.from_str(message) == len(message)
def test_extract_str_lossy():
extractor = BytesExtractor()
message = '\\(-"-;) A message written with a trailing surrogate \ud800'
rust_surrogate_len = extractor.from_str_lossy("\ud800")
assert extractor.from_str_lossy(message) == len(message) - 1 + rust_surrogate_len
def test_extract_buffer():
extractor = BytesExtractor()
message = b'\\(-"-;) A message written in bytes'
assert extractor.from_buffer(message) == len(message)
arr = bytearray(b'\\(-"-;) A message written in bytes')
assert extractor.from_buffer(arr) == len(arr)
def test_return_memoryview():
view = return_memoryview()
assert view.readonly
assert view.contiguous
assert view.tobytes() == b"hello world"
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_comparisons.py | from typing import Type, Union
import pytest
from pyo3_pytests.comparisons import (
Eq,
EqDefaultNe,
EqDerived,
Ordered,
OrderedDefaultNe,
)
from typing_extensions import Self
class PyEq:
def __init__(self, x: int) -> None:
self.x = x
def __eq__(self, other: object) -> bool:
if isinstance(other, self.__class__):
return self.x == other.x
else:
return NotImplemented
def __ne__(self, other: Self) -> bool:
if isinstance(other, self.__class__):
return self.x != other.x
else:
return NotImplemented
@pytest.mark.parametrize(
"ty", (Eq, EqDerived, PyEq), ids=("rust", "rust-derived", "python")
)
def test_eq(ty: Type[Union[Eq, EqDerived, PyEq]]):
a = ty(0)
b = ty(0)
c = ty(1)
assert a == b
assert not (a != b)
assert a != c
assert not (a == c)
assert b == a
assert not (a != b)
assert b != c
assert not (b == c)
assert not a == 0
assert a != 0
assert not b == 0
assert b != 1
assert not c == 1
assert c != 1
with pytest.raises(TypeError):
assert a <= b
with pytest.raises(TypeError):
assert a >= b
with pytest.raises(TypeError):
assert a < c
with pytest.raises(TypeError):
assert c > a
class PyEqDefaultNe:
def __init__(self, x: int) -> None:
self.x = x
def __eq__(self, other: Self) -> bool:
return self.x == other.x
@pytest.mark.parametrize("ty", (EqDefaultNe, PyEqDefaultNe), ids=("rust", "python"))
def test_eq_default_ne(ty: Type[Union[EqDefaultNe, PyEqDefaultNe]]):
a = ty(0)
b = ty(0)
c = ty(1)
assert a == b
assert not (a != b)
assert a != c
assert not (a == c)
assert b == a
assert not (a != b)
assert b != c
assert not (b == c)
with pytest.raises(TypeError):
assert a <= b
with pytest.raises(TypeError):
assert a >= b
with pytest.raises(TypeError):
assert a < c
with pytest.raises(TypeError):
assert c > a
class PyOrdered:
def __init__(self, x: int) -> None:
self.x = x
def __lt__(self, other: Self) -> bool:
return self.x < other.x
def __le__(self, other: Self) -> bool:
return self.x <= other.x
def __eq__(self, other: Self) -> bool:
return self.x == other.x
def __ne__(self, other: Self) -> bool:
return self.x != other.x
def __gt__(self, other: Self) -> bool:
return self.x >= other.x
def __ge__(self, other: Self) -> bool:
return self.x >= other.x
@pytest.mark.parametrize("ty", (Ordered, PyOrdered), ids=("rust", "python"))
def test_ordered(ty: Type[Union[Ordered, PyOrdered]]):
a = ty(0)
b = ty(0)
c = ty(1)
assert a == b
assert a <= b
assert a >= b
assert a != c
assert a <= c
assert b == a
assert b <= a
assert b >= a
assert b != c
assert b <= c
assert c != a
assert c != b
assert c > a
assert c >= a
assert c > b
assert c >= b
class PyOrderedDefaultNe:
def __init__(self, x: int) -> None:
self.x = x
def __lt__(self, other: Self) -> bool:
return self.x < other.x
def __le__(self, other: Self) -> bool:
return self.x <= other.x
def __eq__(self, other: Self) -> bool:
return self.x == other.x
def __gt__(self, other: Self) -> bool:
return self.x >= other.x
def __ge__(self, other: Self) -> bool:
return self.x >= other.x
@pytest.mark.parametrize(
"ty", (OrderedDefaultNe, PyOrderedDefaultNe), ids=("rust", "python")
)
def test_ordered_default_ne(ty: Type[Union[OrderedDefaultNe, PyOrderedDefaultNe]]):
a = ty(0)
b = ty(0)
c = ty(1)
assert a == b
assert not (a != b)
assert a <= b
assert a >= b
assert a != c
assert not (a == c)
assert a <= c
assert b == a
assert not (b != a)
assert b <= a
assert b >= a
assert b != c
assert not (b == c)
assert b <= c
assert c != a
assert not (c == a)
assert c != b
assert not (c == b)
assert c > a
assert c >= a
assert c > b
assert c >= b
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_awaitable.py | import pytest
import sys
from pyo3_pytests.awaitable import IterAwaitable, FutureAwaitable
@pytest.mark.skipif(
sys.implementation.name == "graalpy",
reason="GraalPy's asyncio module has a bug with native classes, see oracle/graalpython#365",
)
@pytest.mark.asyncio
async def test_iter_awaitable():
assert await IterAwaitable(5) == 5
@pytest.mark.skipif(
sys.implementation.name == "graalpy",
reason="GraalPy's asyncio module has a bug with native classes, see oracle/graalpython#365",
)
@pytest.mark.asyncio
async def test_future_awaitable():
assert await FutureAwaitable(5) == 5
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_enums_match.py | # This file is only collected when Python >= 3.10, because it tests match syntax.
import pytest
from pyo3_pytests import enums
@pytest.mark.parametrize(
"variant",
[
enums.ComplexEnum.Int(42),
enums.ComplexEnum.Float(3.14),
enums.ComplexEnum.Str("hello"),
enums.ComplexEnum.EmptyStruct(),
enums.ComplexEnum.MultiFieldStruct(42, 3.14, True),
],
)
def test_complex_enum_match_statement(variant: enums.ComplexEnum):
match variant:
case enums.ComplexEnum.Int(i=x):
assert x == 42
case enums.ComplexEnum.Float(f=x):
assert x == 3.14
case enums.ComplexEnum.Str(s=x):
assert x == "hello"
case enums.ComplexEnum.EmptyStruct():
assert True
case enums.ComplexEnum.MultiFieldStruct(a=x, b=y, c=z):
assert x == 42
assert y == 3.14
assert z is True
case _:
assert False
@pytest.mark.parametrize(
"variant",
[
enums.ComplexEnum.Int(42),
enums.ComplexEnum.Float(3.14),
enums.ComplexEnum.Str("hello"),
enums.ComplexEnum.EmptyStruct(),
enums.ComplexEnum.MultiFieldStruct(42, 3.14, True),
],
)
def test_complex_enum_pyfunction_in_out(variant: enums.ComplexEnum):
match enums.do_complex_stuff(variant):
case enums.ComplexEnum.Int(i=x):
assert x == 5
case enums.ComplexEnum.Float(f=x):
assert x == 9.8596
case enums.ComplexEnum.Str(s=x):
assert x == "42"
case enums.ComplexEnum.EmptyStruct():
assert True
case enums.ComplexEnum.MultiFieldStruct(a=x, b=y, c=z):
assert x == 42
assert y == 3.14
assert z is True
case _:
assert False
@pytest.mark.parametrize(
"variant",
[
enums.ComplexEnum.MultiFieldStruct(42, 3.14, True),
],
)
def test_complex_enum_partial_match(variant: enums.ComplexEnum):
match variant:
case enums.ComplexEnum.MultiFieldStruct(a):
assert a == 42
case _:
assert False
@pytest.mark.parametrize(
"variant",
[
enums.TupleEnum.Full(42, 3.14, True),
enums.TupleEnum.EmptyTuple(),
],
)
def test_tuple_enum_match_statement(variant: enums.TupleEnum):
match variant:
case enums.TupleEnum.Full(_0=x, _1=y, _2=z):
assert x == 42
assert y == 3.14
assert z is True
case enums.TupleEnum.EmptyTuple():
assert True
case _:
print(variant)
assert False
@pytest.mark.parametrize(
"variant",
[
enums.SimpleTupleEnum.Int(42),
enums.SimpleTupleEnum.Str("hello"),
],
)
def test_simple_tuple_enum_match_statement(variant: enums.SimpleTupleEnum):
match variant:
case enums.SimpleTupleEnum.Int(x):
assert x == 42
case enums.SimpleTupleEnum.Str(x):
assert x == "hello"
case _:
assert False
@pytest.mark.parametrize(
"variant",
[
enums.TupleEnum.Full(42, 3.14, True),
],
)
def test_tuple_enum_match_match_args(variant: enums.TupleEnum):
match variant:
case enums.TupleEnum.Full(x, y, z):
assert x == 42
assert y == 3.14
assert z is True
assert True
case _:
assert False
@pytest.mark.parametrize(
"variant",
[
enums.TupleEnum.Full(42, 3.14, True),
],
)
def test_tuple_enum_partial_match(variant: enums.TupleEnum):
match variant:
case enums.TupleEnum.Full(a):
assert a == 42
case _:
assert False
@pytest.mark.parametrize(
"variant",
[
enums.MixedComplexEnum.Nothing(),
enums.MixedComplexEnum.Empty(),
],
)
def test_mixed_complex_enum_match_statement(variant: enums.MixedComplexEnum):
match variant:
case enums.MixedComplexEnum.Nothing():
assert True
case enums.MixedComplexEnum.Empty():
assert True
case _:
assert False
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_pyclasses.py | import platform
from typing import Type
import pytest
from pyo3_pytests import pyclasses
def test_empty_class_init(benchmark):
benchmark(pyclasses.EmptyClass)
def test_method_call(benchmark):
obj = pyclasses.EmptyClass()
assert benchmark(obj.method) is None
def test_proto_call(benchmark):
obj = pyclasses.EmptyClass()
assert benchmark(len, obj) == 0
class EmptyClassPy:
def method(self):
pass
def __len__(self) -> int:
return 0
def test_empty_class_init_py(benchmark):
benchmark(EmptyClassPy)
def test_method_call_py(benchmark):
obj = EmptyClassPy()
assert benchmark(obj.method) == pyclasses.EmptyClass().method()
def test_proto_call_py(benchmark):
obj = EmptyClassPy()
assert benchmark(len, obj) == len(pyclasses.EmptyClass())
def test_iter():
i = pyclasses.PyClassIter()
assert next(i) == 1
assert next(i) == 2
assert next(i) == 3
assert next(i) == 4
assert next(i) == 5
with pytest.raises(StopIteration) as excinfo:
next(i)
assert excinfo.value.value == "Ended"
@pytest.mark.skipif(
platform.machine() in ["wasm32", "wasm64"],
reason="not supporting threads in CI for WASM yet",
)
def test_parallel_iter():
import concurrent.futures
i = pyclasses.PyClassThreadIter()
def func():
next(i)
# the second thread attempts to borrow a reference to the instance's
# state while the first thread is still sleeping, so we trigger a
# runtime borrow-check error
with pytest.raises(RuntimeError, match="Already borrowed"):
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as tpe:
futures = [tpe.submit(func), tpe.submit(func)]
[f.result() for f in futures]
class AssertingSubClass(pyclasses.AssertingBaseClass):
pass
def test_new_classmethod():
# The `AssertingBaseClass` constructor errors if it is not passed the
# relevant subclass.
_ = AssertingSubClass(expected_type=AssertingSubClass)
with pytest.raises(ValueError):
_ = AssertingSubClass(expected_type=str)
class ClassWithoutConstructor:
def __new__(cls):
raise TypeError("No constructor defined for ClassWithoutConstructor")
@pytest.mark.parametrize(
"cls", [pyclasses.ClassWithoutConstructor, ClassWithoutConstructor]
)
def test_no_constructor_defined_propagates_cause(cls: Type):
original_error = ValueError("Original message")
with pytest.raises(Exception) as exc_info:
try:
raise original_error
except Exception:
cls() # should raise TypeError("No constructor defined for ...")
assert exc_info.type is TypeError
assert exc_info.value.args == (
"No constructor defined for ClassWithoutConstructor",
)
assert exc_info.value.__context__ is original_error
def test_dict():
try:
ClassWithDict = pyclasses.ClassWithDict
except AttributeError:
pytest.skip("not defined using abi3 < 3.9")
d = ClassWithDict()
assert d.__dict__ == {}
d.foo = 42
assert d.__dict__ == {"foo": 42}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_enums.py | import pytest
from pyo3_pytests import enums
def test_complex_enum_variant_constructors():
int_variant = enums.ComplexEnum.Int(42)
assert isinstance(int_variant, enums.ComplexEnum.Int)
float_variant = enums.ComplexEnum.Float(3.14)
assert isinstance(float_variant, enums.ComplexEnum.Float)
str_variant = enums.ComplexEnum.Str("hello")
assert isinstance(str_variant, enums.ComplexEnum.Str)
empty_struct_variant = enums.ComplexEnum.EmptyStruct()
assert isinstance(empty_struct_variant, enums.ComplexEnum.EmptyStruct)
multi_field_struct_variant = enums.ComplexEnum.MultiFieldStruct(42, 3.14, True)
assert isinstance(multi_field_struct_variant, enums.ComplexEnum.MultiFieldStruct)
variant_with_default_1 = enums.ComplexEnum.VariantWithDefault()
assert isinstance(variant_with_default_1, enums.ComplexEnum.VariantWithDefault)
variant_with_default_2 = enums.ComplexEnum.VariantWithDefault(25, "Hello")
assert isinstance(variant_with_default_2, enums.ComplexEnum.VariantWithDefault)
@pytest.mark.parametrize(
"variant",
[
enums.ComplexEnum.Int(42),
enums.ComplexEnum.Float(3.14),
enums.ComplexEnum.Str("hello"),
enums.ComplexEnum.EmptyStruct(),
enums.ComplexEnum.MultiFieldStruct(42, 3.14, True),
enums.ComplexEnum.VariantWithDefault(),
],
)
def test_complex_enum_variant_subclasses(variant: enums.ComplexEnum):
assert isinstance(variant, enums.ComplexEnum)
def test_complex_enum_field_getters():
int_variant = enums.ComplexEnum.Int(42)
assert int_variant.i == 42
float_variant = enums.ComplexEnum.Float(3.14)
assert float_variant.f == 3.14
str_variant = enums.ComplexEnum.Str("hello")
assert str_variant.s == "hello"
multi_field_struct_variant = enums.ComplexEnum.MultiFieldStruct(42, 3.14, True)
assert multi_field_struct_variant.a == 42
assert multi_field_struct_variant.b == 3.14
assert multi_field_struct_variant.c is True
variant_with_default = enums.ComplexEnum.VariantWithDefault()
assert variant_with_default.a == 42
assert variant_with_default.b is None
@pytest.mark.parametrize(
"variant",
[
enums.ComplexEnum.Int(42),
enums.ComplexEnum.Float(3.14),
enums.ComplexEnum.Str("hello"),
enums.ComplexEnum.EmptyStruct(),
enums.ComplexEnum.MultiFieldStruct(42, 3.14, True),
enums.ComplexEnum.VariantWithDefault(),
],
)
def test_complex_enum_desugared_match(variant: enums.ComplexEnum):
if isinstance(variant, enums.ComplexEnum.Int):
x = variant.i
assert x == 42
elif isinstance(variant, enums.ComplexEnum.Float):
x = variant.f
assert x == 3.14
elif isinstance(variant, enums.ComplexEnum.Str):
x = variant.s
assert x == "hello"
elif isinstance(variant, enums.ComplexEnum.EmptyStruct):
assert True
elif isinstance(variant, enums.ComplexEnum.MultiFieldStruct):
x = variant.a
y = variant.b
z = variant.c
assert x == 42
assert y == 3.14
assert z is True
elif isinstance(variant, enums.ComplexEnum.VariantWithDefault):
x = variant.a
y = variant.b
assert x == 42
assert y is None
else:
assert False
@pytest.mark.parametrize(
"variant",
[
enums.ComplexEnum.Int(42),
enums.ComplexEnum.Float(3.14),
enums.ComplexEnum.Str("hello"),
enums.ComplexEnum.EmptyStruct(),
enums.ComplexEnum.MultiFieldStruct(42, 3.14, True),
enums.ComplexEnum.VariantWithDefault(b="hello"),
],
)
def test_complex_enum_pyfunction_in_out_desugared_match(variant: enums.ComplexEnum):
variant = enums.do_complex_stuff(variant)
if isinstance(variant, enums.ComplexEnum.Int):
x = variant.i
assert x == 5
elif isinstance(variant, enums.ComplexEnum.Float):
x = variant.f
assert x == 9.8596
elif isinstance(variant, enums.ComplexEnum.Str):
x = variant.s
assert x == "42"
elif isinstance(variant, enums.ComplexEnum.EmptyStruct):
assert True
elif isinstance(variant, enums.ComplexEnum.MultiFieldStruct):
x = variant.a
y = variant.b
z = variant.c
assert x == 42
assert y == 3.14
assert z is True
elif isinstance(variant, enums.ComplexEnum.VariantWithDefault):
x = variant.a
y = variant.b
assert x == 84
assert y == "HELLO"
else:
assert False
def test_tuple_enum_variant_constructors():
tuple_variant = enums.TupleEnum.Full(42, 3.14, False)
assert isinstance(tuple_variant, enums.TupleEnum.Full)
empty_tuple_variant = enums.TupleEnum.EmptyTuple()
assert isinstance(empty_tuple_variant, enums.TupleEnum.EmptyTuple)
@pytest.mark.parametrize(
"variant",
[
enums.TupleEnum.FullWithDefault(),
enums.TupleEnum.Full(42, 3.14, False),
enums.TupleEnum.EmptyTuple(),
],
)
def test_tuple_enum_variant_subclasses(variant: enums.TupleEnum):
assert isinstance(variant, enums.TupleEnum)
def test_tuple_enum_defaults():
variant = enums.TupleEnum.FullWithDefault()
assert variant._0 == 1
assert variant._1 == 1.0
assert variant._2 is True
def test_tuple_enum_field_getters():
tuple_variant = enums.TupleEnum.Full(42, 3.14, False)
assert tuple_variant._0 == 42
assert tuple_variant._1 == 3.14
assert tuple_variant._2 is False
def test_tuple_enum_index_getter():
tuple_variant = enums.TupleEnum.Full(42, 3.14, False)
assert len(tuple_variant) == 3
assert tuple_variant[0] == 42
@pytest.mark.parametrize(
"variant",
[enums.MixedComplexEnum.Nothing()],
)
def test_mixed_complex_enum_pyfunction_instance_nothing(
variant: enums.MixedComplexEnum,
):
assert isinstance(variant, enums.MixedComplexEnum.Nothing)
assert isinstance(
enums.do_mixed_complex_stuff(variant), enums.MixedComplexEnum.Empty
)
@pytest.mark.parametrize(
"variant",
[enums.MixedComplexEnum.Empty()],
)
def test_mixed_complex_enum_pyfunction_instance_empty(variant: enums.MixedComplexEnum):
assert isinstance(variant, enums.MixedComplexEnum.Empty)
assert isinstance(
enums.do_mixed_complex_stuff(variant), enums.MixedComplexEnum.Nothing
)
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_othermod.py | from hypothesis import given, assume
from hypothesis import strategies as st
from pyo3_pytests import othermod
INTEGER32_ST = st.integers(min_value=(-(2**31)), max_value=(2**31 - 1))
USIZE_ST = st.integers(min_value=othermod.USIZE_MIN, max_value=othermod.USIZE_MAX)
@given(x=INTEGER32_ST)
def test_double(x):
expected = x * 2
assume(-(2**31) <= expected <= (2**31 - 1))
assert othermod.double(x) == expected
def test_modclass():
# Test that the repr of the class itself doesn't crash anything
repr(othermod.ModClass)
assert isinstance(othermod.ModClass, type)
def test_modclass_instance():
mi = othermod.ModClass()
repr(mi)
repr(mi.__class__)
assert isinstance(mi, othermod.ModClass)
assert isinstance(mi, object)
@given(x=USIZE_ST)
def test_modclas_noop(x):
mi = othermod.ModClass()
assert mi.noop(x) == x
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_dict_iter.py | import pytest
from pyo3_pytests.dict_iter import DictSize
@pytest.mark.parametrize("size", [64, 128, 256])
def test_size(size):
d = {}
for i in range(size):
d[i] = str(i)
assert DictSize(len(d)).iter_dict(d) == size
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_sequence.py | import pytest
from pyo3_pytests import sequence
def test_vec_from_list_i32():
assert sequence.vec_to_vec_i32([1, 2, 3]) == [1, 2, 3]
def test_vec_from_list_pystring():
assert sequence.vec_to_vec_pystring(["1", "2", "3"]) == ["1", "2", "3"]
def test_vec_from_bytes():
assert sequence.vec_to_vec_i32(b"123") == [49, 50, 51]
def test_vec_from_str():
with pytest.raises(TypeError):
sequence.vec_to_vec_pystring("123")
def test_vec_from_array():
# binary numpy wheel not available on all platforms
numpy = pytest.importorskip("numpy")
assert sequence.vec_to_vec_i32(numpy.array([1, 2, 3])) == [1, 2, 3]
def test_rust_array_from_array():
# binary numpy wheel not available on all platforms
numpy = pytest.importorskip("numpy")
assert sequence.array_to_array_i32(numpy.array([1, 2, 3])) == [1, 2, 3]
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_objstore.py | import gc
import sys
from pyo3_pytests.objstore import ObjStore
def test_objstore_doesnot_leak_memory():
N = 10000
message = b'\\(-"-;) Praying that memory leak would not happen..'
# PyPy does not have sys.getrefcount, provide a no-op lambda and don't
# check refcount on PyPy
getrefcount = getattr(sys, "getrefcount", lambda obj: 0)
if sys.implementation.name == "graalpy":
# GraalPy has an incomplete sys.getrefcount implementation
def getrefcount(obj):
return 0
before = getrefcount(message)
store = ObjStore()
for _ in range(N):
store.push(message)
del store
gc.collect()
after = getrefcount(message)
assert after - before == 0
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_misc.py | import importlib
import platform
import sys
import pyo3_pytests.misc
import pytest
if sys.version_info >= (3, 13):
subinterpreters = pytest.importorskip("_interpreters")
else:
subinterpreters = pytest.importorskip("_xxsubinterpreters")
def test_issue_219():
# Should not deadlock
pyo3_pytests.misc.issue_219()
@pytest.mark.xfail(
platform.python_implementation() == "CPython" and sys.version_info < (3, 9),
reason="Cannot identify subinterpreters on Python older than 3.9",
)
def test_multiple_imports_same_interpreter_ok():
spec = importlib.util.find_spec("pyo3_pytests.pyo3_pytests")
module = importlib.util.module_from_spec(spec)
assert dir(module) == dir(pyo3_pytests.pyo3_pytests)
@pytest.mark.xfail(
platform.python_implementation() == "CPython" and sys.version_info < (3, 9),
reason="Cannot identify subinterpreters on Python older than 3.9",
)
@pytest.mark.skipif(
platform.python_implementation() in ("PyPy", "GraalVM"),
reason="PyPy and GraalPy do not support subinterpreters",
)
def test_import_in_subinterpreter_forbidden():
sub_interpreter = subinterpreters.create()
if sys.version_info < (3, 12):
expected_error = "PyO3 modules do not yet support subinterpreters, see https://github.com/PyO3/pyo3/issues/576"
else:
expected_error = "module pyo3_pytests.pyo3_pytests does not support loading in subinterpreters"
if sys.version_info < (3, 13):
# Python 3.12 subinterpreters had a special error for this
with pytest.raises(
subinterpreters.RunFailedError,
match=expected_error,
):
subinterpreters.run_string(
sub_interpreter, "import pyo3_pytests.pyo3_pytests"
)
else:
res = subinterpreters.run_string(
sub_interpreter, "import pyo3_pytests.pyo3_pytests"
)
assert res.type.__name__ == "ImportError"
assert res.msg == expected_error
subinterpreters.destroy(sub_interpreter)
def test_type_fully_qualified_name_includes_module():
numpy = pytest.importorskip("numpy")
# For numpy 1.x and 2.x
assert pyo3_pytests.misc.get_type_fully_qualified_name(numpy.bool_(True)) in [
"numpy.bool",
"numpy.bool_",
]
def test_accepts_numpy_bool():
# binary numpy wheel not available on all platforms
numpy = pytest.importorskip("numpy")
assert pyo3_pytests.misc.accepts_bool(True) is True
assert pyo3_pytests.misc.accepts_bool(False) is False
assert pyo3_pytests.misc.accepts_bool(numpy.bool_(True)) is True
assert pyo3_pytests.misc.accepts_bool(numpy.bool_(False)) is False
class ArbitraryClass:
worker_id: int
iteration: int
def __init__(self, worker_id: int, iteration: int):
self.worker_id = worker_id
self.iteration = iteration
def __repr__(self):
return f"ArbitraryClass({self.worker_id}, {self.iteration})"
def __del__(self):
print("del", self.worker_id, self.iteration)
def test_gevent():
gevent = pytest.importorskip("gevent")
def worker(worker_id: int) -> None:
for iteration in range(2):
d = {"key": ArbitraryClass(worker_id, iteration)}
def arbitrary_python_code():
# remove the dictionary entry so that the class value can be
# garbage collected
del d["key"]
print("gevent sleep", worker_id, iteration)
gevent.sleep(0)
print("after gevent sleep", worker_id, iteration)
print("start", worker_id, iteration)
pyo3_pytests.misc.get_item_and_run_callback(d, arbitrary_python_code)
print("end", worker_id, iteration)
workers = [gevent.spawn(worker, i) for i in range(2)]
gevent.joinall(workers)
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_subclassing.py | from pyo3_pytests.subclassing import Subclassable
class SomeSubClass(Subclassable):
def __str__(self):
return "SomeSubclass"
def test_subclassing():
a = SomeSubClass()
assert str(a) == "SomeSubclass"
assert type(a) is SomeSubClass
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_datetime.py | import datetime as pdt
import platform
import re
import struct
import sys
import pyo3_pytests.datetime as rdt
import pytest
from hypothesis import example, given
from hypothesis import strategies as st
# Constants
def _get_utc():
timezone = getattr(pdt, "timezone", None)
if timezone:
return timezone.utc
else:
class UTC(pdt.tzinfo):
def utcoffset(self, dt):
return pdt.timedelta(0)
def dst(self, dt):
return pdt.timedelta(0)
def tzname(self, dt):
return "UTC"
return UTC()
UTC = _get_utc()
MAX_SECONDS = int(pdt.timedelta.max.total_seconds())
MIN_SECONDS = int(pdt.timedelta.min.total_seconds())
MAX_DAYS = pdt.timedelta.max // pdt.timedelta(days=1)
MIN_DAYS = pdt.timedelta.min // pdt.timedelta(days=1)
MAX_MICROSECONDS = int(pdt.timedelta.max.total_seconds() * 1e6)
MIN_MICROSECONDS = int(pdt.timedelta.min.total_seconds() * 1e6)
# The reason we don't use platform.architecture() here is that it's not
# reliable on macOS. See https://stackoverflow.com/a/1405971/823869. Similarly,
# sys.maxsize is not reliable on Windows. See
# https://stackoverflow.com/questions/1405913/how-do-i-determine-if-my-python-shell-is-executing-in-32bit-or-64bit-mode-on-os/1405971#comment6209952_1405971
# and https://stackoverflow.com/a/3411134/823869.
_pointer_size = struct.calcsize("P")
if _pointer_size == 8:
IS_32_BIT = False
elif _pointer_size == 4:
IS_32_BIT = True
else:
raise RuntimeError("unexpected pointer size: " + repr(_pointer_size))
IS_WINDOWS = sys.platform == "win32"
if IS_WINDOWS:
MIN_DATETIME = pdt.datetime(1970, 1, 1, 0, 0, 0)
if IS_32_BIT:
MAX_DATETIME = pdt.datetime(2038, 1, 18, 23, 59, 59)
else:
MAX_DATETIME = pdt.datetime(3000, 12, 31, 23, 59, 59)
else:
if IS_32_BIT:
# TS ±2147483648 (2**31)
MIN_DATETIME = pdt.datetime(1901, 12, 13, 20, 45, 52)
MAX_DATETIME = pdt.datetime(2038, 1, 19, 3, 14, 8)
else:
MIN_DATETIME = pdt.datetime(1, 1, 2, 0, 0)
MAX_DATETIME = pdt.datetime(9999, 12, 31, 18, 59, 59)
PYPY = platform.python_implementation() == "PyPy"
# Tests
def test_date():
assert rdt.make_date(2017, 9, 1) == pdt.date(2017, 9, 1)
@given(d=st.dates())
def test_date_accessors(d):
act = rdt.get_date_tuple(d)
exp = (d.year, d.month, d.day)
assert act == exp
def test_invalid_date_fails():
with pytest.raises(ValueError):
rdt.make_date(2017, 2, 30)
@given(d=st.dates(MIN_DATETIME.date(), MAX_DATETIME.date()))
def test_date_from_timestamp(d):
try:
ts = pdt.datetime.timestamp(d)
except Exception:
# out of range for timestamp
return
try:
expected = pdt.date.fromtimestamp(ts)
except Exception as pdt_fail:
# date from timestamp failed; expect the same from Rust binding
with pytest.raises(type(pdt_fail)) as exc_info:
rdt.date_from_timestamp(ts)
assert str(exc_info.value) == str(pdt_fail)
else:
assert rdt.date_from_timestamp(int(ts)) == expected
@pytest.mark.parametrize(
"args, kwargs",
[
((0, 0, 0, 0, None), {}),
((1, 12, 14, 124731), {}),
((1, 12, 14, 124731), {"tzinfo": UTC}),
],
)
def test_time(args, kwargs):
act = rdt.make_time(*args, **kwargs)
exp = pdt.time(*args, **kwargs)
assert act == exp
assert act.tzinfo is exp.tzinfo
assert rdt.get_time_tzinfo(act) == exp.tzinfo
@given(t=st.times())
def test_time_hypothesis(t):
act = rdt.get_time_tuple(t)
exp = (t.hour, t.minute, t.second, t.microsecond)
assert act == exp
@given(t=st.times())
def test_time_tuple_fold(t):
t_nofold = t.replace(fold=0)
t_fold = t.replace(fold=1)
for t in (t_nofold, t_fold):
act = rdt.get_time_tuple_fold(t)
exp = (t.hour, t.minute, t.second, t.microsecond, t.fold)
assert act == exp
@pytest.mark.parametrize("fold", [False, True])
def test_time_with_fold(fold):
t = rdt.time_with_fold(0, 0, 0, 0, None, fold)
assert t.fold == fold
@pytest.mark.parametrize(
"args", [(-1, 0, 0, 0), (0, -1, 0, 0), (0, 0, -1, 0), (0, 0, 0, -1)]
)
def test_invalid_time_fails_overflow(args):
with pytest.raises(OverflowError):
rdt.make_time(*args)
@pytest.mark.parametrize(
"args",
[
(24, 0, 0, 0),
(25, 0, 0, 0),
(0, 60, 0, 0),
(0, 61, 0, 0),
(0, 0, 60, 0),
(0, 0, 61, 0),
(0, 0, 0, 1000000),
],
)
def test_invalid_time_fails(args):
with pytest.raises(ValueError):
rdt.make_time(*args)
@pytest.mark.parametrize(
"args",
[
("0", 0, 0, 0),
(0, "0", 0, 0),
(0, 0, "0", 0),
(0, 0, 0, "0"),
(0, 0, 0, 0, "UTC"),
],
)
def test_time_typeerror(args):
with pytest.raises(TypeError):
rdt.make_time(*args)
@pytest.mark.parametrize(
"args, kwargs",
[((2017, 9, 1, 12, 45, 30, 0), {}), ((2017, 9, 1, 12, 45, 30, 0), {"tzinfo": UTC})],
)
def test_datetime(args, kwargs):
act = rdt.make_datetime(*args, **kwargs)
exp = pdt.datetime(*args, **kwargs)
assert act == exp
assert act.tzinfo is exp.tzinfo
assert rdt.get_datetime_tzinfo(act) == exp.tzinfo
@given(dt=st.datetimes())
def test_datetime_tuple(dt):
act = rdt.get_datetime_tuple(dt)
exp = dt.timetuple()[0:6] + (dt.microsecond,)
assert act == exp
@given(dt=st.datetimes())
def test_datetime_tuple_fold(dt):
dt_fold = dt.replace(fold=1)
dt_nofold = dt.replace(fold=0)
for dt in (dt_fold, dt_nofold):
act = rdt.get_datetime_tuple_fold(dt)
exp = dt.timetuple()[0:6] + (dt.microsecond, dt.fold)
assert act == exp
def test_invalid_datetime_fails():
with pytest.raises(ValueError):
rdt.make_datetime(2011, 1, 42, 0, 0, 0, 0)
def test_datetime_typeerror():
with pytest.raises(TypeError):
rdt.make_datetime("2011", 1, 1, 0, 0, 0, 0)
@given(dt=st.datetimes(MIN_DATETIME, MAX_DATETIME))
@example(dt=pdt.datetime(1971, 1, 2, 0, 0))
def test_datetime_from_timestamp(dt):
try:
ts = pdt.datetime.timestamp(dt)
except Exception:
# out of range for timestamp
return
try:
expected = pdt.datetime.fromtimestamp(ts)
except Exception as pdt_fail:
# datetime from timestamp failed; expect the same from Rust binding
with pytest.raises(type(pdt_fail)) as exc_info:
rdt.datetime_from_timestamp(ts)
assert str(exc_info.value) == str(pdt_fail)
else:
assert rdt.datetime_from_timestamp(ts) == expected
def test_datetime_from_timestamp_tzinfo():
d1 = rdt.datetime_from_timestamp(0, tz=UTC)
d2 = rdt.datetime_from_timestamp(0, tz=UTC)
assert d1 == d2
assert d1.tzinfo is d2.tzinfo
@pytest.mark.parametrize(
"args",
[
(0, 0, 0),
(1, 0, 0),
(-1, 0, 0),
(0, 1, 0),
(0, -1, 0),
(1, -1, 0),
(-1, 1, 0),
(0, 0, 123456),
(0, 0, -123456),
],
)
def test_delta(args):
act = pdt.timedelta(*args)
exp = rdt.make_delta(*args)
assert act == exp
@given(td=st.timedeltas())
def test_delta_accessors(td):
act = rdt.get_delta_tuple(td)
exp = (td.days, td.seconds, td.microseconds)
assert act == exp
@pytest.mark.parametrize(
"args,err_type",
[
((MAX_DAYS + 1, 0, 0), OverflowError),
((MIN_DAYS - 1, 0, 0), OverflowError),
((0, MAX_SECONDS + 1, 0), OverflowError),
((0, MIN_SECONDS - 1, 0), OverflowError),
((0, 0, MAX_MICROSECONDS + 1), OverflowError),
((0, 0, MIN_MICROSECONDS - 1), OverflowError),
(("0", 0, 0), TypeError),
((0, "0", 0), TypeError),
((0, 0, "0"), TypeError),
],
)
def test_delta_err(args, err_type):
with pytest.raises(err_type):
rdt.make_delta(*args)
def test_tz_class():
tzi = rdt.TzClass()
dt = pdt.datetime(2018, 1, 1, tzinfo=tzi)
assert dt.tzname() == "+01:00"
assert dt.utcoffset() == pdt.timedelta(hours=1)
assert dt.dst() is None
def test_tz_class_introspection():
tzi = rdt.TzClass()
assert tzi.__class__ == rdt.TzClass
# PyPy generates <importlib.bootstrap.TzClass ...> for some reason.
assert re.match(r"^<[\w\.]*TzClass object at", repr(tzi))
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/tests/test_pyfunctions.py | from pyo3_pytests import pyfunctions
def none_py():
return None
def test_none_py(benchmark):
benchmark(none_py)
def test_none_rs(benchmark):
rust = benchmark(pyfunctions.none)
py = none_py()
assert rust == py
def simple_py(a, b=None, *, c=None):
return a, b, c
def test_simple_py(benchmark):
benchmark(simple_py, 1, "foo", c={1: 2})
def test_simple_rs(benchmark):
rust = benchmark(pyfunctions.simple, 1, "foo", c={1: 2})
py = simple_py(1, "foo", c={1: 2})
assert rust == py
def simple_args_py(a, b=None, *args, c=None):
return a, b, args, c
def test_simple_args_py(benchmark):
benchmark(simple_args_py, 1, "foo", 4, 5, 6, c={1: 2})
def test_simple_args_rs(benchmark):
rust = benchmark(pyfunctions.simple_args, 1, "foo", 4, 5, 6, c={1: 2})
py = simple_args_py(1, "foo", 4, 5, 6, c={1: 2})
assert rust == py
def simple_kwargs_py(a, b=None, c=None, **kwargs):
return a, b, c, kwargs
def test_simple_kwargs_py(benchmark):
benchmark(simple_kwargs_py, 1, "foo", c={1: 2}, bar=4, foo=10)
def test_simple_kwargs_rs(benchmark):
rust = benchmark(pyfunctions.simple_kwargs, 1, "foo", c={1: 2}, bar=4, foo=10)
py = simple_kwargs_py(1, "foo", c={1: 2}, bar=4, foo=10)
assert rust == py
def simple_args_kwargs_py(a, b=None, *args, c=None, **kwargs):
return (a, b, args, c, kwargs)
def test_simple_args_kwargs_py(benchmark):
benchmark(simple_args_kwargs_py, 1, "foo", "baz", bar=4, foo=10)
def test_simple_args_kwargs_rs(benchmark):
rust = benchmark(pyfunctions.simple_args_kwargs, 1, "foo", "baz", bar=4, foo=10)
py = simple_args_kwargs_py(1, "foo", "baz", bar=4, foo=10)
assert rust == py
def args_kwargs_py(*args, **kwargs):
return (args, kwargs)
def test_args_kwargs_py(benchmark):
benchmark(args_kwargs_py, 1, "foo", {1: 2}, bar=4, foo=10)
def test_args_kwargs_rs(benchmark):
rust = benchmark(pyfunctions.args_kwargs, 1, "foo", {1: 2}, bar=4, foo=10)
py = args_kwargs_py(1, "foo", {1: 2}, bar=4, foo=10)
assert rust == py
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/path.rs | use pyo3::prelude::*;
use std::path::{Path, PathBuf};
#[pyfunction]
fn make_path() -> PathBuf {
Path::new("/root").to_owned()
}
#[pyfunction]
fn take_pathbuf(path: PathBuf) -> PathBuf {
path
}
#[pymodule(gil_used = false)]
pub fn path(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(make_path, m)?)?;
m.add_function(wrap_pyfunction!(take_pathbuf, m)?)?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/pyclasses.rs | use std::{thread, time};
use pyo3::exceptions::{PyStopIteration, PyValueError};
use pyo3::prelude::*;
use pyo3::types::PyType;
#[pyclass]
struct EmptyClass {}
#[pymethods]
impl EmptyClass {
#[new]
fn new() -> Self {
EmptyClass {}
}
fn method(&self) {}
fn __len__(&self) -> usize {
0
}
}
/// This is for demonstrating how to return a value from __next__
#[pyclass]
#[derive(Default)]
struct PyClassIter {
count: usize,
}
#[pymethods]
impl PyClassIter {
#[new]
pub fn new() -> Self {
Default::default()
}
fn __next__(&mut self) -> PyResult<usize> {
if self.count < 5 {
self.count += 1;
Ok(self.count)
} else {
Err(PyStopIteration::new_err("Ended"))
}
}
}
#[pyclass]
#[derive(Default)]
struct PyClassThreadIter {
count: usize,
}
#[pymethods]
impl PyClassThreadIter {
#[new]
pub fn new() -> Self {
Default::default()
}
fn __next__(&mut self, py: Python<'_>) -> usize {
let current_count = self.count;
self.count += 1;
if current_count == 0 {
py.allow_threads(|| thread::sleep(time::Duration::from_millis(100)));
}
self.count
}
}
/// Demonstrates a base class which can operate on the relevant subclass in its constructor.
#[pyclass(subclass)]
#[derive(Clone, Debug)]
struct AssertingBaseClass;
#[pymethods]
impl AssertingBaseClass {
#[new]
#[classmethod]
fn new(cls: &Bound<'_, PyType>, expected_type: Bound<'_, PyType>) -> PyResult<Self> {
if !cls.is(&expected_type) {
return Err(PyValueError::new_err(format!(
"{:?} != {:?}",
cls, expected_type
)));
}
Ok(Self)
}
}
#[pyclass]
struct ClassWithoutConstructor;
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
#[pyclass(dict)]
struct ClassWithDict;
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
#[pymethods]
impl ClassWithDict {
#[new]
fn new() -> Self {
ClassWithDict
}
}
#[pymodule(gil_used = false)]
pub fn pyclasses(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<EmptyClass>()?;
m.add_class::<PyClassIter>()?;
m.add_class::<PyClassThreadIter>()?;
m.add_class::<AssertingBaseClass>()?;
m.add_class::<ClassWithoutConstructor>()?;
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
m.add_class::<ClassWithDict>()?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/enums.rs | use pyo3::{
pyclass, pyfunction, pymodule,
types::{PyModule, PyModuleMethods},
wrap_pyfunction, Bound, PyResult,
};
#[pymodule(gil_used = false)]
pub fn enums(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<SimpleEnum>()?;
m.add_class::<ComplexEnum>()?;
m.add_class::<SimpleTupleEnum>()?;
m.add_class::<TupleEnum>()?;
m.add_class::<MixedComplexEnum>()?;
m.add_wrapped(wrap_pyfunction!(do_simple_stuff))?;
m.add_wrapped(wrap_pyfunction!(do_complex_stuff))?;
m.add_wrapped(wrap_pyfunction!(do_tuple_stuff))?;
m.add_wrapped(wrap_pyfunction!(do_mixed_complex_stuff))?;
Ok(())
}
#[pyclass(eq, eq_int)]
#[derive(PartialEq)]
pub enum SimpleEnum {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
#[pyfunction]
pub fn do_simple_stuff(thing: &SimpleEnum) -> SimpleEnum {
match thing {
SimpleEnum::Sunday => SimpleEnum::Monday,
SimpleEnum::Monday => SimpleEnum::Tuesday,
SimpleEnum::Tuesday => SimpleEnum::Wednesday,
SimpleEnum::Wednesday => SimpleEnum::Thursday,
SimpleEnum::Thursday => SimpleEnum::Friday,
SimpleEnum::Friday => SimpleEnum::Saturday,
SimpleEnum::Saturday => SimpleEnum::Sunday,
}
}
#[pyclass]
pub enum ComplexEnum {
Int {
i: i32,
},
Float {
f: f64,
},
Str {
s: String,
},
EmptyStruct {},
MultiFieldStruct {
a: i32,
b: f64,
c: bool,
},
#[pyo3(constructor = (a = 42, b = None))]
VariantWithDefault {
a: i32,
b: Option<String>,
},
}
#[pyfunction]
pub fn do_complex_stuff(thing: &ComplexEnum) -> ComplexEnum {
match thing {
ComplexEnum::Int { i } => ComplexEnum::Str { s: i.to_string() },
ComplexEnum::Float { f } => ComplexEnum::Float { f: f * f },
ComplexEnum::Str { s } => ComplexEnum::Int { i: s.len() as i32 },
ComplexEnum::EmptyStruct {} => ComplexEnum::EmptyStruct {},
ComplexEnum::MultiFieldStruct { a, b, c } => ComplexEnum::MultiFieldStruct {
a: *a,
b: *b,
c: *c,
},
ComplexEnum::VariantWithDefault { a, b } => ComplexEnum::VariantWithDefault {
a: 2 * a,
b: b.as_ref().map(|s| s.to_uppercase()),
},
}
}
#[pyclass]
enum SimpleTupleEnum {
Int(i32),
Str(String),
}
#[pyclass]
pub enum TupleEnum {
#[pyo3(constructor = (_0 = 1, _1 = 1.0, _2 = true))]
FullWithDefault(i32, f64, bool),
Full(i32, f64, bool),
EmptyTuple(),
}
#[pyfunction]
pub fn do_tuple_stuff(thing: &TupleEnum) -> TupleEnum {
match thing {
TupleEnum::FullWithDefault(a, b, c) => TupleEnum::FullWithDefault(*a, *b, *c),
TupleEnum::Full(a, b, c) => TupleEnum::Full(*a, *b, *c),
TupleEnum::EmptyTuple() => TupleEnum::EmptyTuple(),
}
}
#[pyclass]
pub enum MixedComplexEnum {
Nothing {},
Empty(),
}
#[pyfunction]
pub fn do_mixed_complex_stuff(thing: &MixedComplexEnum) -> MixedComplexEnum {
match thing {
MixedComplexEnum::Nothing {} => MixedComplexEnum::Empty(),
MixedComplexEnum::Empty() => MixedComplexEnum::Nothing {},
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/pyfunctions.rs | use pyo3::prelude::*;
use pyo3::types::{PyDict, PyTuple};
#[pyfunction(signature = ())]
fn none() {}
type Any<'py> = Bound<'py, PyAny>;
type Dict<'py> = Bound<'py, PyDict>;
type Tuple<'py> = Bound<'py, PyTuple>;
#[pyfunction(signature = (a, b = None, *, c = None))]
fn simple<'py>(
a: Any<'py>,
b: Option<Any<'py>>,
c: Option<Any<'py>>,
) -> (Any<'py>, Option<Any<'py>>, Option<Any<'py>>) {
(a, b, c)
}
#[pyfunction(signature = (a, b = None, *args, c = None))]
fn simple_args<'py>(
a: Any<'py>,
b: Option<Any<'py>>,
args: Tuple<'py>,
c: Option<Any<'py>>,
) -> (Any<'py>, Option<Any<'py>>, Tuple<'py>, Option<Any<'py>>) {
(a, b, args, c)
}
#[pyfunction(signature = (a, b = None, c = None, **kwargs))]
fn simple_kwargs<'py>(
a: Any<'py>,
b: Option<Any<'py>>,
c: Option<Any<'py>>,
kwargs: Option<Dict<'py>>,
) -> (
Any<'py>,
Option<Any<'py>>,
Option<Any<'py>>,
Option<Dict<'py>>,
) {
(a, b, c, kwargs)
}
#[pyfunction(signature = (a, b = None, *args, c = None, **kwargs))]
fn simple_args_kwargs<'py>(
a: Any<'py>,
b: Option<Any<'py>>,
args: Tuple<'py>,
c: Option<Any<'py>>,
kwargs: Option<Dict<'py>>,
) -> (
Any<'py>,
Option<Any<'py>>,
Tuple<'py>,
Option<Any<'py>>,
Option<Dict<'py>>,
) {
(a, b, args, c, kwargs)
}
#[pyfunction(signature = (*args, **kwargs))]
fn args_kwargs<'py>(
args: Tuple<'py>,
kwargs: Option<Dict<'py>>,
) -> (Tuple<'py>, Option<Dict<'py>>) {
(args, kwargs)
}
#[pymodule(gil_used = false)]
pub fn pyfunctions(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(none, m)?)?;
m.add_function(wrap_pyfunction!(simple, m)?)?;
m.add_function(wrap_pyfunction!(simple_args, m)?)?;
m.add_function(wrap_pyfunction!(simple_kwargs, m)?)?;
m.add_function(wrap_pyfunction!(simple_args_kwargs, m)?)?;
m.add_function(wrap_pyfunction!(args_kwargs, m)?)?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/misc.rs | use pyo3::{
prelude::*,
types::{PyDict, PyString},
};
#[pyfunction]
fn issue_219() {
// issue 219: acquiring GIL inside #[pyfunction] deadlocks.
Python::with_gil(|_| {});
}
#[pyfunction]
fn get_type_fully_qualified_name<'py>(obj: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyString>> {
obj.get_type().fully_qualified_name()
}
#[pyfunction]
fn accepts_bool(val: bool) -> bool {
val
}
#[pyfunction]
fn get_item_and_run_callback(dict: Bound<'_, PyDict>, callback: Bound<'_, PyAny>) -> PyResult<()> {
// This function gives the opportunity to run a pure-Python callback so that
// gevent can instigate a context switch. This had problematic interactions
// with PyO3's removed "GIL Pool".
// For context, see https://github.com/PyO3/pyo3/issues/3668
let item = dict.get_item("key")?.expect("key not found in dict");
let string = item.to_string();
callback.call0()?;
assert_eq!(item.to_string(), string);
Ok(())
}
#[pymodule(gil_used = false)]
pub fn misc(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(issue_219, m)?)?;
m.add_function(wrap_pyfunction!(get_type_fully_qualified_name, m)?)?;
m.add_function(wrap_pyfunction!(accepts_bool, m)?)?;
m.add_function(wrap_pyfunction!(get_item_and_run_callback, m)?)?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/sequence.rs | use pyo3::prelude::*;
use pyo3::types::PyString;
#[pyfunction]
fn vec_to_vec_i32(vec: Vec<i32>) -> Vec<i32> {
vec
}
#[pyfunction]
fn array_to_array_i32(arr: [i32; 3]) -> [i32; 3] {
arr
}
#[pyfunction]
fn vec_to_vec_pystring(vec: Vec<Bound<'_, PyString>>) -> Vec<Bound<'_, PyString>> {
vec
}
#[pymodule(gil_used = false)]
pub fn sequence(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(vec_to_vec_i32, m)?)?;
m.add_function(wrap_pyfunction!(array_to_array_i32, m)?)?;
m.add_function(wrap_pyfunction!(vec_to_vec_pystring, m)?)?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/subclassing.rs | //! Test for [#220](https://github.com/PyO3/pyo3/issues/220)
use pyo3::prelude::*;
#[pyclass(subclass)]
pub struct Subclassable {}
#[pymethods]
impl Subclassable {
#[new]
fn new() -> Self {
Subclassable {}
}
fn __str__(&self) -> &'static str {
"Subclassable"
}
}
#[pymodule(gil_used = false)]
pub fn subclassing(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Subclassable>()?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/buf_and_str.rs | #![cfg(not(Py_LIMITED_API))]
//! Objects related to PyBuffer and PyStr
use pyo3::buffer::PyBuffer;
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyMemoryView, PyString};
/// This is for confirming that PyBuffer does not cause memory leak
#[pyclass]
struct BytesExtractor {}
#[pymethods]
impl BytesExtractor {
#[new]
pub fn __new__() -> Self {
BytesExtractor {}
}
#[staticmethod]
pub fn from_bytes(bytes: &Bound<'_, PyBytes>) -> PyResult<usize> {
let byte_vec: Vec<u8> = bytes.extract()?;
Ok(byte_vec.len())
}
#[staticmethod]
pub fn from_str(string: &Bound<'_, PyString>) -> PyResult<usize> {
let rust_string: String = string.extract()?;
Ok(rust_string.len())
}
#[staticmethod]
pub fn from_str_lossy(string: &Bound<'_, PyString>) -> usize {
let rust_string_lossy: String = string.to_string_lossy().to_string();
rust_string_lossy.len()
}
#[staticmethod]
pub fn from_buffer(buf: &Bound<'_, PyAny>) -> PyResult<usize> {
let buf = PyBuffer::<u8>::get(buf)?;
Ok(buf.item_count())
}
}
#[pyfunction]
fn return_memoryview(py: Python<'_>) -> PyResult<Bound<'_, PyMemoryView>> {
let bytes = PyBytes::new(py, b"hello world");
PyMemoryView::from(&bytes)
}
#[pymodule(gil_used = false)]
pub fn buf_and_str(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<BytesExtractor>()?;
m.add_function(wrap_pyfunction!(return_memoryview, m)?)?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/othermod.rs | //! <https://github.com/PyO3/pyo3/issues/233>
//!
//! The code below just tries to use the most important code generation paths
use pyo3::prelude::*;
#[pyclass]
pub struct ModClass {
_somefield: String,
}
#[pymethods]
impl ModClass {
#[new]
fn new() -> Self {
ModClass {
_somefield: String::from("contents"),
}
}
fn noop(&self, x: usize) -> usize {
x
}
}
#[pyfunction]
fn double(x: i32) -> i32 {
x * 2
}
#[pymodule(gil_used = false)]
pub fn othermod(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(double, m)?)?;
m.add_class::<ModClass>()?;
m.add("USIZE_MIN", usize::MIN)?;
m.add("USIZE_MAX", usize::MAX)?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/datetime.rs | #![cfg(not(Py_LIMITED_API))]
use pyo3::prelude::*;
use pyo3::types::{
PyDate, PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess, PyTime, PyTimeAccess, PyTuple,
PyTzInfo, PyTzInfoAccess,
};
#[pyfunction]
fn make_date(py: Python<'_>, year: i32, month: u8, day: u8) -> PyResult<Bound<'_, PyDate>> {
PyDate::new(py, year, month, day)
}
#[pyfunction]
fn get_date_tuple<'py>(d: &Bound<'py, PyDate>) -> PyResult<Bound<'py, PyTuple>> {
PyTuple::new(
d.py(),
[d.get_year(), d.get_month() as i32, d.get_day() as i32],
)
}
#[pyfunction]
fn date_from_timestamp(py: Python<'_>, timestamp: i64) -> PyResult<Bound<'_, PyDate>> {
PyDate::from_timestamp(py, timestamp)
}
#[pyfunction]
#[pyo3(signature=(hour, minute, second, microsecond, tzinfo=None))]
fn make_time<'py>(
py: Python<'py>,
hour: u8,
minute: u8,
second: u8,
microsecond: u32,
tzinfo: Option<&Bound<'py, PyTzInfo>>,
) -> PyResult<Bound<'py, PyTime>> {
PyTime::new(py, hour, minute, second, microsecond, tzinfo)
}
#[pyfunction]
#[pyo3(signature = (hour, minute, second, microsecond, tzinfo, fold))]
fn time_with_fold<'py>(
py: Python<'py>,
hour: u8,
minute: u8,
second: u8,
microsecond: u32,
tzinfo: Option<&Bound<'py, PyTzInfo>>,
fold: bool,
) -> PyResult<Bound<'py, PyTime>> {
PyTime::new_with_fold(py, hour, minute, second, microsecond, tzinfo, fold)
}
#[pyfunction]
fn get_time_tuple<'py>(dt: &Bound<'py, PyTime>) -> PyResult<Bound<'py, PyTuple>> {
PyTuple::new(
dt.py(),
[
dt.get_hour() as u32,
dt.get_minute() as u32,
dt.get_second() as u32,
dt.get_microsecond(),
],
)
}
#[pyfunction]
fn get_time_tuple_fold<'py>(dt: &Bound<'py, PyTime>) -> PyResult<Bound<'py, PyTuple>> {
PyTuple::new(
dt.py(),
[
dt.get_hour() as u32,
dt.get_minute() as u32,
dt.get_second() as u32,
dt.get_microsecond(),
dt.get_fold() as u32,
],
)
}
#[pyfunction]
fn make_delta(
py: Python<'_>,
days: i32,
seconds: i32,
microseconds: i32,
) -> PyResult<Bound<'_, PyDelta>> {
PyDelta::new(py, days, seconds, microseconds, true)
}
#[pyfunction]
fn get_delta_tuple<'py>(delta: &Bound<'py, PyDelta>) -> PyResult<Bound<'py, PyTuple>> {
PyTuple::new(
delta.py(),
[
delta.get_days(),
delta.get_seconds(),
delta.get_microseconds(),
],
)
}
#[allow(clippy::too_many_arguments)]
#[pyfunction]
#[pyo3(signature=(year, month, day, hour, minute, second, microsecond, tzinfo=None))]
fn make_datetime<'py>(
py: Python<'py>,
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
microsecond: u32,
tzinfo: Option<&Bound<'py, PyTzInfo>>,
) -> PyResult<Bound<'py, PyDateTime>> {
PyDateTime::new(
py,
year,
month,
day,
hour,
minute,
second,
microsecond,
tzinfo,
)
}
#[pyfunction]
fn get_datetime_tuple<'py>(dt: &Bound<'py, PyDateTime>) -> PyResult<Bound<'py, PyTuple>> {
PyTuple::new(
dt.py(),
[
dt.get_year(),
dt.get_month() as i32,
dt.get_day() as i32,
dt.get_hour() as i32,
dt.get_minute() as i32,
dt.get_second() as i32,
dt.get_microsecond() as i32,
],
)
}
#[pyfunction]
fn get_datetime_tuple_fold<'py>(dt: &Bound<'py, PyDateTime>) -> PyResult<Bound<'py, PyTuple>> {
PyTuple::new(
dt.py(),
[
dt.get_year(),
dt.get_month() as i32,
dt.get_day() as i32,
dt.get_hour() as i32,
dt.get_minute() as i32,
dt.get_second() as i32,
dt.get_microsecond() as i32,
dt.get_fold() as i32,
],
)
}
#[pyfunction]
#[pyo3(signature=(ts, tz=None))]
fn datetime_from_timestamp<'py>(
py: Python<'py>,
ts: f64,
tz: Option<&Bound<'py, PyTzInfo>>,
) -> PyResult<Bound<'py, PyDateTime>> {
PyDateTime::from_timestamp(py, ts, tz)
}
#[pyfunction]
fn get_datetime_tzinfo<'py>(dt: &Bound<'py, PyDateTime>) -> Option<Bound<'py, PyTzInfo>> {
dt.get_tzinfo()
}
#[pyfunction]
fn get_time_tzinfo<'py>(dt: &Bound<'py, PyTime>) -> Option<Bound<'py, PyTzInfo>> {
dt.get_tzinfo()
}
#[pyclass(extends=PyTzInfo)]
pub struct TzClass {}
#[pymethods]
impl TzClass {
#[new]
fn new() -> Self {
TzClass {}
}
fn utcoffset<'py>(&self, dt: &Bound<'py, PyDateTime>) -> PyResult<Bound<'py, PyDelta>> {
PyDelta::new(dt.py(), 0, 3600, 0, true)
}
fn tzname(&self, _dt: &Bound<'_, PyDateTime>) -> String {
String::from("+01:00")
}
fn dst<'py>(&self, _dt: &Bound<'py, PyDateTime>) -> Option<Bound<'py, PyDelta>> {
None
}
}
#[pymodule(gil_used = false)]
pub fn datetime(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(make_date, m)?)?;
m.add_function(wrap_pyfunction!(get_date_tuple, m)?)?;
m.add_function(wrap_pyfunction!(date_from_timestamp, m)?)?;
m.add_function(wrap_pyfunction!(make_time, m)?)?;
m.add_function(wrap_pyfunction!(get_time_tuple, m)?)?;
m.add_function(wrap_pyfunction!(make_delta, m)?)?;
m.add_function(wrap_pyfunction!(get_delta_tuple, m)?)?;
m.add_function(wrap_pyfunction!(make_datetime, m)?)?;
m.add_function(wrap_pyfunction!(get_datetime_tuple, m)?)?;
m.add_function(wrap_pyfunction!(datetime_from_timestamp, m)?)?;
m.add_function(wrap_pyfunction!(get_datetime_tzinfo, m)?)?;
m.add_function(wrap_pyfunction!(get_time_tzinfo, m)?)?;
m.add_function(wrap_pyfunction!(time_with_fold, m)?)?;
m.add_function(wrap_pyfunction!(get_time_tuple_fold, m)?)?;
m.add_function(wrap_pyfunction!(get_datetime_tuple_fold, m)?)?;
m.add_class::<TzClass>()?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/lib.rs | use pyo3::prelude::*;
use pyo3::types::PyDict;
use pyo3::wrap_pymodule;
pub mod awaitable;
pub mod buf_and_str;
pub mod comparisons;
pub mod datetime;
pub mod dict_iter;
pub mod enums;
pub mod misc;
pub mod objstore;
pub mod othermod;
pub mod path;
pub mod pyclasses;
pub mod pyfunctions;
pub mod sequence;
pub mod subclassing;
#[pymodule(gil_used = false)]
fn pyo3_pytests(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_wrapped(wrap_pymodule!(awaitable::awaitable))?;
#[cfg(not(Py_LIMITED_API))]
m.add_wrapped(wrap_pymodule!(buf_and_str::buf_and_str))?;
m.add_wrapped(wrap_pymodule!(comparisons::comparisons))?;
#[cfg(not(Py_LIMITED_API))]
m.add_wrapped(wrap_pymodule!(datetime::datetime))?;
m.add_wrapped(wrap_pymodule!(dict_iter::dict_iter))?;
m.add_wrapped(wrap_pymodule!(enums::enums))?;
m.add_wrapped(wrap_pymodule!(misc::misc))?;
m.add_wrapped(wrap_pymodule!(objstore::objstore))?;
m.add_wrapped(wrap_pymodule!(othermod::othermod))?;
m.add_wrapped(wrap_pymodule!(path::path))?;
m.add_wrapped(wrap_pymodule!(pyclasses::pyclasses))?;
m.add_wrapped(wrap_pymodule!(pyfunctions::pyfunctions))?;
m.add_wrapped(wrap_pymodule!(sequence::sequence))?;
m.add_wrapped(wrap_pymodule!(subclassing::subclassing))?;
// Inserting to sys.modules allows importing submodules nicely from Python
// e.g. import pyo3_pytests.buf_and_str as bas
let sys = PyModule::import(py, "sys")?;
let sys_modules = sys.getattr("modules")?.downcast_into::<PyDict>()?;
sys_modules.set_item("pyo3_pytests.awaitable", m.getattr("awaitable")?)?;
sys_modules.set_item("pyo3_pytests.buf_and_str", m.getattr("buf_and_str")?)?;
sys_modules.set_item("pyo3_pytests.comparisons", m.getattr("comparisons")?)?;
sys_modules.set_item("pyo3_pytests.datetime", m.getattr("datetime")?)?;
sys_modules.set_item("pyo3_pytests.dict_iter", m.getattr("dict_iter")?)?;
sys_modules.set_item("pyo3_pytests.enums", m.getattr("enums")?)?;
sys_modules.set_item("pyo3_pytests.misc", m.getattr("misc")?)?;
sys_modules.set_item("pyo3_pytests.objstore", m.getattr("objstore")?)?;
sys_modules.set_item("pyo3_pytests.othermod", m.getattr("othermod")?)?;
sys_modules.set_item("pyo3_pytests.path", m.getattr("path")?)?;
sys_modules.set_item("pyo3_pytests.pyclasses", m.getattr("pyclasses")?)?;
sys_modules.set_item("pyo3_pytests.pyfunctions", m.getattr("pyfunctions")?)?;
sys_modules.set_item("pyo3_pytests.sequence", m.getattr("sequence")?)?;
sys_modules.set_item("pyo3_pytests.subclassing", m.getattr("subclassing")?)?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/comparisons.rs | use pyo3::prelude::*;
#[pyclass]
struct Eq(i64);
#[pymethods]
impl Eq {
#[new]
fn new(value: i64) -> Self {
Self(value)
}
fn __eq__(&self, other: &Self) -> bool {
self.0 == other.0
}
fn __ne__(&self, other: &Self) -> bool {
self.0 != other.0
}
}
#[pyclass]
struct EqDefaultNe(i64);
#[pymethods]
impl EqDefaultNe {
#[new]
fn new(value: i64) -> Self {
Self(value)
}
fn __eq__(&self, other: &Self) -> bool {
self.0 == other.0
}
}
#[pyclass(eq)]
#[derive(PartialEq, Eq)]
struct EqDerived(i64);
#[pymethods]
impl EqDerived {
#[new]
fn new(value: i64) -> Self {
Self(value)
}
}
#[pyclass]
struct Ordered(i64);
#[pymethods]
impl Ordered {
#[new]
fn new(value: i64) -> Self {
Self(value)
}
fn __lt__(&self, other: &Self) -> bool {
self.0 < other.0
}
fn __le__(&self, other: &Self) -> bool {
self.0 <= other.0
}
fn __eq__(&self, other: &Self) -> bool {
self.0 == other.0
}
fn __ne__(&self, other: &Self) -> bool {
self.0 != other.0
}
fn __gt__(&self, other: &Self) -> bool {
self.0 > other.0
}
fn __ge__(&self, other: &Self) -> bool {
self.0 >= other.0
}
}
#[pyclass]
struct OrderedDefaultNe(i64);
#[pymethods]
impl OrderedDefaultNe {
#[new]
fn new(value: i64) -> Self {
Self(value)
}
fn __lt__(&self, other: &Self) -> bool {
self.0 < other.0
}
fn __le__(&self, other: &Self) -> bool {
self.0 <= other.0
}
fn __eq__(&self, other: &Self) -> bool {
self.0 == other.0
}
fn __gt__(&self, other: &Self) -> bool {
self.0 > other.0
}
fn __ge__(&self, other: &Self) -> bool {
self.0 >= other.0
}
}
#[pymodule(gil_used = false)]
pub fn comparisons(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Eq>()?;
m.add_class::<EqDefaultNe>()?;
m.add_class::<EqDerived>()?;
m.add_class::<Ordered>()?;
m.add_class::<OrderedDefaultNe>()?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/dict_iter.rs | use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;
use pyo3::types::PyDict;
#[pymodule]
pub fn dict_iter(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<DictSize>()?;
Ok(())
}
#[pyclass]
pub struct DictSize {
expected: u32,
}
#[pymethods]
impl DictSize {
#[new]
fn new(expected: u32) -> Self {
DictSize { expected }
}
fn iter_dict(&mut self, _py: Python<'_>, dict: &Bound<'_, PyDict>) -> PyResult<u32> {
let mut seen = 0u32;
for (sym, values) in dict {
seen += 1;
println!(
"{:4}/{:4} iterations:{}=>{}",
seen, self.expected, sym, values
);
}
if seen == self.expected {
Ok(seen)
} else {
Err(PyErr::new::<PyRuntimeError, _>(format!(
"Expected {} iterations - performed {}",
self.expected, seen
)))
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/objstore.rs | use pyo3::prelude::*;
#[pyclass]
#[derive(Default)]
pub struct ObjStore {
obj: Vec<PyObject>,
}
#[pymethods]
impl ObjStore {
#[new]
fn new() -> Self {
ObjStore::default()
}
fn push(&mut self, obj: &Bound<'_, PyAny>) {
self.obj.push(obj.clone().unbind());
}
}
#[pymodule(gil_used = false)]
pub fn objstore(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<ObjStore>()
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests | lc_public_repos/langsmith-sdk/vendor/pyo3/pytests/src/awaitable.rs | //! The following classes are examples of objects which implement Python's
//! awaitable protocol.
//!
//! Both IterAwaitable and FutureAwaitable will return a value immediately
//! when awaited, see guide examples related to pyo3-asyncio for ways
//! to suspend tasks and await results.
use pyo3::exceptions::PyStopIteration;
use pyo3::prelude::*;
#[pyclass]
#[derive(Debug)]
pub(crate) struct IterAwaitable {
result: Option<PyResult<PyObject>>,
}
#[pymethods]
impl IterAwaitable {
#[new]
fn new(result: PyObject) -> Self {
IterAwaitable {
result: Some(Ok(result)),
}
}
fn __await__(pyself: PyRef<'_, Self>) -> PyRef<'_, Self> {
pyself
}
fn __iter__(pyself: PyRef<'_, Self>) -> PyRef<'_, Self> {
pyself
}
fn __next__(&mut self, py: Python<'_>) -> PyResult<PyObject> {
match self.result.take() {
Some(res) => match res {
Ok(v) => Err(PyStopIteration::new_err(v)),
Err(err) => Err(err),
},
_ => Ok(py.None()),
}
}
}
#[pyclass]
pub(crate) struct FutureAwaitable {
#[pyo3(get, set, name = "_asyncio_future_blocking")]
py_block: bool,
result: Option<PyResult<PyObject>>,
}
#[pymethods]
impl FutureAwaitable {
#[new]
fn new(result: PyObject) -> Self {
FutureAwaitable {
py_block: false,
result: Some(Ok(result)),
}
}
fn __await__(pyself: PyRef<'_, Self>) -> PyRef<'_, Self> {
pyself
}
fn __iter__(pyself: PyRef<'_, Self>) -> PyRef<'_, Self> {
pyself
}
fn __next__(mut pyself: PyRefMut<'_, Self>) -> PyResult<PyRefMut<'_, Self>> {
match pyself.result {
Some(_) => match pyself.result.take().unwrap() {
Ok(v) => Err(PyStopIteration::new_err(v)),
Err(err) => Err(err),
},
_ => Ok(pyself),
}
}
}
#[pymodule(gil_used = false)]
pub fn awaitable(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<IterAwaitable>()?;
m.add_class::<FutureAwaitable>()?;
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/Cargo.toml | [package]
name = "pyo3-benches"
version = "0.1.0"
description = "In-tree benchmarks for the PyO3 project"
authors = ["PyO3 Project and Contributors <https://github.com/PyO3>"]
edition = "2021"
publish = false
[dependencies]
pyo3 = { path = "../", features = ["auto-initialize", "full"] }
[build-dependencies]
pyo3-build-config = { path = "../pyo3-build-config" }
[dev-dependencies]
codspeed-criterion-compat = "2.3"
criterion = "0.5.1"
num-bigint = "0.4.3"
rust_decimal = { version = "1.0.0", default-features = false }
hashbrown = "0.15"
[[bench]]
name = "bench_any"
harness = false
[[bench]]
name = "bench_call"
harness = false
[[bench]]
name = "bench_comparisons"
harness = false
[[bench]]
name = "bench_err"
harness = false
[[bench]]
name = "bench_decimal"
harness = false
[[bench]]
name = "bench_dict"
harness = false
[[bench]]
name = "bench_frompyobject"
harness = false
[[bench]]
name = "bench_gil"
harness = false
[[bench]]
name = "bench_intopyobject"
harness = false
[[bench]]
name = "bench_list"
harness = false
[[bench]]
name = "bench_pyclass"
harness = false
[[bench]]
name = "bench_pyobject"
harness = false
[[bench]]
name = "bench_set"
harness = false
[[bench]]
name = "bench_tuple"
harness = false
[[bench]]
name = "bench_intern"
harness = false
[[bench]]
name = "bench_extract"
harness = false
[[bench]]
name = "bench_bigint"
harness = false
[workspace]
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/build.rs | fn main() {
pyo3_build_config::use_pyo3_cfgs();
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_pyclass.rs | use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::{impl_::pyclass::LazyTypeObject, prelude::*};
/// This is a feature-rich class instance used to benchmark various parts of the pyclass lifecycle.
#[pyclass]
struct MyClass {
#[pyo3(get, set)]
elements: Vec<i32>,
}
#[pymethods]
impl MyClass {
#[new]
fn new(elements: Vec<i32>) -> Self {
Self { elements }
}
fn __call__(&mut self, new_element: i32) -> usize {
self.elements.push(new_element);
self.elements.len()
}
/// A basic __str__ implementation.
fn __str__(&self) -> &'static str {
"MyClass"
}
}
pub fn first_time_init(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
b.iter(|| {
// This is using an undocumented internal PyO3 API to measure pyclass performance; please
// don't use this in your own code!
let ty = LazyTypeObject::<MyClass>::new();
ty.get_or_init(py);
});
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("first_time_init", first_time_init);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_pyobject.rs | use codspeed_criterion_compat::{criterion_group, criterion_main, BatchSize, Bencher, Criterion};
use std::sync::{
atomic::{AtomicUsize, Ordering},
mpsc::channel,
Arc, Barrier,
};
use std::thread::spawn;
use std::time::{Duration, Instant};
use pyo3::prelude::*;
fn drop_many_objects(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
b.iter(|| {
for _ in 0..1000 {
drop(py.None());
}
});
});
}
fn drop_many_objects_without_gil(b: &mut Bencher<'_>) {
b.iter_batched(
|| {
Python::with_gil(|py| {
(0..1000)
.map(|_| py.None().into_py(py))
.collect::<Vec<PyObject>>()
})
},
|objs| {
drop(objs);
Python::with_gil(|_py| ());
},
BatchSize::SmallInput,
);
}
fn drop_many_objects_multiple_threads(b: &mut Bencher<'_>) {
const THREADS: usize = 5;
let barrier = Arc::new(Barrier::new(1 + THREADS));
let done = Arc::new(AtomicUsize::new(0));
let sender = (0..THREADS)
.map(|_| {
let (sender, receiver) = channel();
let barrier = barrier.clone();
let done = done.clone();
spawn(move || {
for objs in receiver {
barrier.wait();
drop(objs);
done.fetch_add(1, Ordering::AcqRel);
}
});
sender
})
.collect::<Vec<_>>();
b.iter_custom(|iters| {
let mut duration = Duration::ZERO;
let mut last_done = done.load(Ordering::Acquire);
for _ in 0..iters {
for sender in &sender {
let objs = Python::with_gil(|py| {
(0..1000 / THREADS)
.map(|_| py.None().into_py(py))
.collect::<Vec<PyObject>>()
});
sender.send(objs).unwrap();
}
barrier.wait();
let start = Instant::now();
loop {
Python::with_gil(|_py| ());
let done = done.load(Ordering::Acquire);
if done - last_done == THREADS {
last_done = done;
break;
}
}
Python::with_gil(|_py| ());
duration += start.elapsed();
}
duration
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("drop_many_objects", drop_many_objects);
c.bench_function(
"drop_many_objects_without_gil",
drop_many_objects_without_gil,
);
c.bench_function(
"drop_many_objects_multiple_threads",
drop_many_objects_multiple_threads,
);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_dict.rs | use std::collections::{BTreeMap, HashMap};
use std::hint::black_box;
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::types::IntoPyDict;
use pyo3::{prelude::*, types::PyMapping};
fn iter_dict(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
let dict = (0..LEN as u64)
.map(|i| (i, i * 2))
.into_py_dict(py)
.unwrap();
let mut sum = 0;
b.iter(|| {
for (k, _v) in &dict {
let i: u64 = k.extract().unwrap();
sum += i;
}
});
})
}
fn dict_new(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
b.iter_with_large_drop(|| {
(0..LEN as u64)
.map(|i| (i, i * 2))
.into_py_dict(py)
.unwrap()
});
});
}
fn dict_get_item(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let dict = (0..LEN as u64)
.map(|i| (i, i * 2))
.into_py_dict(py)
.unwrap();
let mut sum = 0;
b.iter(|| {
for i in 0..LEN {
sum += dict
.get_item(i)
.unwrap()
.unwrap()
.extract::<usize>()
.unwrap();
}
});
});
}
fn extract_hashmap(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
let dict = (0..LEN as u64)
.map(|i| (i, i * 2))
.into_py_dict(py)
.unwrap();
b.iter(|| HashMap::<u64, u64>::extract_bound(&dict));
});
}
fn extract_btreemap(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
let dict = (0..LEN as u64)
.map(|i| (i, i * 2))
.into_py_dict(py)
.unwrap();
b.iter(|| BTreeMap::<u64, u64>::extract_bound(&dict));
});
}
fn extract_hashbrown_map(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
let dict = (0..LEN as u64)
.map(|i| (i, i * 2))
.into_py_dict(py)
.unwrap();
b.iter(|| hashbrown::HashMap::<u64, u64>::extract_bound(&dict));
});
}
fn mapping_from_dict(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
let dict = &(0..LEN as u64)
.map(|i| (i, i * 2))
.into_py_dict(py)
.unwrap();
b.iter(|| black_box(dict).downcast::<PyMapping>().unwrap());
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("iter_dict", iter_dict);
c.bench_function("dict_new", dict_new);
c.bench_function("dict_get_item", dict_get_item);
c.bench_function("extract_hashmap", extract_hashmap);
c.bench_function("extract_btreemap", extract_btreemap);
c.bench_function("mapping_from_dict", mapping_from_dict);
c.bench_function("extract_hashbrown_map", extract_hashbrown_map);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_call.rs | use std::hint::black_box;
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::ffi::c_str;
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
macro_rules! test_module {
($py:ident, $code:literal) => {
PyModule::from_code($py, c_str!($code), c_str!(file!()), c_str!("test_module"))
.expect("module creation failed")
};
}
fn bench_call_0(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let module = test_module!(py, "def foo(): pass");
let foo_module = &module.getattr("foo").unwrap();
b.iter(|| {
for _ in 0..1000 {
black_box(foo_module).call0().unwrap();
}
});
})
}
fn bench_call_1(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let module = test_module!(py, "def foo(a, b, c): pass");
let foo_module = &module.getattr("foo").unwrap();
let args = (
<_ as IntoPy<PyObject>>::into_py(1, py).into_bound(py),
<_ as IntoPy<PyObject>>::into_py("s", py).into_bound(py),
<_ as IntoPy<PyObject>>::into_py(1.23, py).into_bound(py),
);
b.iter(|| {
for _ in 0..1000 {
black_box(foo_module).call1(args.clone()).unwrap();
}
});
})
}
fn bench_call(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let module = test_module!(py, "def foo(a, b, c, d, e): pass");
let foo_module = &module.getattr("foo").unwrap();
let args = (
<_ as IntoPy<PyObject>>::into_py(1, py).into_bound(py),
<_ as IntoPy<PyObject>>::into_py("s", py).into_bound(py),
<_ as IntoPy<PyObject>>::into_py(1.23, py).into_bound(py),
);
let kwargs = [("d", 1), ("e", 42)].into_py_dict(py).unwrap();
b.iter(|| {
for _ in 0..1000 {
black_box(foo_module)
.call(args.clone(), Some(&kwargs))
.unwrap();
}
});
})
}
fn bench_call_one_arg(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let module = test_module!(py, "def foo(a): pass");
let foo_module = &module.getattr("foo").unwrap();
let arg = <_ as IntoPy<PyObject>>::into_py(1, py).into_bound(py);
b.iter(|| {
for _ in 0..1000 {
black_box(foo_module).call1((arg.clone(),)).unwrap();
}
});
})
}
fn bench_call_method_0(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let module = test_module!(
py,
"
class Foo:
def foo(self):
pass
"
);
let foo_module = &module.getattr("Foo").unwrap().call0().unwrap();
b.iter(|| {
for _ in 0..1000 {
black_box(foo_module).call_method0("foo").unwrap();
}
});
})
}
fn bench_call_method_1(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let module = test_module!(
py,
"
class Foo:
def foo(self, a, b, c):
pass
"
);
let foo_module = &module.getattr("Foo").unwrap().call0().unwrap();
let args = (
<_ as IntoPy<PyObject>>::into_py(1, py).into_bound(py),
<_ as IntoPy<PyObject>>::into_py("s", py).into_bound(py),
<_ as IntoPy<PyObject>>::into_py(1.23, py).into_bound(py),
);
b.iter(|| {
for _ in 0..1000 {
black_box(foo_module)
.call_method1("foo", args.clone())
.unwrap();
}
});
})
}
fn bench_call_method(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let module = test_module!(
py,
"
class Foo:
def foo(self, a, b, c, d, e):
pass
"
);
let foo_module = &module.getattr("Foo").unwrap().call0().unwrap();
let args = (
<_ as IntoPy<PyObject>>::into_py(1, py).into_bound(py),
<_ as IntoPy<PyObject>>::into_py("s", py).into_bound(py),
<_ as IntoPy<PyObject>>::into_py(1.23, py).into_bound(py),
);
let kwargs = [("d", 1), ("e", 42)].into_py_dict(py).unwrap();
b.iter(|| {
for _ in 0..1000 {
black_box(foo_module)
.call_method("foo", args.clone(), Some(&kwargs))
.unwrap();
}
});
})
}
fn bench_call_method_one_arg(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let module = test_module!(
py,
"
class Foo:
def foo(self, a):
pass
"
);
let foo_module = &module.getattr("Foo").unwrap().call0().unwrap();
let arg = <_ as IntoPy<PyObject>>::into_py(1, py).into_bound(py);
b.iter(|| {
for _ in 0..1000 {
black_box(foo_module)
.call_method1("foo", (arg.clone(),))
.unwrap();
}
});
})
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("call_0", bench_call_0);
c.bench_function("call_1", bench_call_1);
c.bench_function("call", bench_call);
c.bench_function("call_one_arg", bench_call_one_arg);
c.bench_function("call_method_0", bench_call_method_0);
c.bench_function("call_method_1", bench_call_method_1);
c.bench_function("call_method", bench_call_method);
c.bench_function("call_method_one_arg", bench_call_method_one_arg);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_frompyobject.rs | use std::hint::black_box;
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::{
prelude::*,
types::{PyList, PyString},
};
#[derive(FromPyObject)]
#[allow(dead_code)]
enum ManyTypes {
Int(i32),
Bytes(Vec<u8>),
String(String),
}
fn enum_from_pyobject(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let any = PyString::new(py, "hello world").into_any();
b.iter(|| black_box(&any).extract::<ManyTypes>().unwrap());
})
}
fn list_via_downcast(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let any = PyList::empty(py).into_any();
b.iter(|| black_box(&any).downcast::<PyList>().unwrap());
})
}
fn list_via_extract(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let any = PyList::empty(py).into_any();
b.iter(|| black_box(&any).extract::<Bound<'_, PyList>>().unwrap());
})
}
fn not_a_list_via_downcast(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let any = PyString::new(py, "foobar").into_any();
b.iter(|| black_box(&any).downcast::<PyList>().unwrap_err());
})
}
fn not_a_list_via_extract(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let any = PyString::new(py, "foobar").into_any();
b.iter(|| black_box(&any).extract::<Bound<'_, PyList>>().unwrap_err());
})
}
#[derive(FromPyObject)]
enum ListOrNotList<'a> {
List(Bound<'a, PyList>),
NotList(Bound<'a, PyAny>),
}
fn not_a_list_via_extract_enum(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let any = PyString::new(py, "foobar").into_any();
b.iter(|| match black_box(&any).extract::<ListOrNotList<'_>>() {
Ok(ListOrNotList::List(_list)) => panic!(),
Ok(ListOrNotList::NotList(any)) => any,
Err(_) => panic!(),
});
})
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("enum_from_pyobject", enum_from_pyobject);
c.bench_function("list_via_downcast", list_via_downcast);
c.bench_function("list_via_extract", list_via_extract);
c.bench_function("not_a_list_via_downcast", not_a_list_via_downcast);
c.bench_function("not_a_list_via_extract", not_a_list_via_extract);
c.bench_function("not_a_list_via_extract_enum", not_a_list_via_extract_enum);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_any.rs | use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::{
prelude::*,
types::{
PyBool, PyByteArray, PyBytes, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PyMapping,
PySequence, PySet, PyString, PyTuple,
},
};
#[derive(PartialEq, Eq, Debug)]
enum ObjectType {
None,
Bool,
ByteArray,
Bytes,
Dict,
Float,
FrozenSet,
Int,
List,
Set,
Str,
Tuple,
Sequence,
Mapping,
Unknown,
}
fn find_object_type(obj: &Bound<'_, PyAny>) -> ObjectType {
if obj.is_none() {
ObjectType::None
} else if obj.is_instance_of::<PyBool>() {
ObjectType::Bool
} else if obj.is_instance_of::<PyByteArray>() {
ObjectType::ByteArray
} else if obj.is_instance_of::<PyBytes>() {
ObjectType::Bytes
} else if obj.is_instance_of::<PyDict>() {
ObjectType::Dict
} else if obj.is_instance_of::<PyFloat>() {
ObjectType::Float
} else if obj.is_instance_of::<PyFrozenSet>() {
ObjectType::FrozenSet
} else if obj.is_instance_of::<PyInt>() {
ObjectType::Int
} else if obj.is_instance_of::<PyList>() {
ObjectType::List
} else if obj.is_instance_of::<PySet>() {
ObjectType::Set
} else if obj.is_instance_of::<PyString>() {
ObjectType::Str
} else if obj.is_instance_of::<PyTuple>() {
ObjectType::Tuple
} else if obj.downcast::<PySequence>().is_ok() {
ObjectType::Sequence
} else if obj.downcast::<PyMapping>().is_ok() {
ObjectType::Mapping
} else {
ObjectType::Unknown
}
}
fn bench_identify_object_type(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let obj = py.eval(c"object()", None, None).unwrap();
b.iter(|| find_object_type(&obj));
assert_eq!(find_object_type(&obj), ObjectType::Unknown);
});
}
fn bench_collect_generic_iterator(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let collection = py.eval(c"list(range(1 << 20))", None, None).unwrap();
b.iter(|| {
collection
.try_iter()
.unwrap()
.collect::<PyResult<Vec<_>>>()
.unwrap()
});
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("identify_object_type", bench_identify_object_type);
c.bench_function("collect_generic_iterator", bench_collect_generic_iterator);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_tuple.rs | use std::hint::black_box;
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::prelude::*;
use pyo3::types::{PyList, PySequence, PyTuple};
fn iter_tuple(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
let tuple = PyTuple::new(py, 0..LEN).unwrap();
let mut sum = 0;
b.iter(|| {
for x in tuple.iter_borrowed() {
let i: u64 = x.extract().unwrap();
sum += i;
}
});
});
}
fn tuple_new(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
b.iter_with_large_drop(|| PyTuple::new(py, 0..LEN).unwrap());
});
}
fn tuple_get_item(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let tuple = PyTuple::new(py, 0..LEN).unwrap();
let mut sum = 0;
b.iter(|| {
for i in 0..LEN {
sum += tuple.get_item(i).unwrap().extract::<usize>().unwrap();
}
});
});
}
#[cfg(not(any(Py_LIMITED_API, PyPy)))]
fn tuple_get_item_unchecked(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let tuple = PyTuple::new(py, 0..LEN).unwrap();
let mut sum = 0;
b.iter(|| {
for i in 0..LEN {
unsafe {
sum += tuple.get_item_unchecked(i).extract::<usize>().unwrap();
}
}
});
});
}
fn tuple_get_borrowed_item(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let tuple = PyTuple::new(py, 0..LEN).unwrap();
let mut sum = 0;
b.iter(|| {
for i in 0..LEN {
sum += tuple
.get_borrowed_item(i)
.unwrap()
.extract::<usize>()
.unwrap();
}
});
});
}
#[cfg(not(any(Py_LIMITED_API, PyPy)))]
fn tuple_get_borrowed_item_unchecked(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let tuple = PyTuple::new(py, 0..LEN).unwrap();
let mut sum = 0;
b.iter(|| {
for i in 0..LEN {
unsafe {
sum += tuple
.get_borrowed_item_unchecked(i)
.extract::<usize>()
.unwrap();
}
}
});
});
}
fn sequence_from_tuple(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let tuple = PyTuple::new(py, 0..LEN).unwrap().into_any();
b.iter(|| black_box(&tuple).downcast::<PySequence>().unwrap());
});
}
fn tuple_new_list(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let tuple = PyTuple::new(py, 0..LEN).unwrap();
b.iter_with_large_drop(|| PyList::new(py, tuple.iter_borrowed()));
});
}
fn tuple_to_list(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let tuple = PyTuple::new(py, 0..LEN).unwrap();
b.iter_with_large_drop(|| tuple.to_list());
});
}
fn tuple_into_py(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
b.iter(|| -> PyObject { (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12).into_py(py) });
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("iter_tuple", iter_tuple);
c.bench_function("tuple_new", tuple_new);
c.bench_function("tuple_get_item", tuple_get_item);
#[cfg(not(any(Py_LIMITED_API, PyPy)))]
c.bench_function("tuple_get_item_unchecked", tuple_get_item_unchecked);
c.bench_function("tuple_get_borrowed_item", tuple_get_borrowed_item);
#[cfg(not(any(Py_LIMITED_API, PyPy)))]
c.bench_function(
"tuple_get_borrowed_item_unchecked",
tuple_get_borrowed_item_unchecked,
);
c.bench_function("sequence_from_tuple", sequence_from_tuple);
c.bench_function("tuple_new_list", tuple_new_list);
c.bench_function("tuple_to_list", tuple_to_list);
c.bench_function("tuple_into_py", tuple_into_py);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_intopyobject.rs | use std::hint::black_box;
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::conversion::IntoPyObject;
use pyo3::prelude::*;
use pyo3::types::PyBytes;
fn bench_bytes_new(b: &mut Bencher<'_>, data: &[u8]) {
Python::with_gil(|py| {
b.iter_with_large_drop(|| PyBytes::new(py, black_box(data)));
});
}
fn bytes_new_small(b: &mut Bencher<'_>) {
bench_bytes_new(b, &[]);
}
fn bytes_new_medium(b: &mut Bencher<'_>) {
let data = (0..u8::MAX).into_iter().collect::<Vec<u8>>();
bench_bytes_new(b, &data);
}
fn bytes_new_large(b: &mut Bencher<'_>) {
let data = vec![10u8; 100_000];
bench_bytes_new(b, &data);
}
fn bench_bytes_into_pyobject(b: &mut Bencher<'_>, data: &[u8]) {
Python::with_gil(|py| {
b.iter_with_large_drop(|| black_box(data).into_pyobject(py));
});
}
fn byte_slice_into_pyobject_small(b: &mut Bencher<'_>) {
bench_bytes_into_pyobject(b, &[]);
}
fn byte_slice_into_pyobject_medium(b: &mut Bencher<'_>) {
let data = (0..u8::MAX).into_iter().collect::<Vec<u8>>();
bench_bytes_into_pyobject(b, &data);
}
fn byte_slice_into_pyobject_large(b: &mut Bencher<'_>) {
let data = vec![10u8; 100_000];
bench_bytes_into_pyobject(b, &data);
}
fn byte_slice_into_py(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let data = (0..u8::MAX).into_iter().collect::<Vec<u8>>();
let bytes = data.as_slice();
b.iter_with_large_drop(|| black_box(bytes).into_py(py));
});
}
fn vec_into_pyobject(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let bytes = (0..u8::MAX).into_iter().collect::<Vec<u8>>();
b.iter_with_large_drop(|| black_box(&bytes).clone().into_pyobject(py));
});
}
fn vec_into_py(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let bytes = (0..u8::MAX).into_iter().collect::<Vec<u8>>();
b.iter_with_large_drop(|| black_box(&bytes).clone().into_py(py));
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("bytes_new_small", bytes_new_small);
c.bench_function("bytes_new_medium", bytes_new_medium);
c.bench_function("bytes_new_large", bytes_new_large);
c.bench_function(
"byte_slice_into_pyobject_small",
byte_slice_into_pyobject_small,
);
c.bench_function(
"byte_slice_into_pyobject_medium",
byte_slice_into_pyobject_medium,
);
c.bench_function(
"byte_slice_into_pyobject_large",
byte_slice_into_pyobject_large,
);
c.bench_function("byte_slice_into_py", byte_slice_into_py);
c.bench_function("vec_into_pyobject", vec_into_pyobject);
c.bench_function("vec_into_py", vec_into_py);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_comparisons.rs | use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::{prelude::*, pyclass::CompareOp, Python};
#[pyclass]
struct OrderedDunderMethods(i64);
#[pymethods]
impl OrderedDunderMethods {
fn __lt__(&self, other: &Self) -> bool {
self.0 < other.0
}
fn __le__(&self, other: &Self) -> bool {
self.0 <= other.0
}
fn __eq__(&self, other: &Self) -> bool {
self.0 == other.0
}
fn __ne__(&self, other: &Self) -> bool {
self.0 != other.0
}
fn __gt__(&self, other: &Self) -> bool {
self.0 > other.0
}
fn __ge__(&self, other: &Self) -> bool {
self.0 >= other.0
}
}
#[pyclass]
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct OrderedRichcmp(i64);
#[pymethods]
impl OrderedRichcmp {
fn __richcmp__(&self, other: &Self, op: CompareOp) -> bool {
op.matches(self.cmp(other))
}
}
fn bench_ordered_dunder_methods(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let obj1 = &Bound::new(py, OrderedDunderMethods(0)).unwrap().into_any();
let obj2 = &Bound::new(py, OrderedDunderMethods(1)).unwrap().into_any();
b.iter(|| obj2.gt(obj1).unwrap());
});
}
fn bench_ordered_richcmp(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let obj1 = &Bound::new(py, OrderedRichcmp(0)).unwrap().into_any();
let obj2 = &Bound::new(py, OrderedRichcmp(1)).unwrap().into_any();
b.iter(|| obj2.gt(obj1).unwrap());
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("ordered_dunder_methods", bench_ordered_dunder_methods);
c.bench_function("ordered_richcmp", bench_ordered_richcmp);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_extract.rs | use std::hint::black_box;
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::{
prelude::*,
types::{PyDict, PyFloat, PyInt, PyString},
};
fn extract_str_extract_success(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let s = PyString::new(py, "Hello, World!").into_any();
bench.iter(|| black_box(&s).extract::<&str>().unwrap());
});
}
fn extract_str_extract_fail(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let d = PyDict::new(py).into_any();
bench.iter(|| match black_box(&d).extract::<&str>() {
Ok(v) => panic!("should err {}", v),
Err(e) => e,
});
});
}
#[cfg(any(Py_3_10))]
fn extract_str_downcast_success(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let s = PyString::new(py, "Hello, World!").into_any();
bench.iter(|| {
let py_str = black_box(&s).downcast::<PyString>().unwrap();
py_str.to_str().unwrap()
});
});
}
fn extract_str_downcast_fail(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let d = PyDict::new(py).into_any();
bench.iter(|| match black_box(&d).downcast::<PyString>() {
Ok(v) => panic!("should err {}", v),
Err(e) => e,
});
});
}
fn extract_int_extract_success(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let int = 123.to_object(py).into_bound(py);
bench.iter(|| black_box(&int).extract::<i64>().unwrap());
});
}
fn extract_int_extract_fail(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let d = PyDict::new(py).into_any();
bench.iter(|| match black_box(&d).extract::<i64>() {
Ok(v) => panic!("should err {}", v),
Err(e) => e,
});
});
}
fn extract_int_downcast_success(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let int = 123.to_object(py).into_bound(py);
bench.iter(|| {
let py_int = black_box(&int).downcast::<PyInt>().unwrap();
py_int.extract::<i64>().unwrap()
});
});
}
fn extract_int_downcast_fail(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let d = PyDict::new(py).into_any();
bench.iter(|| match black_box(&d).downcast::<PyInt>() {
Ok(v) => panic!("should err {}", v),
Err(e) => black_box(e),
});
});
}
fn extract_float_extract_success(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let float = 23.42.to_object(py).into_bound(py);
bench.iter(|| black_box(&float).extract::<f64>().unwrap());
});
}
fn extract_float_extract_fail(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let d = PyDict::new(py).into_any();
bench.iter(|| match black_box(&d).extract::<f64>() {
Ok(v) => panic!("should err {}", v),
Err(e) => e,
});
});
}
fn extract_float_downcast_success(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let float = 23.42.to_object(py).into_bound(py);
bench.iter(|| {
let py_float = black_box(&float).downcast::<PyFloat>().unwrap();
py_float.value()
});
});
}
fn extract_float_downcast_fail(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let d = PyDict::new(py).into_any();
bench.iter(|| match black_box(&d).downcast::<PyFloat>() {
Ok(v) => panic!("should err {}", v),
Err(e) => e,
});
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("extract_str_extract_success", extract_str_extract_success);
c.bench_function("extract_str_extract_fail", extract_str_extract_fail);
#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
c.bench_function("extract_str_downcast_success", extract_str_downcast_success);
c.bench_function("extract_str_downcast_fail", extract_str_downcast_fail);
c.bench_function("extract_int_extract_success", extract_int_extract_success);
c.bench_function("extract_int_extract_fail", extract_int_extract_fail);
c.bench_function("extract_int_downcast_success", extract_int_downcast_success);
c.bench_function("extract_int_downcast_fail", extract_int_downcast_fail);
c.bench_function(
"extract_float_extract_success",
extract_float_extract_success,
);
c.bench_function("extract_float_extract_fail", extract_float_extract_fail);
c.bench_function(
"extract_float_downcast_success",
extract_float_downcast_success,
);
c.bench_function("extract_float_downcast_fail", extract_float_downcast_fail);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_err.rs | use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::{exceptions::PyValueError, prelude::*};
fn err_new_restore_and_fetch(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
b.iter(|| {
PyValueError::new_err("some exception message").restore(py);
PyErr::fetch(py)
})
})
}
fn err_new_without_gil(b: &mut Bencher<'_>) {
b.iter(|| PyValueError::new_err("some exception message"))
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("err_new_restore_and_fetch", err_new_restore_and_fetch);
c.bench_function("err_new_without_gil", err_new_without_gil);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_set.rs | use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::prelude::*;
use pyo3::types::PySet;
use std::{
collections::{BTreeSet, HashSet},
hint::black_box,
};
fn set_new(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
// Create Python objects up-front, so that the benchmark doesn't need to include
// the cost of allocating LEN Python integers
let elements: Vec<PyObject> = (0..LEN).map(|i| i.into_py(py)).collect();
b.iter_with_large_drop(|| PySet::new(py, &elements).unwrap());
});
}
fn iter_set(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
let set = PySet::new(py, &(0..LEN).collect::<Vec<_>>()).unwrap();
let mut sum = 0;
b.iter(|| {
for x in &set {
let i: u64 = x.extract().unwrap();
sum += i;
}
});
});
}
fn extract_hashset(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
let any = PySet::new(py, &(0..LEN).collect::<Vec<_>>())
.unwrap()
.into_any();
b.iter_with_large_drop(|| black_box(&any).extract::<HashSet<u64>>());
});
}
fn extract_btreeset(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
let any = PySet::new(py, &(0..LEN).collect::<Vec<_>>())
.unwrap()
.into_any();
b.iter_with_large_drop(|| black_box(&any).extract::<BTreeSet<u64>>());
});
}
fn extract_hashbrown_set(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
let any = PySet::new(py, &(0..LEN).collect::<Vec<_>>())
.unwrap()
.into_any();
b.iter_with_large_drop(|| black_box(&any).extract::<hashbrown::HashSet<u64>>());
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("set_new", set_new);
c.bench_function("iter_set", iter_set);
c.bench_function("extract_hashset", extract_hashset);
c.bench_function("extract_btreeset", extract_btreeset);
c.bench_function("extract_hashbrown_set", extract_hashbrown_set);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_decimal.rs | use std::hint::black_box;
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use rust_decimal::Decimal;
use pyo3::prelude::*;
use pyo3::types::PyDict;
fn decimal_via_extract(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let locals = PyDict::new(py);
py.run(
cr#"
import decimal
py_dec = decimal.Decimal("0.0")
"#,
None,
Some(&locals),
)
.unwrap();
let py_dec = locals.get_item("py_dec").unwrap().unwrap();
b.iter(|| black_box(&py_dec).extract::<Decimal>().unwrap());
})
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("decimal_via_extract", decimal_via_extract);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_intern.rs | use std::hint::black_box;
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::prelude::*;
use pyo3::intern;
fn getattr_direct(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let sys = &py.import("sys").unwrap();
b.iter(|| black_box(sys).getattr("version").unwrap());
});
}
fn getattr_intern(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let sys = &py.import("sys").unwrap();
b.iter(|| black_box(sys).getattr(intern!(py, "version")).unwrap());
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("getattr_direct", getattr_direct);
c.bench_function("getattr_intern", getattr_intern);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_list.rs | use std::hint::black_box;
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::prelude::*;
use pyo3::types::{PyList, PySequence};
fn iter_list(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 100_000;
let list = PyList::new(py, 0..LEN).unwrap();
let mut sum = 0;
b.iter(|| {
for x in &list {
let i: u64 = x.extract().unwrap();
sum += i;
}
});
});
}
fn list_new(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
b.iter_with_large_drop(|| PyList::new(py, 0..LEN));
});
}
fn list_get_item(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let list = PyList::new(py, 0..LEN).unwrap();
let mut sum = 0;
b.iter(|| {
for i in 0..LEN {
sum += list.get_item(i).unwrap().extract::<usize>().unwrap();
}
});
});
}
#[cfg(not(any(Py_LIMITED_API, Py_GIL_DISABLED)))]
fn list_get_item_unchecked(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let list = PyList::new(py, 0..LEN).unwrap();
let mut sum = 0;
b.iter(|| {
for i in 0..LEN {
unsafe {
sum += list.get_item_unchecked(i).extract::<usize>().unwrap();
}
}
});
});
}
fn sequence_from_list(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let list = &PyList::new(py, 0..LEN).unwrap();
b.iter(|| black_box(list).downcast::<PySequence>().unwrap());
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("iter_list", iter_list);
c.bench_function("list_new", list_new);
c.bench_function("list_get_item", list_get_item);
#[cfg(not(any(Py_LIMITED_API, Py_GIL_DISABLED)))]
c.bench_function("list_get_item_unchecked", list_get_item_unchecked);
c.bench_function("sequence_from_list", sequence_from_list);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_bigint.rs | use std::hint::black_box;
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use num_bigint::BigInt;
use pyo3::prelude::*;
use pyo3::types::PyDict;
fn extract_bigint_extract_fail(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let d = PyDict::new(py).into_any();
bench.iter(|| match black_box(&d).extract::<BigInt>() {
Ok(v) => panic!("should err {}", v),
Err(e) => e,
});
});
}
fn extract_bigint_small(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let int = py.eval(c"-42", None, None).unwrap();
bench.iter_with_large_drop(|| black_box(&int).extract::<BigInt>().unwrap());
});
}
fn extract_bigint_big_negative(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let int = py.eval(c"-10**300", None, None).unwrap();
bench.iter_with_large_drop(|| black_box(&int).extract::<BigInt>().unwrap());
});
}
fn extract_bigint_big_positive(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let int = py.eval(c"10**300", None, None).unwrap();
bench.iter_with_large_drop(|| black_box(&int).extract::<BigInt>().unwrap());
});
}
fn extract_bigint_huge_negative(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let int = py.eval(c"-10**3000", None, None).unwrap();
bench.iter_with_large_drop(|| black_box(&int).extract::<BigInt>().unwrap());
});
}
fn extract_bigint_huge_positive(bench: &mut Bencher<'_>) {
Python::with_gil(|py| {
let int = py.eval(c"10**3000", None, None).unwrap();
bench.iter_with_large_drop(|| black_box(&int).extract::<BigInt>().unwrap());
});
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("extract_bigint_extract_fail", extract_bigint_extract_fail);
c.bench_function("extract_bigint_small", extract_bigint_small);
c.bench_function("extract_bigint_big_negative", extract_bigint_big_negative);
c.bench_function("extract_bigint_big_positive", extract_bigint_big_positive);
c.bench_function("extract_bigint_huge_negative", extract_bigint_huge_negative);
c.bench_function("extract_bigint_huge_positive", extract_bigint_huge_positive);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-benches/benches/bench_gil.rs | use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::prelude::*;
fn bench_clean_acquire_gil(b: &mut Bencher<'_>) {
// Acquiring first GIL will also create a "clean" GILPool, so this measures the Python overhead.
b.iter(|| Python::with_gil(|_| {}));
}
fn bench_dirty_acquire_gil(b: &mut Bencher<'_>) {
let obj = Python::with_gil(|py| py.None());
// Drop the returned clone of the object so that the reference pool has work to do.
b.iter(|| Python::with_gil(|py| obj.clone_ref(py)));
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("clean_acquire_gil", bench_clean_acquire_gil);
c.bench_function("dirty_acquire_gil", bench_dirty_acquire_gil);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/.netlify/internal_banner.html | <div id='pyo3-internal-banner'>
<div style="white-space: nowrap;">
⚠️ Internal Docs ⚠️ Not Public API 👉
<a href='https://pyo3.rs/main/doc/pyo3/index.html' style='color:red;text-decoration:underline;'>
Official Docs Here
</a>
</div>
<style id="pyo3-noscript-style">
body {
padding-top: 2em;
}
</style>
<style>
#pyo3-internal-banner {
position: fixed;
display: flex;
align-items: center;
justify-content:
center;
z-index: 99999;
color: red;
left: 0;
right: 0;
top: 0;
height: 2em;
border: 3px solid red;
width: 100%;
overflow-x: hidden;
background-color: var(--target-background-color);
}
@media (max-width: 700px) {
#pyo3-internal-banner {
top: 50px;
margin-bottom: 10px;
}
}
</style>
</div>
<script>
// when javascript is active, splice the banner into a "sticky" location
// inside the doc body for best appearance
banner = document.getElementById("pyo3-internal-banner")
banner.style.position = "sticky"
document.getElementsByTagName("main")[0].prepend(banner)
document.getElementById("pyo3-noscript-style").remove()
</script>
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/.netlify/build.sh | #!/usr/bin/env bash
set -uex
rustup update nightly
rustup default nightly
PYO3_VERSION=$(cargo search pyo3 --limit 1 | head -1 | tr -s ' ' | cut -d ' ' -f 3 | tr -d '"')
## Start from the existing gh-pages content.
## By serving it over netlify, we can have better UX for users because
## netlify can then redirect e.g. /v0.17.0 to /v0.17.0/
## which leads to better loading of CSS assets.
wget -qc https://github.com/PyO3/pyo3/archive/gh-pages.tar.gz -O - | tar -xz
mv pyo3-gh-pages netlify_build
## Configure netlify _redirects file
# Add redirect for each documented version
set +x # these loops get very spammy and fill the deploy log
for d in netlify_build/v*; do
version="${d/netlify_build\/v/}"
echo "/v$version/doc/* https://docs.rs/pyo3/$version/:splat" >> netlify_build/_redirects
if [ $version != $PYO3_VERSION ]; then
# for old versions, mark the files in the latest version as the canonical URL
for file in $(find $d -type f); do
file_path="${file/$d\//}"
# remove index.html and/or .html suffix to match the page URL on the
# final netlfiy site
url_path="$file_path"
if [[ $file_path == index.html ]]; then
url_path=""
elif [[ $file_path == *.html ]]; then
url_path="${file_path%.html}"
fi
echo "/v$version/$url_path" >> netlify_build/_headers
if test -f "netlify_build/v$PYO3_VERSION/$file_path"; then
echo " Link: <https://pyo3.rs/v$PYO3_VERSION/$url_path>; rel=\"canonical\"" >> netlify_build/_headers
else
# this file doesn't exist in the latest guide, don't index it
echo " X-Robots-Tag: noindex" >> netlify_build/_headers
fi
done
fi
done
# Add latest redirect
echo "/latest/* /v${PYO3_VERSION}/:splat 302" >> netlify_build/_redirects
# some backwards compatbiility redirects
echo "/latest/building_and_distribution/* /latest/building-and-distribution/:splat 302" >> netlify_build/_redirects
echo "/latest/building-and-distribution/multiple_python_versions/* /latest/building-and-distribution/multiple-python-versions:splat 302" >> netlify_build/_redirects
echo "/latest/function/error_handling/* /latest/function/error-handling/:splat 302" >> netlify_build/_redirects
echo "/latest/getting_started/* /latest/getting-started/:splat 302" >> netlify_build/_redirects
echo "/latest/python_from_rust/* /latest/python-from-rust/:splat 302" >> netlify_build/_redirects
echo "/latest/python_typing_hints/* /latest/python-typing-hints/:splat 302" >> netlify_build/_redirects
echo "/latest/trait_bounds/* /latest/trait-bounds/:splat 302" >> netlify_build/_redirects
## Add landing page redirect
if [ "${CONTEXT}" == "deploy-preview" ]; then
echo "/ /main/" >> netlify_build/_redirects
else
echo "/ /v${PYO3_VERSION}/ 302" >> netlify_build/_redirects
fi
set -x
## Generate towncrier release notes
pip install towncrier
towncrier build --yes --version Unreleased --date TBC
## Build guide
# Install latest mdbook. Netlify will cache the cargo bin dir, so this will
# only build mdbook if needed.
MDBOOK_VERSION=$(cargo search mdbook --limit 1 | head -1 | tr -s ' ' | cut -d ' ' -f 3 | tr -d '"')
INSTALLED_MDBOOK_VERSION=$(mdbook --version || echo "none")
if [ "${INSTALLED_MDBOOK_VERSION}" != "mdbook v${MDBOOK_VERSION}" ]; then
cargo install mdbook@${MDBOOK_VERSION} --force
fi
# Install latest mdbook-linkcheck. Netlify will cache the cargo bin dir, so this will
# only build mdbook-linkcheck if needed.
MDBOOK_LINKCHECK_VERSION=$(cargo search mdbook-linkcheck --limit 1 | head -1 | tr -s ' ' | cut -d ' ' -f 3 | tr -d '"')
INSTALLED_MDBOOK_LINKCHECK_VERSION=$(mdbook-linkcheck --version || echo "none")
if [ "${INSTALLED_MDBOOK_LINKCHECK_VERSION}" != "mdbook v${MDBOOK_LINKCHECK_VERSION}" ]; then
cargo install mdbook-linkcheck@${MDBOOK_LINKCHECK_VERSION} --force
fi
pip install nox
nox -s build-guide
mv target/guide/ netlify_build/main/
## Build public docs
nox -s docs
mv target/doc netlify_build/main/doc/
echo "<meta http-equiv=refresh content=0;url=pyo3/>" > netlify_build/main/doc/index.html
## Build internal docs
nox -s docs -- nightly internal
mkdir -p netlify_build/internal
mv target/doc netlify_build/internal/
ls -l netlify_build/
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/branding/pyotr.svg | <?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="1080" height="1080" viewBox="0 0 1080 1080"><defs><style>.p{fill:#fff;}.q{fill:#5a9fd4;}.r{fill:#ffd43b;}.s{fill:#e43a25;}.t{fill:#030404;}.u{fill:#3e6d90;}.v{fill:#1a1a1a;}</style></defs><g id="a"><rect class="v" width="1080" height="1080"/></g><g id="b"><g id="c"><path class="q" d="M470.1992,170.2002c140.2648-2.5648,282.2545,49.1764,379.6617,152.05,42.1707,44.6778,74.899,98.5985,93.3894,157.4029,28.0162,99.5323,23.6492,210.0918-22.2551,304.1025-17.3741,35.6271-41.0854,68.57-69.0085,96.6582-116.4061,117.8402-311.8488,158.9436-458.4507,74.024-34.9209-21.118-65.6353-48.0825-92.1285-78.9857-44.2956-52.0525-72.9359-115.6509-77.5245-184.3734-6.8541-93.9946,25.6439-189.9315,100.9035-249.6672,84.0959-66.1615,205.9983-86.8043,304.297-41.1946,45.6125,21.289,81.4601,57.3094,104.7376,101.7447,37.2798,69.8445,41.9726,157.0079-4.552,223.7989-27.6397,39.8894-69.6303,69.0195-116.2176,82.0876-34.9037,9.9045-73.4819,10.2288-108.1644-1.5152-11.703-3.8106-22.6418-9.2572-33.1248-15.3554-33.4788-19.4956-62.4994-49.2218-75.2479-86.5194-22.2928-64.4901,6.0814-145.2041,68.5029-175.6444,29.5916-13.9453,66.5414-16.7278,97.6527-6.4616,23.6064,7.765,43.629,24.9383,52.7659,48.2988,13.8873,33.4484,3.3714,74.5204-21.5234,99.1309.0004,0-.8257-.5635-.8257-.5635,6.2627-14.762,10.1991-30.3483,10.2071-46.0897-.2131-22.5477-7.8197-43.1595-24.8902-56.7847-21.2296-16.1751-51.2193-16.8267-76.5045-9.5361-33.1876,9.2462-55.0902,39.0586-61.7813,71.9208-8.7734,41.4375,6.7431,78.1186,41.5081,102.2906,12.9228,9.0329,27.5612,16.8422,42.8364,20.8661,56.1118,14.0549,118.4104-15.1339,148.8361-63.3017,13.754-21.7683,19.6984-47.7195,18.0554-73.3693-2.7718-43.7222-25.5962-89.1167-59.3832-116.9753-74.1693-59.8609-198.0471-31.1359-254.8214,39.6856-30.8904,39.395-40.4606,91.2021-35.4807,140.6621,4.0847,41.9461,22.0432,80.9697,49.4688,113.0022,13.8904,16.3896,30.0619,31.1339,47.4808,43.6973,6.177,4.356,12.4878,8.7047,19.0009,12.1489,113.5095,60.2664,268.6177,6.8057,334.5213-99.9259,41.5134-66.9728,45.9873-153.5518,25.938-229.0895-13.5634-42.8773-38.3435-82.1332-70.3238-114.2228-72.4277-72.547-174.6106-108.128-276.9539-109.3969,0,0-.6016-124.5995-.6016-124.5995h0Z"/></g><g id="d"><path class="u" d="M526.9381,397.3214c8.2352,5.9642,28.4158,17.9125,32.9769,24.1895,7.0574,9.7125,12.329,18.47,15.8714,26.2755,1.4799,3.261,6.2541,2.9056,7.1904-.5509,3.1887-11.7715.1411-21.9116-2.3587-27.5323-1.0217-2.2975.3764-4.9269,2.8549-5.3503,5.3774-.9186,13.8798-3.0937,21.1227-8.1682,3.0605-2.1443,1.6372-6.9122-2.0986-7.0074-6.5564-.167-15.1837-1.5665-23.9292-6.4747-5.0786-2.8502-14.5004-8.6029-22.7406-14.0484-6.9265-.9987-13.8912-1.7329-20.8774-2.2142-3.0247,5.2936-6.0493,10.5873-9.0739,15.8809-.9685,1.6951-.519,3.8555,1.0621,5.0006Z"/><path class="u" d="M470.2316,176.8992c.0045.9412.0095,1.9697.0148,3.0781.0054,1.1084.0111,2.2968.0172,3.5573.0092,1.8908.019,3.9441.0296,6.1343.0071,1.4601.0143,2.9811.022,4.5554.0152,3.1484.0314,6.5098.0484,10.0233.0043.8826.0086,1.7748.0129,2.6757.0087,1.7888.0175,3.6114.0264,5.4606.0179,3.7074.0363,7.5213.0549,11.3808.0093,1.9297.0187,3.871.0281,5.8159s.0188,3.8937.0282,5.8387c.0093,1.9403.0187,3.8768.028,5.8019.0047.9742.0094,1.9455.014,2.9129.0092,1.9072.0184,3.7991.0274,5.6686.0046.9483.0091,1.8909.0136,2.8266.0089,1.8491.0177,3.6718.0264,5.4603.013,2.6937.0256,5.3098.0378,7.8232.0161,3.3376.0314,6.4935.0454,9.4074,0,.007,0,.0142.0001.0212.0564,11.6739.094,19.4562.094,19.4581.0033.0001.007.0003.0103.0004,3.8586.0479,7.7164.1611,11.5729.3067,2.0309.0556,3.9788.1246,5.647.2254.2617.02.548.0392.8225.0588,2.2717.1182,4.5413.2671,6.8108.4193,2.3681.1348,4.7145.2679,6.6782.4078,24.4694,1.9338,48.9315,5.9893,72.8813,12.1271,6.7089-35.8959,10.1854-78.5311,8.2295-128.3035-20.8409-4.043-41.9423-6.8651-63.1398-8.4427-.2734-.0201-.5469-.0396-.8203-.0593-1.8622-.1357-3.7255-.2593-5.5891-.3759-.7231-.0448-1.4463-.0886-2.1696-.1306-1.4073-.0823-2.8151-.1569-4.223-.2282-1.0446-.0524-2.0894-.1044-3.1342-.1508-1.0819-.0485-2.1641-.0906-3.2463-.1326-1.2878-.0496-2.5756-.0988-3.8636-.1392-.838-.0265-1.6762-.0469-2.5143-.0695-1.4706-.0394-2.9413-.0783-4.4122-.1058-.6635-.0125-1.327-.0186-1.9905-.0286-1.6062-.0242-3.2125-.0475-4.8187-.0574-.5552-.0034-1.1104-.0002-1.6656-.0019-1.6803-.0053-3.3607-.0095-5.0408.0007-2.2089.0142-4.4178.0389-6.6262.0804,0,0,.0072,1.4905.02,4.1456.0037.7586.0078,1.6123.0123,2.5534Z"/><path class="u" d="M309.836,454.277c95.1288,28.996,157.9599,20.0751,190.6381,1.6937,15.8222-8.9,37.5245-34.1166,54.8436-77.3873-80.6993-11.4839-166.5547,12.4953-230.5311,62.8281-5.189,4.1186-10.1671,8.4153-14.9506,12.8655Z"/></g><g id="e"><path class="r" d="M728.646,233.3535c-2.2085,2.5682-.7001,4.7817-1.2302,14.2649-.6437,11.5109-3.1644,13.5895-1.0813,16.5969,2.3533,3.3973,6.8386,1.7161,18.8418,4.8345,6.9363,1.802,12.879,3.358,12.879,3.358,3.2098.8357,6.6195.0124,8.9913-2.1785,2.3828-2.1853,3.3877-5.4111,2.6752-8.5404,0,0-.7104-3.1938-1.6968-7.5859-12.0963-7.9258-24.5636-15.3071-37.3475-22.1412-.7725.2506-1.406.6644-2.0315,1.3918Z"/><path class="r" d="M880.8426,516.2337c-.1501,4.1301,4.4488,5.47,12.1937,15.1558,4.4757,5.5973,8.3028,10.4024,8.3028,10.4024,2.07,2.5916,5.2937,3.9743,8.5052,3.6403,3.217-.323,5.9537-2.3045,7.2571-5.2373,0,0,9.9089-21.9964,12.8071-28.8768.2153-.5109.367-1.3594.1909-2.3862-.6946-4.0494-6.4305-5.0585-14.5202-8.9891-9.8552-4.7884-10.7346-7.8543-14.4028-7.0398-3.3066.7341-3.4243,3.4101-9.5283,10.687-7.4092,8.8328-10.6728,8.9878-10.8057,12.6436Z"/><path class="r" d="M838.9262,795.3444c-3.1075,2.7246-.9268,6.9895-2.6591,19.2695-1.0011,7.0964-1.8708,13.1775-1.8708,13.1775-.465,3.284.7409,6.5779,3.1874,8.6851,2.4423,2.1187,5.7615,2.75,8.7894,1.686,0,0,22.8008-7.8838,29.7946-10.4962.5194-.194,1.2407-.6657,1.8669-1.4983,2.4693-3.2837-.7322-8.1489-3.4233-16.7308-3.2785-10.455-1.6515-13.1982-4.7608-15.308-2.8028-1.9018-4.8303-.1514-14.3122.4009-11.5094.6704-13.8614-1.5975-16.6121.8142Z"/><path class="r" d="M619.9149,926.6034c-4.0945-.5614-5.8865,3.8808-16.2968,10.6207-6.0159,3.8949-11.1789,7.2235-11.1789,7.2235-2.7851,1.8011-4.4826,4.8708-4.4707,8.0996.0004,3.2332,1.699,6.1539,4.4871,7.7435,0,0,20.898,12.0542,27.4549,15.6244.4869.2652,1.316.5008,2.3552.4281,4.0985-.2871,5.6749-5.8937,10.3929-13.5508,5.7478-9.3283,8.8861-9.8974,8.4417-13.6285-.4006-3.3634-3.0514-3.7475-9.683-10.5471-8.0495-8.2535-7.8781-11.5163-11.5024-12.0133Z"/><path class="r" d="M371.4353,824.7067c-.6472-4.0818-5.4179-4.512-14.8814-12.5271-5.4688-4.6318-10.1488-8.611-10.1488-8.611-2.5298-2.145-5.9594-2.8817-9.0466-1.9362-3.0948.9358-5.3992,3.4068-6.1141,6.5355,0,0-5.4925,23.4917-7.0131,30.8011-.113.5428-.0987,1.4046.2716,2.3783,1.4606,3.8402,7.2835,3.727,15.9781,6.028,10.5923,2.8032,12.045,5.6426,15.488,4.1378,3.1036-1.3565,2.7044-4.0051,7.2946-12.3203,5.5717-10.0931,8.7446-10.873,8.1717-14.4861Z"/><path class="r" d="M342.7974,573.0036c-.4918.2559-1.1501.8123-1.6699,1.7151-2.0497,3.5607,1.7222,7.9984,5.4416,16.1873.743,1.636,1.317,3.0623,1.7935,4.3434,3.0795-10.7336,7.1102-21.1558,12.1518-31.1047-6.4917,3.2029-14.2099,7.0333-17.717,8.8589Z"/></g></g><g id="f"><path id="g" class="s" d="M512.4227,375.6755c-.7583,1.3271-.4063,3.0186.8316,3.9151,6.4476,4.6695,43.2476,25.0243,46.8186,29.9387,5.5254,7.6042,9.6528,14.4607,12.4262,20.5719,1.1587,2.5531,4.8965,2.2749,5.6296-.4313,2.4965-9.2163.1104-17.1552-1.8467-21.5559-.8-1.7988.2947-3.8574,2.2352-4.1889,4.2102-.7192,10.8669-2.4222,16.5376-6.3951,2.3963-1.6788,1.2819-5.4118-1.643-5.4863-5.1332-.1308-11.8878-1.2265-18.7349-5.0693-6.2953-3.5331-42.118-23.7635-48.2905-28.7153-1.442-1.1569-3.5714-.7717-4.4886.8335-3.1583,5.5276-6.3167,11.0552-9.475,16.5828Z"/><path id="h" class="r" d="M174.8148,380.6682c-1.7461-.969-2.23-9.0428-1.8148-11.6682l-19.2007-20.2723c-2.2474-2.4437-3.1462-5.8382-2.3607-9.0066.7773-3.1541,3.1162-5.6144,6.1848-6.5125l30.2446-8.7554c.8505-2.5101,1.728-5.0103,2.6414-7.4913l-17.299-27.8219c-1.7596-2.8116-1.9907-6.3135-.6127-9.2303,1.3617-2.9211,4.1493-4.8561,7.3481-5.1066l31.488-2.4943c1.3342-2.299,2.6878-4.5774,4.0794-6.8364l-11.7422-30.4749c-1.1922-3.0856-.7487-6.5456,1.1591-9.109,1.9106-2.5788,5.0314-3.9034,8.2439-3.5073l31.5599,3.8371c1.7628-1.9685,3.5417-3.9223,5.3619-5.8509l-5.7736-31.9894c-.5961-3.2551.4941-6.5194,2.8837-8.6482,2.3783-2.1079,5.7137-2.7819,8.8006-1.7677l30.5124,10.0602c2.0901-1.5488,4.2087-3.0838,6.3481-4.5756l.4176-32.3894c.0303-3.2741,1.7402-6.2417,4.4957-7.8299,2.7618-1.5919,6.1816-1.5809,9.0421.027l28.2308,15.877c2.3632-1.1034,4.7426-2.1609,7.1345-3.1955l6.5879-31.4442c.6682-3.1786,2.913-5.7209,5.9384-6.7276,3.0372-1.0073,6.4083-.3063,8.9313,1.8382l24.7781,21.0355c2.5879-.6121,5.1655-1.1776,7.751-1.7071l12.507-29.2366c1.2639-2.9693,3.9745-5.0065,7.1544-5.3679,3.1858-.3724,6.3947.9824,8.4697,3.5592l20.481,25.4379c2.6534-.0724,5.3066-.0945,7.9556-.1004l17.9446-25.9978c1.8252-2.6397,4.8821-4.0789,8.1031-3.7992,3.2176.2679,6.1288,2.225,7.6818,5.1558l15.3964,28.9185c2.6099.4502,5.2178.9415,7.8073,1.4689l22.7416-21.7849c2.3048-2.2066,5.6135-2.994,8.7276-2.0828,3.1282.9127,5.6202,3.3888,6.6051,6.5602l7.2505,24.3384c2.4881.9423,9.6885,7.862,9.8569,9.8546,15.1431,179.1454-42.8569,269.1454-74.8569,287.1454-43.9951,24.7473-147,31-315.1852-62.3318Z"/><path id="i" class="t" d="M416.6517,268.8313s9.1773-41.5786,49.7558-28.6784c0,0,40.4838,25.0557,31.4023,54.4816,0,0-17.3313,43.8615-49.7558,28.6784,0,0-32.8394-7.6867-31.4023-54.4816Z"/><path id="j" class="p" d="M451.2784,262.3353c6.1138,10.6072,4.8179,22.8102-2.8933,27.2548-7.7096,4.4437-18.9185-.5518-25.0323-11.159s-4.8182-22.8108,2.8914-27.2545,18.9206.5519,25.0342,11.1586Z"/><path id="k" class="t" d="M301.3287,325.3925s31.7841-43.492,67.7395-8.0315c0,0,40.5337,42.1237-5.1123,72.1296,0,0-66.9345,23.1212-62.6273-64.0981Z"/><path id="l" class="p" d="M333.2752,331.278c6.3044,10.9379,4.9707,23.5254-2.9834,28.1099s-19.5129-.5718-25.8173-11.5097c-6.3059-10.9405-4.9691-23.5262,2.9818-28.109s19.513.5683,25.8189,11.5088Z"/><g id="m"><path id="n" class="t" d="M457.6063,435.6128s-1.3552,8.2645-9.4633,6.1675c0,0-8.2203-4.4854-6.7533-10.3622,0,0,2.932-8.8006,9.4633-6.1675,0,0,6.5322,1.1564,6.7533,10.3622Z"/><path id="o" class="t" d="M498.6468,412.2641s-5.7744,8.8835-13.2173,2.3059c0,0-8.4137-7.8369.2282-14.2209,0,0,12.8969-5.2608,12.9891,11.9149Z"/></g></g></svg> |
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/branding/pyo3logo.svg | <?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="1080" height="1080" viewBox="0 0 1080 1080"><defs><style>.p{fill:#fff;}.q{fill:#5a9fd4;}.r{fill:#ffd43b;}.s{fill:#e43a25;}.t{fill:#030404;}.u{fill:#3e6d90;}.v{fill:#1a1a1a;}</style></defs><g id="a"><rect class="v" width="1080" height="1080"/></g><g id="b"><g id="c"><path class="q" d="M470.1992,170.2002c183.1195-3.4423,368.7289,87.0951,451.4542,255.463,3.7264,7.8904,7.9798,16.9627,11.1247,25.0938,1.6794,4.2844,4.2134,10.3611,5.6123,14.6827,1.2089,3.5004,3.2923,9.5944,4.4559,13.0307,1.1567,3.5621,2.2379,7.5561,3.133,10.8667,25.3786,99.7964,19.2125,209.6855-28.7118,302.0917-89.8475,175.1771-325.4628,261.5867-504.3941,174.0052-.9378-.372-2.7308-1.348-3.6325-1.8014-7.0873-3.7565-15.7297-8.1826-22.2811-12.4553-33.2534-21.2097-62.7693-47.296-88.0664-77.4392-44.995-53.1256-73.9121-121.2598-77.0905-191.2472-5.1268-110.7094,43.8245-216.6098,140.3756-273.929,79.9273-47.6785,183.3157-64.3372,271.5453-30.0944,32.1734,12.7682,61.6289,34.1589,81.6286,62.7829,34.4009,48.2308,46.1475,117.4057,13.0142,169.3145-29.3734,46.4966-83.6013,71.3252-135.6074,81.3171-45.1958,8.336-106.5594,8.624-143.494-23.6-26.7708-23.817-33.0872-66.5725-13.572-96.8889,32.4652-48.0054,114.4256-42.4554,163.6766-31.1086,48.0253,11.5482,96.9553,33.2474,128.2142,73.0777,25.2857,32.4702,30.1323,72.0076,17.3407,110.5293-8.1652,24.6661-22.7548,47.6281-42.5283,64.4565-49.5004,42.6007-131.2154,52.726-192.3812,35.0978-44.4411-13.0305-83.2341-43.1871-108.768-81.3301-4.9598-7.4428-9.4885-15.1876-13.159-23.3322,0,0,.8236-.5673.8236-.5673,61.3908,61.6235,138.0487,93.3511,223.9438,68.8118,34.0447-9.5819,66.0403-29.5225,79.8015-62.4243,6.9608-15.9159,10.5977-34.4516,6.6374-51.346-7.6444-30.8439-38.5743-49.8405-67.5377-61.6926-35.3726-13.7305-75.2487-20.3625-112.8366-15.4416-6.9515,1.0199-13.485,2.619-18.7512,4.6392-3.7501,1.4975-7.7565,3.3577-9.5432,5.8202.078.0449.0322-.0111.0883.0167.079-.0094.0654.052.0367.2646-.3209,1.5235-.2305,4.4593.4112,6.2976.8105,2.1492,1.0628,3.0448,2.7965,4.2313.8112.6038,2.2382,1.5067,4.172,2.3986,3.876,1.8301,9.5817,3.4748,15.8238,4.5084,20.8172,3.2351,42.8435,1.1259,63.8734-3.7723,32.9335-7.7916,79.8646-28.5445,87.2925-64.1346,4.8007-26.327-10.3932-58.1219-31.6862-74.8435-26.0881-19.834-59.7944-24.2033-92.1538-22.447-58.7691,4.171-118.5053,30.5979-156.6319,75.9366-23.4586,28.1706-36.574,63.2723-40.7303,99.6784-2.9288,25.0438-1.808,50.5872,4.5861,74.9208,10.3896,41.2564,35.9388,77.7984,67.3632,106.2914,15.0343,13.4211,31.4966,26.1029,49.5866,34.7971,98.2459,47.0762,224.0064,12.5372,297.2051-65.1348,2.0739-2.0613,5.018-5.434,6.9475-7.6836,1.9995-2.1707,4.7326-5.5634,6.5553-7.9457,3.2348-3.7416,6.3054-8.2929,9.1848-12.3315.5032-.7049,1.7394-2.4365,2.2336-3.1225l.6793-1.0822,5.4612-8.6378c39.1637-65.6316,43.8287-148.2221,25.6387-221.8856-.7198-3.4049-3.296-10.2818-4.3398-13.524-.4323-1.4425-1.2201-3.5227-1.7862-4.9168-1.1377-2.8073-2.6909-6.9741-3.844-9.7495-1.0835-2.3654-3.2295-7.2126-4.2896-9.5931-12.8829-27.3433-30.3804-52.3757-51.0358-74.5277-64.6754-68.9074-158.1879-106.9822-251.7216-114.374-4.1942-.2988-10.1276-.5664-14.3115-.8859-4.9774-.3007-12.4258-.3213-17.2303-.5325,0,.0002-.6015-124.5994-.6015-124.5994h0Z"/></g><g id="d"><path class="u" d="M525.876,392.3208c-.9685,1.695-.519,3.8555,1.0621,5.0006,8.2352,5.9642,28.4158,17.9125,32.9768,24.1895,7.0574,9.7125,12.3291,18.47,15.8714,26.2755,1.4799,3.261,6.2541,2.9056,7.1904-.5509,3.1887-11.7716.141-21.9116-2.3587-27.5324-1.0217-2.2975.3764-4.9269,2.8549-5.3503,5.3774-.9186,13.8798-3.0937,21.1227-8.1682,3.0606-2.1443,1.6373-6.9122-2.0985-7.0074-6.5564-.167-15.1837-1.5665-23.9292-6.4747-8.0407-4.5127-26.9731-16.3022-34.8568-22.6269-1.8419-1.4776-4.5616-.9856-5.7331,1.0646-4.034,7.0602-8.068,14.1203-12.102,21.1805Z"/><path class="u" d="M738.4279,629.9719c-3.0709-5.7035-6.6735-11.2543-10.8439-16.6096-.1912-.2435-.391-.4781-.5835-.7203-2.3684,3.6052-4.8704,7.0928-7.5281,10.4346-2.1123,2.6558-4.3118,5.2296-6.5917,7.7228-2.2799,2.4932-4.6405,4.9061-7.075,7.2401-5.1838,4.9698-10.7115,9.5715-16.5021,13.8429,3.3539,4.7073,6.1138,9.7892,8.1168,15.2762,15.3763-10.3981,29.3158-22.7248,41.0073-37.1866Z"/><path class="u" d="M470.1992,170.2002s.6016,124.5995.6015,124.5994c4.8045.2112,12.253.2318,17.2303.5325,4.1839.3195,10.1173.5871,14.3115.8859,24.4694,1.9338,48.9315,5.9893,72.8813,12.1271,6.7089-35.8959,10.1854-78.5311,8.2295-128.3035-37.2323-7.2228-75.2954-10.555-113.2542-9.8414Z"/><path class="u" d="M362.1785,408.5621c-21.2189,12.5969-40.1271,27.5494-56.6787,44.3748,97.5591,30.605,161.802,21.6932,194.9742,3.0338,17.7859-10.0046,43.007-40.6061,61.0737-94.3199-68.8964-6.4874-140.4964,11.7922-199.3693,46.9113Z"/></g><g id="e"><path class="r" d="M728.646,233.3535c-2.2085,2.5682-.7001,4.7817-1.2302,14.2649-.6437,11.5109-3.1644,13.5895-1.0813,16.5969,2.3533,3.3973,6.8386,1.7161,18.8418,4.8345,6.9363,1.802,12.879,3.358,12.879,3.358,3.2098.8357,6.6195.0124,8.9913-2.1785,2.3828-2.1853,3.3877-5.4111,2.6752-8.5404,0,0-.7104-3.1938-1.6968-7.5859-12.0963-7.9258-24.5636-15.3071-37.3475-22.1412-.7725.2506-1.406.6644-2.0315,1.3918Z"/><path class="r" d="M880.8426,516.2337c-.1501,4.1301,4.4488,5.47,12.1937,15.1558,4.4757,5.5973,8.3028,10.4024,8.3028,10.4024,2.07,2.5916,5.2937,3.9743,8.5052,3.6403,3.217-.323,5.9537-2.3045,7.2571-5.2373,0,0,9.9089-21.9964,12.8071-28.8768.2153-.5109.367-1.3594.1909-2.3862-.6946-4.0494-6.4305-5.0585-14.5202-8.9891-9.8552-4.7884-10.7346-7.8543-14.4028-7.0398-3.3066.7341-3.4243,3.4101-9.5283,10.687-7.4092,8.8328-10.6728,8.9878-10.8057,12.6436Z"/><path class="r" d="M838.9262,795.3444c-3.1075,2.7246-.9268,6.9895-2.6591,19.2695-1.0011,7.0964-1.8708,13.1775-1.8708,13.1775-.465,3.284.7409,6.5779,3.1874,8.6851,2.4423,2.1187,5.7615,2.75,8.7894,1.686,0,0,22.8008-7.8838,29.7946-10.4962.5194-.194,1.2407-.6657,1.8669-1.4983,2.4693-3.2837-.7322-8.1489-3.4233-16.7308-3.2785-10.455-1.6515-13.1982-4.7608-15.308-2.8028-1.9018-4.8303-.1514-14.3122.4009-11.5094.6704-13.8614-1.5975-16.6121.8142Z"/><path class="r" d="M619.9149,926.6034c-4.0945-.5614-5.8865,3.8808-16.2968,10.6207-6.0159,3.8949-11.1789,7.2235-11.1789,7.2235-2.7851,1.8011-4.4826,4.8708-4.4707,8.0996.0004,3.2332,1.699,6.1539,4.4871,7.7435,0,0,20.898,12.0542,27.4549,15.6244.4869.2652,1.316.5008,2.3552.4281,4.0985-.2871,5.6749-5.8937,10.3929-13.5508,5.7478-9.3283,8.8861-9.8974,8.4417-13.6285-.4006-3.3634-3.0514-3.7475-9.683-10.5471-8.0495-8.2535-7.8781-11.5163-11.5024-12.0133Z"/><path class="r" d="M371.4353,824.7067c-.6472-4.0818-5.4179-4.512-14.8814-12.5271-5.4688-4.6318-10.1488-8.611-10.1488-8.611-2.5298-2.145-5.9594-2.8817-9.0466-1.9362-3.0948.9358-5.3992,3.4068-6.1141,6.5355,0,0-5.4925,23.4917-7.0131,30.8011-.113.5428-.0987,1.4046.2716,2.3783,1.4606,3.8402,7.2835,3.727,15.9781,6.028,10.5923,2.8032,12.045,5.6426,15.488,4.1378,3.1036-1.3565,2.7044-4.0051,7.2946-12.3203,5.5717-10.0931,8.7446-10.873,8.1717-14.4861Z"/><path class="r" d="M350.3782,601.5195c3.9575-14.1255,9.4405-27.7554,16.5353-40.5255-6.6313,3.2585-19.3187,9.5123-24.116,12.0096-.4918.2559-1.1501.8123-1.6699,1.7151-2.0497,3.5607,1.7222,7.9984,5.4416,16.1873,2.3421,5.1566,3.131,8.4191,3.809,10.6135Z"/></g></g><g id="f"><path id="g" class="s" d="M512.4227,375.6755c-.7583,1.3271-.4063,3.0186.8316,3.9151,6.4476,4.6695,43.2476,25.0243,46.8186,29.9387,5.5254,7.6042,9.6528,14.4607,12.4262,20.5719,1.1587,2.5531,4.8965,2.2749,5.6296-.4313,2.4965-9.2163.1104-17.1552-1.8467-21.5559-.8-1.7988.2947-3.8574,2.2352-4.1889,4.2102-.7192,10.8669-2.4222,16.5376-6.3951,2.3963-1.6788,1.2819-5.4118-1.643-5.4863-5.1332-.1308-11.8878-1.2265-18.7349-5.0693-6.2953-3.5331-42.118-23.7635-48.2905-28.7153-1.442-1.1569-3.5714-.7717-4.4886.8335-3.1583,5.5276-6.3167,11.0552-9.475,16.5828Z"/><path id="h" class="r" d="M174.8148,380.6682c-1.7461-.969-2.23-9.0428-1.8148-11.6682l-19.2007-20.2723c-2.2474-2.4437-3.1462-5.8382-2.3607-9.0066.7773-3.1541,3.1162-5.6144,6.1848-6.5125l30.2446-8.7554c.8505-2.5101,1.728-5.0103,2.6414-7.4913l-17.299-27.8219c-1.7596-2.8116-1.9907-6.3135-.6127-9.2303,1.3617-2.9211,4.1493-4.8561,7.3481-5.1066l31.488-2.4943c1.3342-2.299,2.6878-4.5774,4.0794-6.8364l-11.7422-30.4749c-1.1922-3.0856-.7487-6.5456,1.1591-9.109,1.9106-2.5788,5.0314-3.9034,8.2439-3.5073l31.5599,3.8371c1.7628-1.9685,3.5417-3.9223,5.3619-5.8509l-5.7736-31.9894c-.5961-3.2551.4941-6.5194,2.8837-8.6482,2.3783-2.1079,5.7137-2.7819,8.8006-1.7677l30.5124,10.0602c2.0901-1.5488,4.2087-3.0838,6.3481-4.5756l.4176-32.3894c.0303-3.2741,1.7402-6.2417,4.4957-7.8299,2.7618-1.5919,6.1816-1.5809,9.0421.027l28.2308,15.877c2.3632-1.1034,4.7426-2.1609,7.1345-3.1955l6.5879-31.4442c.6682-3.1786,2.913-5.7209,5.9384-6.7276,3.0372-1.0073,6.4083-.3063,8.9313,1.8382l24.7781,21.0355c2.5879-.6121,5.1655-1.1776,7.751-1.7071l12.507-29.2366c1.2639-2.9693,3.9745-5.0065,7.1544-5.3679,3.1858-.3724,6.3947.9824,8.4697,3.5592l20.481,25.4379c2.6534-.0724,5.3066-.0945,7.9556-.1004l17.9446-25.9978c1.8252-2.6397,4.8821-4.0789,8.1031-3.7992,3.2176.2679,6.1288,2.225,7.6818,5.1558l15.3964,28.9185c2.6099.4502,5.2178.9415,7.8073,1.4689l22.7416-21.7849c2.3048-2.2066,5.6135-2.994,8.7276-2.0828,3.1282.9127,5.6202,3.3888,6.6051,6.5602l7.2505,24.3384c2.4881.9423,9.6885,7.862,9.8569,9.8546,15.1431,179.1454-42.8569,269.1454-74.8569,287.1454-43.9951,24.7473-147,31-315.1852-62.3318Z"/><path id="i" class="t" d="M416.6517,268.8313s9.1773-41.5786,49.7558-28.6784c0,0,40.4838,25.0557,31.4023,54.4816,0,0-17.3313,43.8615-49.7558,28.6784,0,0-32.8394-7.6867-31.4023-54.4816Z"/><path id="j" class="p" d="M451.2784,262.3353c6.1138,10.6072,4.8179,22.8102-2.8933,27.2548-7.7096,4.4437-18.9185-.5518-25.0323-11.159s-4.8182-22.8108,2.8914-27.2545,18.9206.5519,25.0342,11.1586Z"/><path id="k" class="t" d="M301.3287,325.3925s31.7841-43.492,67.7395-8.0315c0,0,40.5337,42.1237-5.1123,72.1296,0,0-66.9345,23.1212-62.6273-64.0981Z"/><path id="l" class="p" d="M333.2752,331.278c6.3044,10.9379,4.9707,23.5254-2.9834,28.1099s-19.5129-.5718-25.8173-11.5097c-6.3059-10.9405-4.9691-23.5262,2.9818-28.109s19.513.5683,25.8189,11.5088Z"/><g id="m"><path id="n" class="t" d="M457.6063,435.6128s-1.3552,8.2645-9.4633,6.1675c0,0-8.2203-4.4854-6.7533-10.3622,0,0,2.932-8.8006,9.4633-6.1675,0,0,6.5322,1.1564,6.7533,10.3622Z"/><path id="o" class="t" d="M498.6468,412.2641s-5.7744,8.8835-13.2173,2.3059c0,0-8.4137-7.8369.2282-14.2209,0,0,12.8969-5.2608,12.9891,11.9149Z"/></g></g></svg> |
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config/LICENSE-APACHE | Copyright (c) 2017-present PyO3 Project and Contributors. https://github.com/PyO3
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config/Cargo.toml | [package]
name = "pyo3-build-config"
version = "0.23.0-dev"
description = "Build configuration for the PyO3 ecosystem"
authors = ["PyO3 Project and Contributors <https://github.com/PyO3>"]
keywords = ["pyo3", "python", "cpython", "ffi"]
homepage = "https://github.com/pyo3/pyo3"
repository = "https://github.com/pyo3/pyo3"
categories = ["api-bindings", "development-tools::ffi"]
license = "MIT OR Apache-2.0"
edition = "2021"
[dependencies]
once_cell = "1"
python3-dll-a = { version = "0.2.6", optional = true }
target-lexicon = "0.12.14"
[build-dependencies]
python3-dll-a = { version = "0.2.6", optional = true }
target-lexicon = "0.12.14"
[features]
default = []
# Attempt to resolve a Python interpreter config for building in the build
# script. If this feature isn't enabled, the build script no-ops.
resolve-config = []
# This feature is enabled by pyo3 when building an extension module.
extension-module = []
# These features are enabled by pyo3 when building Stable ABI extension modules.
abi3 = []
abi3-py37 = ["abi3-py38"]
abi3-py38 = ["abi3-py39"]
abi3-py39 = ["abi3-py310"]
abi3-py310 = ["abi3-py311"]
abi3-py311 = ["abi3-py312"]
abi3-py312 = ["abi3"]
[package.metadata.docs.rs]
features = ["resolve-config"]
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config/build.rs | // Import some modules from this crate inline to generate the build config.
// Allow dead code because not all code in the modules is used in this build script.
#[path = "src/impl_.rs"]
#[allow(dead_code)]
mod impl_;
#[path = "src/errors.rs"]
#[allow(dead_code)]
mod errors;
use std::{env, path::Path};
use errors::{Context, Result};
use impl_::{make_interpreter_config, InterpreterConfig};
fn configure(interpreter_config: Option<InterpreterConfig>, name: &str) -> Result<bool> {
let target = Path::new(&env::var_os("OUT_DIR").unwrap()).join(name);
if let Some(config) = interpreter_config {
config
.to_writer(&mut std::fs::File::create(&target).with_context(|| {
format!("failed to write config file at {}", target.display())
})?)?;
Ok(true)
} else {
std::fs::File::create(&target)
.with_context(|| format!("failed to create new file at {}", target.display()))?;
Ok(false)
}
}
fn generate_build_configs() -> Result<()> {
// If PYO3_CONFIG_FILE is set, copy it into the crate.
let configured = configure(
InterpreterConfig::from_pyo3_config_file_env().transpose()?,
"pyo3-build-config-file.txt",
)?;
if configured {
// Don't bother trying to find an interpreter on the host system
// if the user-provided config file is present.
configure(None, "pyo3-build-config.txt")?;
} else {
configure(Some(make_interpreter_config()?), "pyo3-build-config.txt")?;
}
Ok(())
}
fn main() {
if std::env::var("CARGO_FEATURE_RESOLVE_CONFIG").is_ok() {
if let Err(e) = generate_build_configs() {
eprintln!("error: {}", e.report());
std::process::exit(1)
}
} else {
eprintln!("resolve-config feature not enabled; build script in no-op mode");
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config/LICENSE-MIT | Copyright (c) 2023-present PyO3 Project and Contributors. https://github.com/PyO3
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config/src/impl_.rs | //! Main implementation module included in both the `pyo3-build-config` library crate
//! and its build script.
// Optional python3.dll import library generator for Windows
#[cfg(feature = "python3-dll-a")]
#[path = "import_lib.rs"]
mod import_lib;
use std::{
collections::{HashMap, HashSet},
env,
ffi::{OsStr, OsString},
fmt::Display,
fs::{self, DirEntry},
io::{BufRead, BufReader, Read, Write},
path::{Path, PathBuf},
process::{Command, Stdio},
str,
str::FromStr,
};
pub use target_lexicon::Triple;
use target_lexicon::{Environment, OperatingSystem};
use crate::{
bail, ensure,
errors::{Context, Error, Result},
warn,
};
/// Minimum Python version PyO3 supports.
pub(crate) const MINIMUM_SUPPORTED_VERSION: PythonVersion = PythonVersion { major: 3, minor: 7 };
/// GraalPy may implement the same CPython version over multiple releases.
const MINIMUM_SUPPORTED_VERSION_GRAALPY: PythonVersion = PythonVersion {
major: 24,
minor: 0,
};
/// Maximum Python version that can be used as minimum required Python version with abi3.
pub(crate) const ABI3_MAX_MINOR: u8 = 12;
/// Gets an environment variable owned by cargo.
///
/// Environment variables set by cargo are expected to be valid UTF8.
pub fn cargo_env_var(var: &str) -> Option<String> {
env::var_os(var).map(|os_string| os_string.to_str().unwrap().into())
}
/// Gets an external environment variable, and registers the build script to rerun if
/// the variable changes.
pub fn env_var(var: &str) -> Option<OsString> {
if cfg!(feature = "resolve-config") {
println!("cargo:rerun-if-env-changed={}", var);
}
env::var_os(var)
}
/// Gets the compilation target triple from environment variables set by Cargo.
///
/// Must be called from a crate build script.
pub fn target_triple_from_env() -> Triple {
env::var("TARGET")
.expect("target_triple_from_env() must be called from a build script")
.parse()
.expect("Unrecognized TARGET environment variable value")
}
/// Configuration needed by PyO3 to build for the correct Python implementation.
///
/// Usually this is queried directly from the Python interpreter, or overridden using the
/// `PYO3_CONFIG_FILE` environment variable.
///
/// When the `PYO3_NO_PYTHON` variable is set, or during cross compile situations, then alternative
/// strategies are used to populate this type.
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
pub struct InterpreterConfig {
/// The Python implementation flavor.
///
/// Serialized to `implementation`.
pub implementation: PythonImplementation,
/// Python `X.Y` version. e.g. `3.9`.
///
/// Serialized to `version`.
pub version: PythonVersion,
/// Whether link library is shared.
///
/// Serialized to `shared`.
pub shared: bool,
/// Whether linking against the stable/limited Python 3 API.
///
/// Serialized to `abi3`.
pub abi3: bool,
/// The name of the link library defining Python.
///
/// This effectively controls the `cargo:rustc-link-lib=<name>` value to
/// control how libpython is linked. Values should not contain the `lib`
/// prefix.
///
/// Serialized to `lib_name`.
pub lib_name: Option<String>,
/// The directory containing the Python library to link against.
///
/// The effectively controls the `cargo:rustc-link-search=native=<path>` value
/// to add an additional library search path for the linker.
///
/// Serialized to `lib_dir`.
pub lib_dir: Option<String>,
/// Path of host `python` executable.
///
/// This is a valid executable capable of running on the host/building machine.
/// For configurations derived by invoking a Python interpreter, it was the
/// executable invoked.
///
/// Serialized to `executable`.
pub executable: Option<String>,
/// Width in bits of pointers on the target machine.
///
/// Serialized to `pointer_width`.
pub pointer_width: Option<u32>,
/// Additional relevant Python build flags / configuration settings.
///
/// Serialized to `build_flags`.
pub build_flags: BuildFlags,
/// Whether to suppress emitting of `cargo:rustc-link-*` lines from the build script.
///
/// Typically, `pyo3`'s build script will emit `cargo:rustc-link-lib=` and
/// `cargo:rustc-link-search=` lines derived from other fields in this struct. In
/// advanced building configurations, the default logic to derive these lines may not
/// be sufficient. This field can be set to `Some(true)` to suppress the emission
/// of these lines.
///
/// If suppression is enabled, `extra_build_script_lines` should contain equivalent
/// functionality or else a build failure is likely.
pub suppress_build_script_link_lines: bool,
/// Additional lines to `println!()` from Cargo build scripts.
///
/// This field can be populated to enable the `pyo3` crate to emit additional lines from its
/// its Cargo build script.
///
/// This crate doesn't populate this field itself. Rather, it is intended to be used with
/// externally provided config files to give them significant control over how the crate
/// is build/configured.
///
/// Serialized to multiple `extra_build_script_line` values.
pub extra_build_script_lines: Vec<String>,
}
impl InterpreterConfig {
#[doc(hidden)]
pub fn build_script_outputs(&self) -> Vec<String> {
// This should have been checked during pyo3-build-config build time.
assert!(self.version >= MINIMUM_SUPPORTED_VERSION);
let mut out = vec![];
for i in MINIMUM_SUPPORTED_VERSION.minor..=self.version.minor {
out.push(format!("cargo:rustc-cfg=Py_3_{}", i));
}
match self.implementation {
PythonImplementation::CPython => {}
PythonImplementation::PyPy => out.push("cargo:rustc-cfg=PyPy".to_owned()),
PythonImplementation::GraalPy => out.push("cargo:rustc-cfg=GraalPy".to_owned()),
}
// If Py_GIL_DISABLED is set, do not build with limited API support
if self.abi3 && !self.build_flags.0.contains(&BuildFlag::Py_GIL_DISABLED) {
out.push("cargo:rustc-cfg=Py_LIMITED_API".to_owned());
}
for flag in &self.build_flags.0 {
match flag {
BuildFlag::Py_GIL_DISABLED => {
out.push("cargo:rustc-cfg=Py_GIL_DISABLED".to_owned())
}
flag => out.push(format!("cargo:rustc-cfg=py_sys_config=\"{}\"", flag)),
}
}
out
}
#[doc(hidden)]
pub fn from_interpreter(interpreter: impl AsRef<Path>) -> Result<Self> {
const SCRIPT: &str = r#"
# Allow the script to run on Python 2, so that nicer error can be printed later.
from __future__ import print_function
import os.path
import platform
import struct
import sys
from sysconfig import get_config_var, get_platform
PYPY = platform.python_implementation() == "PyPy"
GRAALPY = platform.python_implementation() == "GraalVM"
if GRAALPY:
graalpy_ver = map(int, __graalpython__.get_graalvm_version().split('.'));
print("graalpy_major", next(graalpy_ver))
print("graalpy_minor", next(graalpy_ver))
# sys.base_prefix is missing on Python versions older than 3.3; this allows the script to continue
# so that the version mismatch can be reported in a nicer way later.
base_prefix = getattr(sys, "base_prefix", None)
if base_prefix:
# Anaconda based python distributions have a static python executable, but include
# the shared library. Use the shared library for embedding to avoid rust trying to
# LTO the static library (and failing with newer gcc's, because it is old).
ANACONDA = os.path.exists(os.path.join(base_prefix, "conda-meta"))
else:
ANACONDA = False
def print_if_set(varname, value):
if value is not None:
print(varname, value)
# Windows always uses shared linking
WINDOWS = platform.system() == "Windows"
# macOS framework packages use shared linking
FRAMEWORK = bool(get_config_var("PYTHONFRAMEWORK"))
# unix-style shared library enabled
SHARED = bool(get_config_var("Py_ENABLE_SHARED"))
print("implementation", platform.python_implementation())
print("version_major", sys.version_info[0])
print("version_minor", sys.version_info[1])
print("shared", PYPY or GRAALPY or ANACONDA or WINDOWS or FRAMEWORK or SHARED)
print_if_set("ld_version", get_config_var("LDVERSION"))
print_if_set("libdir", get_config_var("LIBDIR"))
print_if_set("base_prefix", base_prefix)
print("executable", sys.executable)
print("calcsize_pointer", struct.calcsize("P"))
print("mingw", get_platform().startswith("mingw"))
print("ext_suffix", get_config_var("EXT_SUFFIX"))
print("gil_disabled", get_config_var("Py_GIL_DISABLED"))
"#;
let output = run_python_script(interpreter.as_ref(), SCRIPT)?;
let map: HashMap<String, String> = parse_script_output(&output);
ensure!(
!map.is_empty(),
"broken Python interpreter: {}",
interpreter.as_ref().display()
);
if let Some(value) = map.get("graalpy_major") {
let graalpy_version = PythonVersion {
major: value
.parse()
.context("failed to parse GraalPy major version")?,
minor: map["graalpy_minor"]
.parse()
.context("failed to parse GraalPy minor version")?,
};
ensure!(
graalpy_version >= MINIMUM_SUPPORTED_VERSION_GRAALPY,
"At least GraalPy version {} needed, got {}",
MINIMUM_SUPPORTED_VERSION_GRAALPY,
graalpy_version
);
};
let shared = map["shared"].as_str() == "True";
let version = PythonVersion {
major: map["version_major"]
.parse()
.context("failed to parse major version")?,
minor: map["version_minor"]
.parse()
.context("failed to parse minor version")?,
};
let abi3 = is_abi3();
let implementation = map["implementation"].parse()?;
let gil_disabled = match map["gil_disabled"].as_str() {
"1" => true,
"0" => false,
"None" => false,
_ => panic!("Unknown Py_GIL_DISABLED value"),
};
let lib_name = if cfg!(windows) {
default_lib_name_windows(
version,
implementation,
abi3,
map["mingw"].as_str() == "True",
// This is the best heuristic currently available to detect debug build
// on Windows from sysconfig - e.g. ext_suffix may be
// `_d.cp312-win_amd64.pyd` for 3.12 debug build
map["ext_suffix"].starts_with("_d."),
gil_disabled,
)
} else {
default_lib_name_unix(
version,
implementation,
map.get("ld_version").map(String::as_str),
gil_disabled,
)
};
let lib_dir = if cfg!(windows) {
map.get("base_prefix")
.map(|base_prefix| format!("{}\\libs", base_prefix))
} else {
map.get("libdir").cloned()
};
// The reason we don't use platform.architecture() here is that it's not
// reliable on macOS. See https://stackoverflow.com/a/1405971/823869.
// Similarly, sys.maxsize is not reliable on Windows. See
// https://stackoverflow.com/questions/1405913/how-do-i-determine-if-my-python-shell-is-executing-in-32bit-or-64bit-mode-on-os/1405971#comment6209952_1405971
// and https://stackoverflow.com/a/3411134/823869.
let calcsize_pointer: u32 = map["calcsize_pointer"]
.parse()
.context("failed to parse calcsize_pointer")?;
Ok(InterpreterConfig {
version,
implementation,
shared,
abi3,
lib_name: Some(lib_name),
lib_dir,
executable: map.get("executable").cloned(),
pointer_width: Some(calcsize_pointer * 8),
build_flags: BuildFlags::from_interpreter(interpreter)?,
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
})
}
/// Generate from parsed sysconfigdata file
///
/// Use [`parse_sysconfigdata`] to generate a hash map of configuration values which may be
/// used to build an [`InterpreterConfig`].
pub fn from_sysconfigdata(sysconfigdata: &Sysconfigdata) -> Result<Self> {
macro_rules! get_key {
($sysconfigdata:expr, $key:literal) => {
$sysconfigdata
.get_value($key)
.ok_or(concat!($key, " not found in sysconfigdata file"))
};
}
macro_rules! parse_key {
($sysconfigdata:expr, $key:literal) => {
get_key!($sysconfigdata, $key)?
.parse()
.context(concat!("could not parse value of ", $key))
};
}
let soabi = get_key!(sysconfigdata, "SOABI")?;
let implementation = PythonImplementation::from_soabi(soabi)?;
let version = parse_key!(sysconfigdata, "VERSION")?;
let shared = match sysconfigdata.get_value("Py_ENABLE_SHARED") {
Some("1") | Some("true") | Some("True") => true,
Some("0") | Some("false") | Some("False") => false,
_ => bail!("expected a bool (1/true/True or 0/false/False) for Py_ENABLE_SHARED"),
};
// macOS framework packages use shared linking (PYTHONFRAMEWORK is the framework name, hence the empty check)
let framework = match sysconfigdata.get_value("PYTHONFRAMEWORK") {
Some(s) => !s.is_empty(),
_ => false,
};
let lib_dir = get_key!(sysconfigdata, "LIBDIR").ok().map(str::to_string);
let gil_disabled = match sysconfigdata.get_value("Py_GIL_DISABLED") {
Some(value) => value == "1",
None => false,
};
let lib_name = Some(default_lib_name_unix(
version,
implementation,
sysconfigdata.get_value("LDVERSION"),
gil_disabled,
));
let pointer_width = parse_key!(sysconfigdata, "SIZEOF_VOID_P")
.map(|bytes_width: u32| bytes_width * 8)
.ok();
let build_flags = BuildFlags::from_sysconfigdata(sysconfigdata);
Ok(InterpreterConfig {
implementation,
version,
shared: shared || framework,
abi3: is_abi3(),
lib_dir,
lib_name,
executable: None,
pointer_width,
build_flags,
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
})
}
/// Import an externally-provided config file.
///
/// The `abi3` features, if set, may apply an `abi3` constraint to the Python version.
#[allow(dead_code)] // only used in build.rs
pub(super) fn from_pyo3_config_file_env() -> Option<Result<Self>> {
cargo_env_var("PYO3_CONFIG_FILE").map(|path| {
let path = Path::new(&path);
println!("cargo:rerun-if-changed={}", path.display());
// Absolute path is necessary because this build script is run with a cwd different to the
// original `cargo build` instruction.
ensure!(
path.is_absolute(),
"PYO3_CONFIG_FILE must be an absolute path"
);
let mut config = InterpreterConfig::from_path(path)
.context("failed to parse contents of PYO3_CONFIG_FILE")?;
// If the abi3 feature is enabled, the minimum Python version is constrained by the abi3
// feature.
//
// TODO: abi3 is a property of the build mode, not the interpreter. Should this be
// removed from `InterpreterConfig`?
config.abi3 |= is_abi3();
config.fixup_for_abi3_version(get_abi3_version())?;
Ok(config)
})
}
#[doc(hidden)]
pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
let config_file = std::fs::File::open(path)
.with_context(|| format!("failed to open PyO3 config file at {}", path.display()))?;
let reader = std::io::BufReader::new(config_file);
InterpreterConfig::from_reader(reader)
}
#[doc(hidden)]
pub fn from_cargo_dep_env() -> Option<Result<Self>> {
cargo_env_var("DEP_PYTHON_PYO3_CONFIG")
.map(|buf| InterpreterConfig::from_reader(&*unescape(&buf)))
}
#[doc(hidden)]
pub fn from_reader(reader: impl Read) -> Result<Self> {
let reader = BufReader::new(reader);
let lines = reader.lines();
macro_rules! parse_value {
($variable:ident, $value:ident) => {
$variable = Some($value.trim().parse().context(format!(
concat!(
"failed to parse ",
stringify!($variable),
" from config value '{}'"
),
$value
))?)
};
}
let mut implementation = None;
let mut version = None;
let mut shared = None;
let mut abi3 = None;
let mut lib_name = None;
let mut lib_dir = None;
let mut executable = None;
let mut pointer_width = None;
let mut build_flags = None;
let mut suppress_build_script_link_lines = None;
let mut extra_build_script_lines = vec![];
for (i, line) in lines.enumerate() {
let line = line.context("failed to read line from config")?;
let mut split = line.splitn(2, '=');
let (key, value) = (
split
.next()
.expect("first splitn value should always be present"),
split
.next()
.ok_or_else(|| format!("expected key=value pair on line {}", i + 1))?,
);
match key {
"implementation" => parse_value!(implementation, value),
"version" => parse_value!(version, value),
"shared" => parse_value!(shared, value),
"abi3" => parse_value!(abi3, value),
"lib_name" => parse_value!(lib_name, value),
"lib_dir" => parse_value!(lib_dir, value),
"executable" => parse_value!(executable, value),
"pointer_width" => parse_value!(pointer_width, value),
"build_flags" => parse_value!(build_flags, value),
"suppress_build_script_link_lines" => {
parse_value!(suppress_build_script_link_lines, value)
}
"extra_build_script_line" => {
extra_build_script_lines.push(value.to_string());
}
unknown => warn!("unknown config key `{}`", unknown),
}
}
let version = version.ok_or("missing value for version")?;
let implementation = implementation.unwrap_or(PythonImplementation::CPython);
let abi3 = abi3.unwrap_or(false);
// Fixup lib_name if it's not set
let lib_name = lib_name.or_else(|| {
if let Ok(Ok(target)) = env::var("TARGET").map(|target| target.parse::<Triple>()) {
default_lib_name_for_target(version, implementation, abi3, &target)
} else {
None
}
});
Ok(InterpreterConfig {
implementation,
version,
shared: shared.unwrap_or(true),
abi3,
lib_name,
lib_dir,
executable,
pointer_width,
build_flags: build_flags.unwrap_or_default(),
suppress_build_script_link_lines: suppress_build_script_link_lines.unwrap_or(false),
extra_build_script_lines,
})
}
#[cfg(feature = "python3-dll-a")]
#[allow(clippy::unnecessary_wraps)]
pub fn generate_import_libs(&mut self) -> Result<()> {
// Auto generate python3.dll import libraries for Windows targets.
if self.lib_dir.is_none() {
let target = target_triple_from_env();
let py_version = if self.abi3 { None } else { Some(self.version) };
self.lib_dir =
import_lib::generate_import_lib(&target, self.implementation, py_version)?;
}
Ok(())
}
#[cfg(not(feature = "python3-dll-a"))]
#[allow(clippy::unnecessary_wraps)]
pub fn generate_import_libs(&mut self) -> Result<()> {
Ok(())
}
#[doc(hidden)]
/// Serialize the `InterpreterConfig` and print it to the environment for Cargo to pass along
/// to dependent packages during build time.
///
/// NB: writing to the cargo environment requires the
/// [`links`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#the-links-manifest-key)
/// manifest key to be set. In this case that means this is called by the `pyo3-ffi` crate and
/// available for dependent package build scripts in `DEP_PYTHON_PYO3_CONFIG`. See
/// documentation for the
/// [`DEP_<name>_<key>`](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts)
/// environment variable.
pub fn to_cargo_dep_env(&self) -> Result<()> {
let mut buf = Vec::new();
self.to_writer(&mut buf)?;
// escape newlines in env var
println!("cargo:PYO3_CONFIG={}", escape(&buf));
Ok(())
}
#[doc(hidden)]
pub fn to_writer(&self, mut writer: impl Write) -> Result<()> {
macro_rules! write_line {
($value:ident) => {
writeln!(writer, "{}={}", stringify!($value), self.$value).context(concat!(
"failed to write ",
stringify!($value),
" to config"
))
};
}
macro_rules! write_option_line {
($value:ident) => {
if let Some(value) = &self.$value {
writeln!(writer, "{}={}", stringify!($value), value).context(concat!(
"failed to write ",
stringify!($value),
" to config"
))
} else {
Ok(())
}
};
}
write_line!(implementation)?;
write_line!(version)?;
write_line!(shared)?;
write_line!(abi3)?;
write_option_line!(lib_name)?;
write_option_line!(lib_dir)?;
write_option_line!(executable)?;
write_option_line!(pointer_width)?;
write_line!(build_flags)?;
write_line!(suppress_build_script_link_lines)?;
for line in &self.extra_build_script_lines {
writeln!(writer, "extra_build_script_line={}", line)
.context("failed to write extra_build_script_line")?;
}
Ok(())
}
/// Run a python script using the [`InterpreterConfig::executable`].
///
/// # Panics
///
/// This function will panic if the [`executable`](InterpreterConfig::executable) is `None`.
pub fn run_python_script(&self, script: &str) -> Result<String> {
run_python_script_with_envs(
Path::new(self.executable.as_ref().expect("no interpreter executable")),
script,
std::iter::empty::<(&str, &str)>(),
)
}
/// Run a python script using the [`InterpreterConfig::executable`] with additional
/// environment variables (e.g. PYTHONPATH) set.
///
/// # Panics
///
/// This function will panic if the [`executable`](InterpreterConfig::executable) is `None`.
pub fn run_python_script_with_envs<I, K, V>(&self, script: &str, envs: I) -> Result<String>
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
run_python_script_with_envs(
Path::new(self.executable.as_ref().expect("no interpreter executable")),
script,
envs,
)
}
/// Lowers the configured version to the abi3 version, if set.
fn fixup_for_abi3_version(&mut self, abi3_version: Option<PythonVersion>) -> Result<()> {
// PyPy doesn't support abi3; don't adjust the version
if self.implementation.is_pypy() || self.implementation.is_graalpy() {
return Ok(());
}
if let Some(version) = abi3_version {
ensure!(
version <= self.version,
"cannot set a minimum Python version {} higher than the interpreter version {} \
(the minimum Python version is implied by the abi3-py3{} feature)",
version,
self.version,
version.minor,
);
self.version = version;
}
Ok(())
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PythonVersion {
pub major: u8,
pub minor: u8,
}
impl PythonVersion {
const PY37: Self = PythonVersion { major: 3, minor: 7 };
}
impl Display for PythonVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}", self.major, self.minor)
}
}
impl FromStr for PythonVersion {
type Err = crate::errors::Error;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let mut split = value.splitn(2, '.');
let (major, minor) = (
split
.next()
.expect("first splitn value should always be present"),
split.next().ok_or("expected major.minor version")?,
);
Ok(Self {
major: major.parse().context("failed to parse major version")?,
minor: minor.parse().context("failed to parse minor version")?,
})
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum PythonImplementation {
CPython,
PyPy,
GraalPy,
}
impl PythonImplementation {
#[doc(hidden)]
pub fn is_pypy(self) -> bool {
self == PythonImplementation::PyPy
}
#[doc(hidden)]
pub fn is_graalpy(self) -> bool {
self == PythonImplementation::GraalPy
}
#[doc(hidden)]
pub fn from_soabi(soabi: &str) -> Result<Self> {
if soabi.starts_with("pypy") {
Ok(PythonImplementation::PyPy)
} else if soabi.starts_with("cpython") {
Ok(PythonImplementation::CPython)
} else if soabi.starts_with("graalpy") {
Ok(PythonImplementation::GraalPy)
} else {
bail!("unsupported Python interpreter");
}
}
}
impl Display for PythonImplementation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PythonImplementation::CPython => write!(f, "CPython"),
PythonImplementation::PyPy => write!(f, "PyPy"),
PythonImplementation::GraalPy => write!(f, "GraalVM"),
}
}
}
impl FromStr for PythonImplementation {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"CPython" => Ok(PythonImplementation::CPython),
"PyPy" => Ok(PythonImplementation::PyPy),
"GraalVM" => Ok(PythonImplementation::GraalPy),
_ => bail!("unknown interpreter: {}", s),
}
}
}
/// Checks if we should look for a Python interpreter installation
/// to get the target interpreter configuration.
///
/// Returns `false` if `PYO3_NO_PYTHON` environment variable is set.
fn have_python_interpreter() -> bool {
env_var("PYO3_NO_PYTHON").is_none()
}
/// Checks if `abi3` or any of the `abi3-py3*` features is enabled for the PyO3 crate.
///
/// Must be called from a PyO3 crate build script.
fn is_abi3() -> bool {
cargo_env_var("CARGO_FEATURE_ABI3").is_some()
|| env_var("PYO3_USE_ABI3_FORWARD_COMPATIBILITY").map_or(false, |os_str| os_str == "1")
}
/// Gets the minimum supported Python version from PyO3 `abi3-py*` features.
///
/// Must be called from a PyO3 crate build script.
pub fn get_abi3_version() -> Option<PythonVersion> {
let minor_version = (MINIMUM_SUPPORTED_VERSION.minor..=ABI3_MAX_MINOR)
.find(|i| cargo_env_var(&format!("CARGO_FEATURE_ABI3_PY3{}", i)).is_some());
minor_version.map(|minor| PythonVersion { major: 3, minor })
}
/// Checks if the `extension-module` feature is enabled for the PyO3 crate.
///
/// Must be called from a PyO3 crate build script.
pub fn is_extension_module() -> bool {
cargo_env_var("CARGO_FEATURE_EXTENSION_MODULE").is_some()
}
/// Checks if we need to link to `libpython` for the current build target.
///
/// Must be called from a PyO3 crate build script.
pub fn is_linking_libpython() -> bool {
is_linking_libpython_for_target(&target_triple_from_env())
}
/// Checks if we need to link to `libpython` for the target.
///
/// Must be called from a PyO3 crate build script.
fn is_linking_libpython_for_target(target: &Triple) -> bool {
target.operating_system == OperatingSystem::Windows
// See https://github.com/PyO3/pyo3/issues/4068#issuecomment-2051159852
|| target.operating_system == OperatingSystem::Aix
|| target.environment == Environment::Android
|| target.environment == Environment::Androideabi
|| !is_extension_module()
}
/// Checks if we need to discover the Python library directory
/// to link the extension module binary.
///
/// Must be called from a PyO3 crate build script.
fn require_libdir_for_target(target: &Triple) -> bool {
let is_generating_libpython = cfg!(feature = "python3-dll-a")
&& target.operating_system == OperatingSystem::Windows
&& is_abi3();
is_linking_libpython_for_target(target) && !is_generating_libpython
}
/// Configuration needed by PyO3 to cross-compile for a target platform.
///
/// Usually this is collected from the environment (i.e. `PYO3_CROSS_*` and `CARGO_CFG_TARGET_*`)
/// when a cross-compilation configuration is detected.
#[derive(Debug, PartialEq, Eq)]
pub struct CrossCompileConfig {
/// The directory containing the Python library to link against.
pub lib_dir: Option<PathBuf>,
/// The version of the Python library to link against.
version: Option<PythonVersion>,
/// The target Python implementation hint (CPython, PyPy, GraalPy, ...)
implementation: Option<PythonImplementation>,
/// The compile target triple (e.g. aarch64-unknown-linux-gnu)
target: Triple,
}
impl CrossCompileConfig {
/// Creates a new cross compile config struct from PyO3 environment variables
/// and the build environment when cross compilation mode is detected.
///
/// Returns `None` when not cross compiling.
fn try_from_env_vars_host_target(
env_vars: CrossCompileEnvVars,
host: &Triple,
target: &Triple,
) -> Result<Option<Self>> {
if env_vars.any() || Self::is_cross_compiling_from_to(host, target) {
let lib_dir = env_vars.lib_dir_path()?;
let version = env_vars.parse_version()?;
let implementation = env_vars.parse_implementation()?;
let target = target.clone();
Ok(Some(CrossCompileConfig {
lib_dir,
version,
implementation,
target,
}))
} else {
Ok(None)
}
}
/// Checks if compiling on `host` for `target` required "real" cross compilation.
///
/// Returns `false` if the target Python interpreter can run on the host.
fn is_cross_compiling_from_to(host: &Triple, target: &Triple) -> bool {
// Not cross-compiling if arch-vendor-os is all the same
// e.g. x86_64-unknown-linux-musl on x86_64-unknown-linux-gnu host
// x86_64-pc-windows-gnu on x86_64-pc-windows-msvc host
let mut compatible = host.architecture == target.architecture
&& host.vendor == target.vendor
&& host.operating_system == target.operating_system;
// Not cross-compiling to compile for 32-bit Python from windows 64-bit
compatible |= target.operating_system == OperatingSystem::Windows
&& host.operating_system == OperatingSystem::Windows;
// Not cross-compiling to compile for x86-64 Python from macOS arm64 and vice versa
compatible |= target.operating_system == OperatingSystem::Darwin
&& host.operating_system == OperatingSystem::Darwin;
!compatible
}
/// Converts `lib_dir` member field to an UTF-8 string.
///
/// The conversion can not fail because `PYO3_CROSS_LIB_DIR` variable
/// is ensured contain a valid UTF-8 string.
fn lib_dir_string(&self) -> Option<String> {
self.lib_dir
.as_ref()
.map(|s| s.to_str().unwrap().to_owned())
}
}
/// PyO3-specific cross compile environment variable values
struct CrossCompileEnvVars {
/// `PYO3_CROSS`
pyo3_cross: Option<OsString>,
/// `PYO3_CROSS_LIB_DIR`
pyo3_cross_lib_dir: Option<OsString>,
/// `PYO3_CROSS_PYTHON_VERSION`
pyo3_cross_python_version: Option<OsString>,
/// `PYO3_CROSS_PYTHON_IMPLEMENTATION`
pyo3_cross_python_implementation: Option<OsString>,
}
impl CrossCompileEnvVars {
/// Grabs the PyO3 cross-compile variables from the environment.
///
/// Registers the build script to rerun if any of the variables changes.
fn from_env() -> Self {
CrossCompileEnvVars {
pyo3_cross: env_var("PYO3_CROSS"),
pyo3_cross_lib_dir: env_var("PYO3_CROSS_LIB_DIR"),
pyo3_cross_python_version: env_var("PYO3_CROSS_PYTHON_VERSION"),
pyo3_cross_python_implementation: env_var("PYO3_CROSS_PYTHON_IMPLEMENTATION"),
}
}
/// Checks if any of the variables is set.
fn any(&self) -> bool {
self.pyo3_cross.is_some()
|| self.pyo3_cross_lib_dir.is_some()
|| self.pyo3_cross_python_version.is_some()
|| self.pyo3_cross_python_implementation.is_some()
}
/// Parses `PYO3_CROSS_PYTHON_VERSION` environment variable value
/// into `PythonVersion`.
fn parse_version(&self) -> Result<Option<PythonVersion>> {
let version = self
.pyo3_cross_python_version
.as_ref()
.map(|os_string| {
let utf8_str = os_string
.to_str()
.ok_or("PYO3_CROSS_PYTHON_VERSION is not valid a UTF-8 string")?;
utf8_str
.parse()
.context("failed to parse PYO3_CROSS_PYTHON_VERSION")
})
.transpose()?;
Ok(version)
}
/// Parses `PYO3_CROSS_PYTHON_IMPLEMENTATION` environment variable value
/// into `PythonImplementation`.
fn parse_implementation(&self) -> Result<Option<PythonImplementation>> {
let implementation = self
.pyo3_cross_python_implementation
.as_ref()
.map(|os_string| {
let utf8_str = os_string
.to_str()
.ok_or("PYO3_CROSS_PYTHON_IMPLEMENTATION is not valid a UTF-8 string")?;
utf8_str
.parse()
.context("failed to parse PYO3_CROSS_PYTHON_IMPLEMENTATION")
})
.transpose()?;
Ok(implementation)
}
/// Converts the stored `PYO3_CROSS_LIB_DIR` variable value (if any)
/// into a `PathBuf` instance.
///
/// Ensures that the path is a valid UTF-8 string.
fn lib_dir_path(&self) -> Result<Option<PathBuf>> {
let lib_dir = self.pyo3_cross_lib_dir.as_ref().map(PathBuf::from);
if let Some(dir) = lib_dir.as_ref() {
ensure!(
dir.to_str().is_some(),
"PYO3_CROSS_LIB_DIR variable value is not a valid UTF-8 string"
);
}
Ok(lib_dir)
}
}
/// Detect whether we are cross compiling and return an assembled CrossCompileConfig if so.
///
/// This function relies on PyO3 cross-compiling environment variables:
///
/// * `PYO3_CROSS`: If present, forces PyO3 to configure as a cross-compilation.
/// * `PYO3_CROSS_LIB_DIR`: If present, must be set to the directory containing
/// the target's libpython DSO and the associated `_sysconfigdata*.py` file for
/// Unix-like targets, or the Python DLL import libraries for the Windows target.
/// * `PYO3_CROSS_PYTHON_VERSION`: Major and minor version (e.g. 3.9) of the target Python
/// installation. This variable is only needed if PyO3 cannnot determine the version to target
/// from `abi3-py3*` features, or if there are multiple versions of Python present in
/// `PYO3_CROSS_LIB_DIR`.
///
/// See the [PyO3 User Guide](https://pyo3.rs/) for more info on cross-compiling.
pub fn cross_compiling_from_to(
host: &Triple,
target: &Triple,
) -> Result<Option<CrossCompileConfig>> {
let env_vars = CrossCompileEnvVars::from_env();
CrossCompileConfig::try_from_env_vars_host_target(env_vars, host, target)
}
/// Detect whether we are cross compiling from Cargo and `PYO3_CROSS_*` environment
/// variables and return an assembled `CrossCompileConfig` if so.
///
/// This must be called from PyO3's build script, because it relies on environment
/// variables such as `CARGO_CFG_TARGET_OS` which aren't available at any other time.
pub fn cross_compiling_from_cargo_env() -> Result<Option<CrossCompileConfig>> {
let env_vars = CrossCompileEnvVars::from_env();
let host = Triple::host();
let target = target_triple_from_env();
CrossCompileConfig::try_from_env_vars_host_target(env_vars, &host, &target)
}
#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum BuildFlag {
Py_DEBUG,
Py_REF_DEBUG,
Py_TRACE_REFS,
Py_GIL_DISABLED,
COUNT_ALLOCS,
Other(String),
}
impl Display for BuildFlag {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BuildFlag::Other(flag) => write!(f, "{}", flag),
_ => write!(f, "{:?}", self),
}
}
}
impl FromStr for BuildFlag {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Py_DEBUG" => Ok(BuildFlag::Py_DEBUG),
"Py_REF_DEBUG" => Ok(BuildFlag::Py_REF_DEBUG),
"Py_TRACE_REFS" => Ok(BuildFlag::Py_TRACE_REFS),
"Py_GIL_DISABLED" => Ok(BuildFlag::Py_GIL_DISABLED),
"COUNT_ALLOCS" => Ok(BuildFlag::COUNT_ALLOCS),
other => Ok(BuildFlag::Other(other.to_owned())),
}
}
}
/// A list of python interpreter compile-time preprocessor defines.
///
/// PyO3 will pick these up and pass to rustc via `--cfg=py_sys_config={varname}`;
/// this allows using them conditional cfg attributes in the .rs files, so
///
/// ```rust
/// #[cfg(py_sys_config="{varname}")]
/// # struct Foo;
/// ```
///
/// is the equivalent of `#ifdef {varname}` in C.
///
/// see Misc/SpecialBuilds.txt in the python source for what these mean.
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
#[derive(Clone, Default)]
pub struct BuildFlags(pub HashSet<BuildFlag>);
impl BuildFlags {
const ALL: [BuildFlag; 5] = [
BuildFlag::Py_DEBUG,
BuildFlag::Py_REF_DEBUG,
BuildFlag::Py_TRACE_REFS,
BuildFlag::Py_GIL_DISABLED,
BuildFlag::COUNT_ALLOCS,
];
pub fn new() -> Self {
BuildFlags(HashSet::new())
}
fn from_sysconfigdata(config_map: &Sysconfigdata) -> Self {
Self(
BuildFlags::ALL
.iter()
.filter(|flag| {
config_map
.get_value(flag.to_string())
.map_or(false, |value| value == "1")
})
.cloned()
.collect(),
)
.fixup()
}
/// Examine python's compile flags to pass to cfg by launching
/// the interpreter and printing variables of interest from
/// sysconfig.get_config_vars.
fn from_interpreter(interpreter: impl AsRef<Path>) -> Result<Self> {
// sysconfig is missing all the flags on windows for Python 3.12 and
// older, so we can't actually query the interpreter directly for its
// build flags on those versions.
if cfg!(windows) {
let script = String::from("import sys;print(sys.version_info < (3, 13))");
let stdout = run_python_script(interpreter.as_ref(), &script)?;
if stdout.trim_end() == "True" {
return Ok(Self::new());
}
}
let mut script = String::from("import sysconfig\n");
script.push_str("config = sysconfig.get_config_vars()\n");
for k in &BuildFlags::ALL {
use std::fmt::Write;
writeln!(&mut script, "print(config.get('{}', '0'))", k).unwrap();
}
let stdout = run_python_script(interpreter.as_ref(), &script)?;
let split_stdout: Vec<&str> = stdout.trim_end().lines().collect();
ensure!(
split_stdout.len() == BuildFlags::ALL.len(),
"Python stdout len didn't return expected number of lines: {}",
split_stdout.len()
);
let flags = BuildFlags::ALL
.iter()
.zip(split_stdout)
.filter(|(_, flag_value)| *flag_value == "1")
.map(|(flag, _)| flag.clone())
.collect();
Ok(Self(flags).fixup())
}
fn fixup(mut self) -> Self {
if self.0.contains(&BuildFlag::Py_DEBUG) {
self.0.insert(BuildFlag::Py_REF_DEBUG);
}
self
}
}
impl Display for BuildFlags {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut first = true;
for flag in &self.0 {
if first {
first = false;
} else {
write!(f, ",")?;
}
write!(f, "{}", flag)?;
}
Ok(())
}
}
impl FromStr for BuildFlags {
type Err = std::convert::Infallible;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let mut flags = HashSet::new();
for flag in value.split_terminator(',') {
flags.insert(flag.parse().unwrap());
}
Ok(BuildFlags(flags))
}
}
fn parse_script_output(output: &str) -> HashMap<String, String> {
output
.lines()
.filter_map(|line| {
let mut i = line.splitn(2, ' ');
Some((i.next()?.into(), i.next()?.into()))
})
.collect()
}
/// Parsed data from Python sysconfigdata file
///
/// A hash map of all values from a sysconfigdata file.
pub struct Sysconfigdata(HashMap<String, String>);
impl Sysconfigdata {
pub fn get_value<S: AsRef<str>>(&self, k: S) -> Option<&str> {
self.0.get(k.as_ref()).map(String::as_str)
}
#[allow(dead_code)]
fn new() -> Self {
Sysconfigdata(HashMap::new())
}
#[allow(dead_code)]
fn insert<S: Into<String>>(&mut self, k: S, v: S) {
self.0.insert(k.into(), v.into());
}
}
/// Parse sysconfigdata file
///
/// The sysconfigdata is simply a dictionary containing all the build time variables used for the
/// python executable and library. This function necessitates a python interpreter on the host
/// machine to work. Here it is read into a `Sysconfigdata` (hash map), which can be turned into an
/// [`InterpreterConfig`] using
/// [`from_sysconfigdata`](InterpreterConfig::from_sysconfigdata).
pub fn parse_sysconfigdata(sysconfigdata_path: impl AsRef<Path>) -> Result<Sysconfigdata> {
let sysconfigdata_path = sysconfigdata_path.as_ref();
let mut script = fs::read_to_string(sysconfigdata_path).with_context(|| {
format!(
"failed to read config from {}",
sysconfigdata_path.display()
)
})?;
script += r#"
for key, val in build_time_vars.items():
print(key, val)
"#;
let output = run_python_script(&find_interpreter()?, &script)?;
Ok(Sysconfigdata(parse_script_output(&output)))
}
fn starts_with(entry: &DirEntry, pat: &str) -> bool {
let name = entry.file_name();
name.to_string_lossy().starts_with(pat)
}
fn ends_with(entry: &DirEntry, pat: &str) -> bool {
let name = entry.file_name();
name.to_string_lossy().ends_with(pat)
}
/// Finds the sysconfigdata file when the target Python library directory is set.
///
/// Returns `None` if the library directory is not available, and a runtime error
/// when no or multiple sysconfigdata files are found.
fn find_sysconfigdata(cross: &CrossCompileConfig) -> Result<Option<PathBuf>> {
let mut sysconfig_paths = find_all_sysconfigdata(cross)?;
if sysconfig_paths.is_empty() {
if let Some(lib_dir) = cross.lib_dir.as_ref() {
bail!("Could not find _sysconfigdata*.py in {}", lib_dir.display());
} else {
// Continue with the default configuration when PYO3_CROSS_LIB_DIR is not set.
return Ok(None);
}
} else if sysconfig_paths.len() > 1 {
let mut error_msg = String::from(
"Detected multiple possible Python versions. Please set either the \
PYO3_CROSS_PYTHON_VERSION variable to the wanted version or the \
_PYTHON_SYSCONFIGDATA_NAME variable to the wanted sysconfigdata file name.\n\n\
sysconfigdata files found:",
);
for path in sysconfig_paths {
use std::fmt::Write;
write!(&mut error_msg, "\n\t{}", path.display()).unwrap();
}
bail!("{}\n", error_msg);
}
Ok(Some(sysconfig_paths.remove(0)))
}
/// Finds `_sysconfigdata*.py` files for detected Python interpreters.
///
/// From the python source for `_sysconfigdata*.py` is always going to be located at
/// `build/lib.{PLATFORM}-{PY_MINOR_VERSION}` when built from source. The [exact line][1] is defined as:
///
/// ```py
/// pybuilddir = 'build/lib.%s-%s' % (get_platform(), sys.version_info[:2])
/// ```
///
/// Where get_platform returns a kebab-case formatted string containing the os, the architecture and
/// possibly the os' kernel version (not the case on linux). However, when installed using a package
/// manager, the `_sysconfigdata*.py` file is installed in the `${PREFIX}/lib/python3.Y/` directory.
/// The `_sysconfigdata*.py` is generally in a sub-directory of the location of `libpython3.Y.so`.
/// So we must find the file in the following possible locations:
///
/// ```sh
/// # distribution from package manager, (lib_dir may or may not include lib/)
/// ${INSTALL_PREFIX}/lib/python3.Y/_sysconfigdata*.py
/// ${INSTALL_PREFIX}/lib/libpython3.Y.so
/// ${INSTALL_PREFIX}/lib/python3.Y/config-3.Y-${HOST_TRIPLE}/libpython3.Y.so
///
/// # Built from source from host
/// ${CROSS_COMPILED_LOCATION}/build/lib.linux-x86_64-Y/_sysconfigdata*.py
/// ${CROSS_COMPILED_LOCATION}/libpython3.Y.so
///
/// # if cross compiled, kernel release is only present on certain OS targets.
/// ${CROSS_COMPILED_LOCATION}/build/lib.{OS}(-{OS-KERNEL-RELEASE})?-{ARCH}-Y/_sysconfigdata*.py
/// ${CROSS_COMPILED_LOCATION}/libpython3.Y.so
///
/// # PyPy includes a similar file since v73
/// ${INSTALL_PREFIX}/lib/pypy3.Y/_sysconfigdata.py
/// ${INSTALL_PREFIX}/lib_pypy/_sysconfigdata.py
/// ```
///
/// [1]: https://github.com/python/cpython/blob/3.5/Lib/sysconfig.py#L389
///
/// Returns an empty vector when the target Python library directory
/// is not set via `PYO3_CROSS_LIB_DIR`.
pub fn find_all_sysconfigdata(cross: &CrossCompileConfig) -> Result<Vec<PathBuf>> {
let sysconfig_paths = if let Some(lib_dir) = cross.lib_dir.as_ref() {
search_lib_dir(lib_dir, cross).with_context(|| {
format!(
"failed to search the lib dir at 'PYO3_CROSS_LIB_DIR={}'",
lib_dir.display()
)
})?
} else {
return Ok(Vec::new());
};
let sysconfig_name = env_var("_PYTHON_SYSCONFIGDATA_NAME");
let mut sysconfig_paths = sysconfig_paths
.iter()
.filter_map(|p| {
let canonical = fs::canonicalize(p).ok();
match &sysconfig_name {
Some(_) => canonical.filter(|p| p.file_stem() == sysconfig_name.as_deref()),
None => canonical,
}
})
.collect::<Vec<PathBuf>>();
sysconfig_paths.sort();
sysconfig_paths.dedup();
Ok(sysconfig_paths)
}
fn is_pypy_lib_dir(path: &str, v: &Option<PythonVersion>) -> bool {
let pypy_version_pat = if let Some(v) = v {
format!("pypy{}", v)
} else {
"pypy3.".into()
};
path == "lib_pypy" || path.starts_with(&pypy_version_pat)
}
fn is_graalpy_lib_dir(path: &str, v: &Option<PythonVersion>) -> bool {
let graalpy_version_pat = if let Some(v) = v {
format!("graalpy{}", v)
} else {
"graalpy2".into()
};
path == "lib_graalpython" || path.starts_with(&graalpy_version_pat)
}
fn is_cpython_lib_dir(path: &str, v: &Option<PythonVersion>) -> bool {
let cpython_version_pat = if let Some(v) = v {
format!("python{}", v)
} else {
"python3.".into()
};
path.starts_with(&cpython_version_pat)
}
/// recursive search for _sysconfigdata, returns all possibilities of sysconfigdata paths
fn search_lib_dir(path: impl AsRef<Path>, cross: &CrossCompileConfig) -> Result<Vec<PathBuf>> {
let mut sysconfig_paths = vec![];
for f in fs::read_dir(path.as_ref()).with_context(|| {
format!(
"failed to list the entries in '{}'",
path.as_ref().display()
)
})? {
sysconfig_paths.extend(match &f {
// Python 3.7+ sysconfigdata with platform specifics
Ok(f) if starts_with(f, "_sysconfigdata_") && ends_with(f, "py") => vec![f.path()],
Ok(f) if f.metadata().map_or(false, |metadata| metadata.is_dir()) => {
let file_name = f.file_name();
let file_name = file_name.to_string_lossy();
if file_name == "build" || file_name == "lib" {
search_lib_dir(f.path(), cross)?
} else if file_name.starts_with("lib.") {
// check if right target os
if !file_name.contains(&cross.target.operating_system.to_string()) {
continue;
}
// Check if right arch
if !file_name.contains(&cross.target.architecture.to_string()) {
continue;
}
search_lib_dir(f.path(), cross)?
} else if is_cpython_lib_dir(&file_name, &cross.version)
|| is_pypy_lib_dir(&file_name, &cross.version)
|| is_graalpy_lib_dir(&file_name, &cross.version)
{
search_lib_dir(f.path(), cross)?
} else {
continue;
}
}
_ => continue,
});
}
// If we got more than one file, only take those that contain the arch name.
// For ubuntu 20.04 with host architecture x86_64 and a foreign architecture of armhf
// this reduces the number of candidates to 1:
//
// $ find /usr/lib/python3.8/ -name '_sysconfigdata*.py' -not -lname '*'
// /usr/lib/python3.8/_sysconfigdata__x86_64-linux-gnu.py
// /usr/lib/python3.8/_sysconfigdata__arm-linux-gnueabihf.py
if sysconfig_paths.len() > 1 {
let temp = sysconfig_paths
.iter()
.filter(|p| {
p.to_string_lossy()
.contains(&cross.target.architecture.to_string())
})
.cloned()
.collect::<Vec<PathBuf>>();
if !temp.is_empty() {
sysconfig_paths = temp;
}
}
Ok(sysconfig_paths)
}
/// Find cross compilation information from sysconfigdata file
///
/// first find sysconfigdata file which follows the pattern [`_sysconfigdata_{abi}_{platform}_{multiarch}`][1]
///
/// [1]: https://github.com/python/cpython/blob/3.8/Lib/sysconfig.py#L348
///
/// Returns `None` when the target Python library directory is not set.
fn cross_compile_from_sysconfigdata(
cross_compile_config: &CrossCompileConfig,
) -> Result<Option<InterpreterConfig>> {
if let Some(path) = find_sysconfigdata(cross_compile_config)? {
let data = parse_sysconfigdata(path)?;
let mut config = InterpreterConfig::from_sysconfigdata(&data)?;
if let Some(cross_lib_dir) = cross_compile_config.lib_dir_string() {
config.lib_dir = Some(cross_lib_dir)
}
Ok(Some(config))
} else {
Ok(None)
}
}
/// Generates "default" cross compilation information for the target.
///
/// This should work for most CPython extension modules when targeting
/// Windows, macOS and Linux.
///
/// Must be called from a PyO3 crate build script.
#[allow(unused_mut)]
fn default_cross_compile(cross_compile_config: &CrossCompileConfig) -> Result<InterpreterConfig> {
let version = cross_compile_config
.version
.or_else(get_abi3_version)
.ok_or_else(||
format!(
"PYO3_CROSS_PYTHON_VERSION or an abi3-py3* feature must be specified \
when cross-compiling and PYO3_CROSS_LIB_DIR is not set.\n\
= help: see the PyO3 user guide for more information: https://pyo3.rs/v{}/building-and-distribution.html#cross-compiling",
env!("CARGO_PKG_VERSION")
)
)?;
let abi3 = is_abi3();
let implementation = cross_compile_config
.implementation
.unwrap_or(PythonImplementation::CPython);
let lib_name =
default_lib_name_for_target(version, implementation, abi3, &cross_compile_config.target);
let mut lib_dir = cross_compile_config.lib_dir_string();
// Auto generate python3.dll import libraries for Windows targets.
#[cfg(feature = "python3-dll-a")]
if lib_dir.is_none() {
let py_version = if abi3 { None } else { Some(version) };
lib_dir = self::import_lib::generate_import_lib(
&cross_compile_config.target,
cross_compile_config
.implementation
.unwrap_or(PythonImplementation::CPython),
py_version,
)?;
}
Ok(InterpreterConfig {
implementation,
version,
shared: true,
abi3,
lib_name,
lib_dir,
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
})
}
/// Generates "default" interpreter configuration when compiling "abi3" extensions
/// without a working Python interpreter.
///
/// `version` specifies the minimum supported Stable ABI CPython version.
///
/// This should work for most CPython extension modules when compiling on
/// Windows, macOS and Linux.
///
/// Must be called from a PyO3 crate build script.
fn default_abi3_config(host: &Triple, version: PythonVersion) -> InterpreterConfig {
// FIXME: PyPy & GraalPy do not support the Stable ABI.
let implementation = PythonImplementation::CPython;
let abi3 = true;
let lib_name = if host.operating_system == OperatingSystem::Windows {
Some(default_lib_name_windows(
version,
implementation,
abi3,
false,
false,
false,
))
} else {
None
};
InterpreterConfig {
implementation,
version,
shared: true,
abi3,
lib_name,
lib_dir: None,
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
}
/// Detects the cross compilation target interpreter configuration from all
/// available sources (PyO3 environment variables, Python sysconfigdata, etc.).
///
/// Returns the "default" target interpreter configuration for Windows and
/// when no target Python interpreter is found.
///
/// Must be called from a PyO3 crate build script.
fn load_cross_compile_config(
cross_compile_config: CrossCompileConfig,
) -> Result<InterpreterConfig> {
let windows = cross_compile_config.target.operating_system == OperatingSystem::Windows;
let config = if windows || !have_python_interpreter() {
// Load the defaults for Windows even when `PYO3_CROSS_LIB_DIR` is set
// since it has no sysconfigdata files in it.
// Also, do not try to look for sysconfigdata when `PYO3_NO_PYTHON` variable is set.
default_cross_compile(&cross_compile_config)?
} else if let Some(config) = cross_compile_from_sysconfigdata(&cross_compile_config)? {
// Try to find and parse sysconfigdata files on other targets.
config
} else {
// Fall back to the defaults when nothing else can be done.
default_cross_compile(&cross_compile_config)?
};
if config.lib_name.is_some() && config.lib_dir.is_none() {
warn!(
"The output binary will link to libpython, \
but PYO3_CROSS_LIB_DIR environment variable is not set. \
Ensure that the target Python library directory is \
in the rustc native library search path."
);
}
Ok(config)
}
// Link against python3.lib for the stable ABI on Windows.
// See https://www.python.org/dev/peps/pep-0384/#linkage
//
// This contains only the limited ABI symbols.
const WINDOWS_ABI3_LIB_NAME: &str = "python3";
fn default_lib_name_for_target(
version: PythonVersion,
implementation: PythonImplementation,
abi3: bool,
target: &Triple,
) -> Option<String> {
if target.operating_system == OperatingSystem::Windows {
Some(default_lib_name_windows(
version,
implementation,
abi3,
false,
false,
false,
))
} else if is_linking_libpython_for_target(target) {
Some(default_lib_name_unix(version, implementation, None, false))
} else {
None
}
}
fn default_lib_name_windows(
version: PythonVersion,
implementation: PythonImplementation,
abi3: bool,
mingw: bool,
debug: bool,
gil_disabled: bool,
) -> String {
if debug {
// CPython bug: linking against python3_d.dll raises error
// https://github.com/python/cpython/issues/101614
if gil_disabled {
format!("python{}{}t_d", version.major, version.minor)
} else {
format!("python{}{}_d", version.major, version.minor)
}
} else if abi3 && !(implementation.is_pypy() || implementation.is_graalpy()) {
WINDOWS_ABI3_LIB_NAME.to_owned()
} else if mingw {
if gil_disabled {
panic!("MinGW free-threaded builds are not currently tested or supported")
}
// https://packages.msys2.org/base/mingw-w64-python
format!("python{}.{}", version.major, version.minor)
} else if gil_disabled {
format!("python{}{}t", version.major, version.minor)
} else {
format!("python{}{}", version.major, version.minor)
}
}
fn default_lib_name_unix(
version: PythonVersion,
implementation: PythonImplementation,
ld_version: Option<&str>,
gil_disabled: bool,
) -> String {
match implementation {
PythonImplementation::CPython => match ld_version {
Some(ld_version) => format!("python{}", ld_version),
None => {
if version > PythonVersion::PY37 {
// PEP 3149 ABI version tags are finally gone
if gil_disabled {
format!("python{}.{}t", version.major, version.minor)
} else {
format!("python{}.{}", version.major, version.minor)
}
} else {
// Work around https://bugs.python.org/issue36707
format!("python{}.{}m", version.major, version.minor)
}
}
},
PythonImplementation::PyPy => match ld_version {
Some(ld_version) => format!("pypy{}-c", ld_version),
None => format!("pypy{}.{}-c", version.major, version.minor),
},
PythonImplementation::GraalPy => "python-native".to_string(),
}
}
/// Run a python script using the specified interpreter binary.
fn run_python_script(interpreter: &Path, script: &str) -> Result<String> {
run_python_script_with_envs(interpreter, script, std::iter::empty::<(&str, &str)>())
}
/// Run a python script using the specified interpreter binary with additional environment
/// variables (e.g. PYTHONPATH) set.
fn run_python_script_with_envs<I, K, V>(interpreter: &Path, script: &str, envs: I) -> Result<String>
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
let out = Command::new(interpreter)
.env("PYTHONIOENCODING", "utf-8")
.envs(envs)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.and_then(|mut child| {
child
.stdin
.as_mut()
.expect("piped stdin")
.write_all(script.as_bytes())?;
child.wait_with_output()
});
match out {
Err(err) => bail!(
"failed to run the Python interpreter at {}: {}",
interpreter.display(),
err
),
Ok(ok) if !ok.status.success() => bail!("Python script failed"),
Ok(ok) => Ok(String::from_utf8(ok.stdout)
.context("failed to parse Python script output as utf-8")?),
}
}
fn venv_interpreter(virtual_env: &OsStr, windows: bool) -> PathBuf {
if windows {
Path::new(virtual_env).join("Scripts").join("python.exe")
} else {
Path::new(virtual_env).join("bin").join("python")
}
}
fn conda_env_interpreter(conda_prefix: &OsStr, windows: bool) -> PathBuf {
if windows {
Path::new(conda_prefix).join("python.exe")
} else {
Path::new(conda_prefix).join("bin").join("python")
}
}
fn get_env_interpreter() -> Option<PathBuf> {
match (env_var("VIRTUAL_ENV"), env_var("CONDA_PREFIX")) {
// Use cfg rather than CARGO_CFG_TARGET_OS because this affects where files are located on the
// build host
(Some(dir), None) => Some(venv_interpreter(&dir, cfg!(windows))),
(None, Some(dir)) => Some(conda_env_interpreter(&dir, cfg!(windows))),
(Some(_), Some(_)) => {
warn!(
"Both VIRTUAL_ENV and CONDA_PREFIX are set. PyO3 will ignore both of these for \
locating the Python interpreter until you unset one of them."
);
None
}
(None, None) => None,
}
}
/// Attempts to locate a python interpreter.
///
/// Locations are checked in the order listed:
/// 1. If `PYO3_PYTHON` is set, this interpreter is used.
/// 2. If in a virtualenv, that environment's interpreter is used.
/// 3. `python`, if this is functional a Python 3.x interpreter
/// 4. `python3`, as above
pub fn find_interpreter() -> Result<PathBuf> {
// Trigger rebuilds when `PYO3_ENVIRONMENT_SIGNATURE` env var value changes
// See https://github.com/PyO3/pyo3/issues/2724
println!("cargo:rerun-if-env-changed=PYO3_ENVIRONMENT_SIGNATURE");
if let Some(exe) = env_var("PYO3_PYTHON") {
Ok(exe.into())
} else if let Some(env_interpreter) = get_env_interpreter() {
Ok(env_interpreter)
} else {
println!("cargo:rerun-if-env-changed=PATH");
["python", "python3"]
.iter()
.find(|bin| {
if let Ok(out) = Command::new(bin).arg("--version").output() {
// begin with `Python 3.X.X :: additional info`
out.stdout.starts_with(b"Python 3")
|| out.stderr.starts_with(b"Python 3")
|| out.stdout.starts_with(b"GraalPy 3")
} else {
false
}
})
.map(PathBuf::from)
.ok_or_else(|| "no Python 3.x interpreter found".into())
}
}
/// Locates and extracts the build host Python interpreter configuration.
///
/// Lowers the configured Python version to `abi3_version` if required.
fn get_host_interpreter(abi3_version: Option<PythonVersion>) -> Result<InterpreterConfig> {
let interpreter_path = find_interpreter()?;
let mut interpreter_config = InterpreterConfig::from_interpreter(interpreter_path)?;
interpreter_config.fixup_for_abi3_version(abi3_version)?;
Ok(interpreter_config)
}
/// Generates an interpreter config suitable for cross-compilation.
///
/// This must be called from PyO3's build script, because it relies on environment variables such as
/// CARGO_CFG_TARGET_OS which aren't available at any other time.
pub fn make_cross_compile_config() -> Result<Option<InterpreterConfig>> {
let interpreter_config = if let Some(cross_config) = cross_compiling_from_cargo_env()? {
let mut interpreter_config = load_cross_compile_config(cross_config)?;
interpreter_config.fixup_for_abi3_version(get_abi3_version())?;
Some(interpreter_config)
} else {
None
};
Ok(interpreter_config)
}
/// Generates an interpreter config which will be hard-coded into the pyo3-build-config crate.
/// Only used by `pyo3-build-config` build script.
#[allow(dead_code, unused_mut)]
pub fn make_interpreter_config() -> Result<InterpreterConfig> {
let host = Triple::host();
let abi3_version = get_abi3_version();
// See if we can safely skip the Python interpreter configuration detection.
// Unix "abi3" extension modules can usually be built without any interpreter.
let need_interpreter = abi3_version.is_none() || require_libdir_for_target(&host);
if have_python_interpreter() {
match get_host_interpreter(abi3_version) {
Ok(interpreter_config) => return Ok(interpreter_config),
// Bail if the interpreter configuration is required to build.
Err(e) if need_interpreter => return Err(e),
_ => {
// Fall back to the "abi3" defaults just as if `PYO3_NO_PYTHON`
// environment variable was set.
warn!("Compiling without a working Python interpreter.");
}
}
} else {
ensure!(
abi3_version.is_some(),
"An abi3-py3* feature must be specified when compiling without a Python interpreter."
);
};
let mut interpreter_config = default_abi3_config(&host, abi3_version.unwrap());
// Auto generate python3.dll import libraries for Windows targets.
#[cfg(feature = "python3-dll-a")]
{
let py_version = if interpreter_config.abi3 {
None
} else {
Some(interpreter_config.version)
};
interpreter_config.lib_dir = self::import_lib::generate_import_lib(
&host,
interpreter_config.implementation,
py_version,
)?;
}
Ok(interpreter_config)
}
fn escape(bytes: &[u8]) -> String {
let mut escaped = String::with_capacity(2 * bytes.len());
for byte in bytes {
const LUT: &[u8; 16] = b"0123456789abcdef";
escaped.push(LUT[(byte >> 4) as usize] as char);
escaped.push(LUT[(byte & 0x0F) as usize] as char);
}
escaped
}
fn unescape(escaped: &str) -> Vec<u8> {
assert!(escaped.len() % 2 == 0, "invalid hex encoding");
let mut bytes = Vec::with_capacity(escaped.len() / 2);
for chunk in escaped.as_bytes().chunks_exact(2) {
fn unhex(hex: u8) -> u8 {
match hex {
b'a'..=b'f' => hex - b'a' + 10,
b'0'..=b'9' => hex - b'0',
_ => panic!("invalid hex encoding"),
}
}
bytes.push(unhex(chunk[0]) << 4 | unhex(chunk[1]));
}
bytes
}
#[cfg(test)]
mod tests {
use target_lexicon::triple;
use super::*;
#[test]
fn test_config_file_roundtrip() {
let config = InterpreterConfig {
abi3: true,
build_flags: BuildFlags::default(),
pointer_width: Some(32),
executable: Some("executable".into()),
implementation: PythonImplementation::CPython,
lib_name: Some("lib_name".into()),
lib_dir: Some("lib_dir".into()),
shared: true,
version: MINIMUM_SUPPORTED_VERSION,
suppress_build_script_link_lines: true,
extra_build_script_lines: vec!["cargo:test1".to_string(), "cargo:test2".to_string()],
};
let mut buf: Vec<u8> = Vec::new();
config.to_writer(&mut buf).unwrap();
assert_eq!(config, InterpreterConfig::from_reader(&*buf).unwrap());
// And some different options, for variety
let config = InterpreterConfig {
abi3: false,
build_flags: {
let mut flags = HashSet::new();
flags.insert(BuildFlag::Py_DEBUG);
flags.insert(BuildFlag::Other(String::from("Py_SOME_FLAG")));
BuildFlags(flags)
},
pointer_width: None,
executable: None,
implementation: PythonImplementation::PyPy,
lib_dir: None,
lib_name: None,
shared: true,
version: PythonVersion {
major: 3,
minor: 10,
},
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
};
let mut buf: Vec<u8> = Vec::new();
config.to_writer(&mut buf).unwrap();
assert_eq!(config, InterpreterConfig::from_reader(&*buf).unwrap());
}
#[test]
fn test_config_file_roundtrip_with_escaping() {
let config = InterpreterConfig {
abi3: true,
build_flags: BuildFlags::default(),
pointer_width: Some(32),
executable: Some("executable".into()),
implementation: PythonImplementation::CPython,
lib_name: Some("lib_name".into()),
lib_dir: Some("lib_dir\\n".into()),
shared: true,
version: MINIMUM_SUPPORTED_VERSION,
suppress_build_script_link_lines: true,
extra_build_script_lines: vec!["cargo:test1".to_string(), "cargo:test2".to_string()],
};
let mut buf: Vec<u8> = Vec::new();
config.to_writer(&mut buf).unwrap();
let buf = unescape(&escape(&buf));
assert_eq!(config, InterpreterConfig::from_reader(&*buf).unwrap());
}
#[test]
fn test_config_file_defaults() {
// Only version is required
assert_eq!(
InterpreterConfig::from_reader("version=3.7".as_bytes()).unwrap(),
InterpreterConfig {
version: PythonVersion { major: 3, minor: 7 },
implementation: PythonImplementation::CPython,
shared: true,
abi3: false,
lib_name: None,
lib_dir: None,
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
)
}
#[test]
fn test_config_file_unknown_keys() {
// ext_suffix is unknown to pyo3-build-config, but it shouldn't error
assert_eq!(
InterpreterConfig::from_reader("version=3.7\next_suffix=.python37.so".as_bytes())
.unwrap(),
InterpreterConfig {
version: PythonVersion { major: 3, minor: 7 },
implementation: PythonImplementation::CPython,
shared: true,
abi3: false,
lib_name: None,
lib_dir: None,
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
)
}
#[test]
fn build_flags_default() {
assert_eq!(BuildFlags::default(), BuildFlags::new());
}
#[test]
fn build_flags_from_sysconfigdata() {
let mut sysconfigdata = Sysconfigdata::new();
assert_eq!(
BuildFlags::from_sysconfigdata(&sysconfigdata).0,
HashSet::new()
);
for flag in &BuildFlags::ALL {
sysconfigdata.insert(flag.to_string(), "0".into());
}
assert_eq!(
BuildFlags::from_sysconfigdata(&sysconfigdata).0,
HashSet::new()
);
let mut expected_flags = HashSet::new();
for flag in &BuildFlags::ALL {
sysconfigdata.insert(flag.to_string(), "1".into());
expected_flags.insert(flag.clone());
}
assert_eq!(
BuildFlags::from_sysconfigdata(&sysconfigdata).0,
expected_flags
);
}
#[test]
fn build_flags_fixup() {
let mut build_flags = BuildFlags::new();
build_flags = build_flags.fixup();
assert!(build_flags.0.is_empty());
build_flags.0.insert(BuildFlag::Py_DEBUG);
build_flags = build_flags.fixup();
// Py_DEBUG implies Py_REF_DEBUG
assert!(build_flags.0.contains(&BuildFlag::Py_REF_DEBUG));
}
#[test]
fn parse_script_output() {
let output = "foo bar\nbar foobar\n\n";
let map = super::parse_script_output(output);
assert_eq!(map.len(), 2);
assert_eq!(map["foo"], "bar");
assert_eq!(map["bar"], "foobar");
}
#[test]
fn config_from_interpreter() {
// Smoke test to just see whether this works
//
// PyO3's CI is dependent on Python being installed, so this should be reliable.
assert!(make_interpreter_config().is_ok())
}
#[test]
fn config_from_empty_sysconfigdata() {
let sysconfigdata = Sysconfigdata::new();
assert!(InterpreterConfig::from_sysconfigdata(&sysconfigdata).is_err());
}
#[test]
fn config_from_sysconfigdata() {
let mut sysconfigdata = Sysconfigdata::new();
// these are the minimal values required such that InterpreterConfig::from_sysconfigdata
// does not error
sysconfigdata.insert("SOABI", "cpython-37m-x86_64-linux-gnu");
sysconfigdata.insert("VERSION", "3.7");
sysconfigdata.insert("Py_ENABLE_SHARED", "1");
sysconfigdata.insert("LIBDIR", "/usr/lib");
sysconfigdata.insert("LDVERSION", "3.7m");
sysconfigdata.insert("SIZEOF_VOID_P", "8");
assert_eq!(
InterpreterConfig::from_sysconfigdata(&sysconfigdata).unwrap(),
InterpreterConfig {
abi3: false,
build_flags: BuildFlags::from_sysconfigdata(&sysconfigdata),
pointer_width: Some(64),
executable: None,
implementation: PythonImplementation::CPython,
lib_dir: Some("/usr/lib".into()),
lib_name: Some("python3.7m".into()),
shared: true,
version: PythonVersion::PY37,
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
);
}
#[test]
fn config_from_sysconfigdata_framework() {
let mut sysconfigdata = Sysconfigdata::new();
sysconfigdata.insert("SOABI", "cpython-37m-x86_64-linux-gnu");
sysconfigdata.insert("VERSION", "3.7");
// PYTHONFRAMEWORK should override Py_ENABLE_SHARED
sysconfigdata.insert("Py_ENABLE_SHARED", "0");
sysconfigdata.insert("PYTHONFRAMEWORK", "Python");
sysconfigdata.insert("LIBDIR", "/usr/lib");
sysconfigdata.insert("LDVERSION", "3.7m");
sysconfigdata.insert("SIZEOF_VOID_P", "8");
assert_eq!(
InterpreterConfig::from_sysconfigdata(&sysconfigdata).unwrap(),
InterpreterConfig {
abi3: false,
build_flags: BuildFlags::from_sysconfigdata(&sysconfigdata),
pointer_width: Some(64),
executable: None,
implementation: PythonImplementation::CPython,
lib_dir: Some("/usr/lib".into()),
lib_name: Some("python3.7m".into()),
shared: true,
version: PythonVersion::PY37,
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
);
sysconfigdata = Sysconfigdata::new();
sysconfigdata.insert("SOABI", "cpython-37m-x86_64-linux-gnu");
sysconfigdata.insert("VERSION", "3.7");
// An empty PYTHONFRAMEWORK means it is not a framework
sysconfigdata.insert("Py_ENABLE_SHARED", "0");
sysconfigdata.insert("PYTHONFRAMEWORK", "");
sysconfigdata.insert("LIBDIR", "/usr/lib");
sysconfigdata.insert("LDVERSION", "3.7m");
sysconfigdata.insert("SIZEOF_VOID_P", "8");
assert_eq!(
InterpreterConfig::from_sysconfigdata(&sysconfigdata).unwrap(),
InterpreterConfig {
abi3: false,
build_flags: BuildFlags::from_sysconfigdata(&sysconfigdata),
pointer_width: Some(64),
executable: None,
implementation: PythonImplementation::CPython,
lib_dir: Some("/usr/lib".into()),
lib_name: Some("python3.7m".into()),
shared: false,
version: PythonVersion::PY37,
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
);
}
#[test]
fn windows_hardcoded_abi3_compile() {
let host = triple!("x86_64-pc-windows-msvc");
let min_version = "3.7".parse().unwrap();
assert_eq!(
default_abi3_config(&host, min_version),
InterpreterConfig {
implementation: PythonImplementation::CPython,
version: PythonVersion { major: 3, minor: 7 },
shared: true,
abi3: true,
lib_name: Some("python3".into()),
lib_dir: None,
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
);
}
#[test]
fn unix_hardcoded_abi3_compile() {
let host = triple!("x86_64-unknown-linux-gnu");
let min_version = "3.9".parse().unwrap();
assert_eq!(
default_abi3_config(&host, min_version),
InterpreterConfig {
implementation: PythonImplementation::CPython,
version: PythonVersion { major: 3, minor: 9 },
shared: true,
abi3: true,
lib_name: None,
lib_dir: None,
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
);
}
#[test]
fn windows_hardcoded_cross_compile() {
let env_vars = CrossCompileEnvVars {
pyo3_cross: None,
pyo3_cross_lib_dir: Some("C:\\some\\path".into()),
pyo3_cross_python_implementation: None,
pyo3_cross_python_version: Some("3.7".into()),
};
let host = triple!("x86_64-unknown-linux-gnu");
let target = triple!("i686-pc-windows-msvc");
let cross_config =
CrossCompileConfig::try_from_env_vars_host_target(env_vars, &host, &target)
.unwrap()
.unwrap();
assert_eq!(
default_cross_compile(&cross_config).unwrap(),
InterpreterConfig {
implementation: PythonImplementation::CPython,
version: PythonVersion { major: 3, minor: 7 },
shared: true,
abi3: false,
lib_name: Some("python37".into()),
lib_dir: Some("C:\\some\\path".into()),
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
);
}
#[test]
fn mingw_hardcoded_cross_compile() {
let env_vars = CrossCompileEnvVars {
pyo3_cross: None,
pyo3_cross_lib_dir: Some("/usr/lib/mingw".into()),
pyo3_cross_python_implementation: None,
pyo3_cross_python_version: Some("3.8".into()),
};
let host = triple!("x86_64-unknown-linux-gnu");
let target = triple!("i686-pc-windows-gnu");
let cross_config =
CrossCompileConfig::try_from_env_vars_host_target(env_vars, &host, &target)
.unwrap()
.unwrap();
assert_eq!(
default_cross_compile(&cross_config).unwrap(),
InterpreterConfig {
implementation: PythonImplementation::CPython,
version: PythonVersion { major: 3, minor: 8 },
shared: true,
abi3: false,
lib_name: Some("python38".into()),
lib_dir: Some("/usr/lib/mingw".into()),
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
);
}
#[test]
fn unix_hardcoded_cross_compile() {
let env_vars = CrossCompileEnvVars {
pyo3_cross: None,
pyo3_cross_lib_dir: Some("/usr/arm64/lib".into()),
pyo3_cross_python_implementation: None,
pyo3_cross_python_version: Some("3.9".into()),
};
let host = triple!("x86_64-unknown-linux-gnu");
let target = triple!("aarch64-unknown-linux-gnu");
let cross_config =
CrossCompileConfig::try_from_env_vars_host_target(env_vars, &host, &target)
.unwrap()
.unwrap();
assert_eq!(
default_cross_compile(&cross_config).unwrap(),
InterpreterConfig {
implementation: PythonImplementation::CPython,
version: PythonVersion { major: 3, minor: 9 },
shared: true,
abi3: false,
lib_name: Some("python3.9".into()),
lib_dir: Some("/usr/arm64/lib".into()),
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
);
}
#[test]
fn pypy_hardcoded_cross_compile() {
let env_vars = CrossCompileEnvVars {
pyo3_cross: None,
pyo3_cross_lib_dir: None,
pyo3_cross_python_implementation: Some("PyPy".into()),
pyo3_cross_python_version: Some("3.10".into()),
};
let triple = triple!("x86_64-unknown-linux-gnu");
let cross_config =
CrossCompileConfig::try_from_env_vars_host_target(env_vars, &triple, &triple)
.unwrap()
.unwrap();
assert_eq!(
default_cross_compile(&cross_config).unwrap(),
InterpreterConfig {
implementation: PythonImplementation::PyPy,
version: PythonVersion {
major: 3,
minor: 10
},
shared: true,
abi3: false,
lib_name: Some("pypy3.10-c".into()),
lib_dir: None,
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
);
}
#[test]
fn default_lib_name_windows() {
use PythonImplementation::*;
assert_eq!(
super::default_lib_name_windows(
PythonVersion { major: 3, minor: 9 },
CPython,
false,
false,
false,
false,
),
"python39",
);
assert_eq!(
super::default_lib_name_windows(
PythonVersion { major: 3, minor: 9 },
CPython,
true,
false,
false,
false,
),
"python3",
);
assert_eq!(
super::default_lib_name_windows(
PythonVersion { major: 3, minor: 9 },
CPython,
false,
true,
false,
false,
),
"python3.9",
);
assert_eq!(
super::default_lib_name_windows(
PythonVersion { major: 3, minor: 9 },
CPython,
true,
true,
false,
false,
),
"python3",
);
assert_eq!(
super::default_lib_name_windows(
PythonVersion { major: 3, minor: 9 },
PyPy,
true,
false,
false,
false,
),
"python39",
);
assert_eq!(
super::default_lib_name_windows(
PythonVersion { major: 3, minor: 9 },
CPython,
false,
false,
true,
false,
),
"python39_d",
);
// abi3 debug builds on windows use version-specific lib
// to workaround https://github.com/python/cpython/issues/101614
assert_eq!(
super::default_lib_name_windows(
PythonVersion { major: 3, minor: 9 },
CPython,
true,
false,
true,
false,
),
"python39_d",
);
}
#[test]
fn default_lib_name_unix() {
use PythonImplementation::*;
// Defaults to python3.7m for CPython 3.7
assert_eq!(
super::default_lib_name_unix(
PythonVersion { major: 3, minor: 7 },
CPython,
None,
false
),
"python3.7m",
);
// Defaults to pythonX.Y for CPython 3.8+
assert_eq!(
super::default_lib_name_unix(
PythonVersion { major: 3, minor: 8 },
CPython,
None,
false
),
"python3.8",
);
assert_eq!(
super::default_lib_name_unix(
PythonVersion { major: 3, minor: 9 },
CPython,
None,
false
),
"python3.9",
);
// Can use ldversion to override for CPython
assert_eq!(
super::default_lib_name_unix(
PythonVersion { major: 3, minor: 9 },
CPython,
Some("3.7md"),
false
),
"python3.7md",
);
// PyPy 3.9 includes ldversion
assert_eq!(
super::default_lib_name_unix(PythonVersion { major: 3, minor: 9 }, PyPy, None, false),
"pypy3.9-c",
);
assert_eq!(
super::default_lib_name_unix(
PythonVersion { major: 3, minor: 9 },
PyPy,
Some("3.9d"),
false
),
"pypy3.9d-c",
);
}
#[test]
fn parse_cross_python_version() {
let env_vars = CrossCompileEnvVars {
pyo3_cross: None,
pyo3_cross_lib_dir: None,
pyo3_cross_python_version: Some("3.9".into()),
pyo3_cross_python_implementation: None,
};
assert_eq!(
env_vars.parse_version().unwrap(),
Some(PythonVersion { major: 3, minor: 9 })
);
let env_vars = CrossCompileEnvVars {
pyo3_cross: None,
pyo3_cross_lib_dir: None,
pyo3_cross_python_version: None,
pyo3_cross_python_implementation: None,
};
assert_eq!(env_vars.parse_version().unwrap(), None);
let env_vars = CrossCompileEnvVars {
pyo3_cross: None,
pyo3_cross_lib_dir: None,
pyo3_cross_python_version: Some("100".into()),
pyo3_cross_python_implementation: None,
};
assert!(env_vars.parse_version().is_err());
}
#[test]
fn interpreter_version_reduced_to_abi3() {
let mut config = InterpreterConfig {
abi3: true,
build_flags: BuildFlags::default(),
pointer_width: None,
executable: None,
implementation: PythonImplementation::CPython,
lib_dir: None,
lib_name: None,
shared: true,
version: PythonVersion { major: 3, minor: 7 },
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
};
config
.fixup_for_abi3_version(Some(PythonVersion { major: 3, minor: 7 }))
.unwrap();
assert_eq!(config.version, PythonVersion { major: 3, minor: 7 });
}
#[test]
fn abi3_version_cannot_be_higher_than_interpreter() {
let mut config = InterpreterConfig {
abi3: true,
build_flags: BuildFlags::new(),
pointer_width: None,
executable: None,
implementation: PythonImplementation::CPython,
lib_dir: None,
lib_name: None,
shared: true,
version: PythonVersion { major: 3, minor: 7 },
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
};
assert!(config
.fixup_for_abi3_version(Some(PythonVersion { major: 3, minor: 8 }))
.unwrap_err()
.to_string()
.contains(
"cannot set a minimum Python version 3.8 higher than the interpreter version 3.7"
));
}
#[test]
#[cfg(all(
target_os = "linux",
target_arch = "x86_64",
feature = "resolve-config"
))]
fn parse_sysconfigdata() {
// A best effort attempt to get test coverage for the sysconfigdata parsing.
// Might not complete successfully depending on host installation; that's ok as long as
// CI demonstrates this path is covered!
let interpreter_config = crate::get();
let lib_dir = match &interpreter_config.lib_dir {
Some(lib_dir) => Path::new(lib_dir),
// Don't know where to search for sysconfigdata; never mind.
None => return,
};
let cross = CrossCompileConfig {
lib_dir: Some(lib_dir.into()),
version: Some(interpreter_config.version),
implementation: Some(interpreter_config.implementation),
target: triple!("x86_64-unknown-linux-gnu"),
};
let sysconfigdata_path = match find_sysconfigdata(&cross) {
Ok(Some(path)) => path,
// Couldn't find a matching sysconfigdata; never mind!
_ => return,
};
let sysconfigdata = super::parse_sysconfigdata(sysconfigdata_path).unwrap();
let parsed_config = InterpreterConfig::from_sysconfigdata(&sysconfigdata).unwrap();
assert_eq!(
parsed_config,
InterpreterConfig {
abi3: false,
build_flags: BuildFlags(interpreter_config.build_flags.0.clone()),
pointer_width: Some(64),
executable: None,
implementation: PythonImplementation::CPython,
lib_dir: interpreter_config.lib_dir.to_owned(),
lib_name: interpreter_config.lib_name.to_owned(),
shared: true,
version: interpreter_config.version,
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
}
)
}
#[test]
fn test_venv_interpreter() {
let base = OsStr::new("base");
assert_eq!(
venv_interpreter(base, true),
PathBuf::from_iter(&["base", "Scripts", "python.exe"])
);
assert_eq!(
venv_interpreter(base, false),
PathBuf::from_iter(&["base", "bin", "python"])
);
}
#[test]
fn test_conda_env_interpreter() {
let base = OsStr::new("base");
assert_eq!(
conda_env_interpreter(base, true),
PathBuf::from_iter(&["base", "python.exe"])
);
assert_eq!(
conda_env_interpreter(base, false),
PathBuf::from_iter(&["base", "bin", "python"])
);
}
#[test]
fn test_not_cross_compiling_from_to() {
assert!(cross_compiling_from_to(
&triple!("x86_64-unknown-linux-gnu"),
&triple!("x86_64-unknown-linux-gnu"),
)
.unwrap()
.is_none());
assert!(cross_compiling_from_to(
&triple!("x86_64-apple-darwin"),
&triple!("x86_64-apple-darwin")
)
.unwrap()
.is_none());
assert!(cross_compiling_from_to(
&triple!("aarch64-apple-darwin"),
&triple!("x86_64-apple-darwin")
)
.unwrap()
.is_none());
assert!(cross_compiling_from_to(
&triple!("x86_64-apple-darwin"),
&triple!("aarch64-apple-darwin")
)
.unwrap()
.is_none());
assert!(cross_compiling_from_to(
&triple!("x86_64-pc-windows-msvc"),
&triple!("i686-pc-windows-msvc")
)
.unwrap()
.is_none());
assert!(cross_compiling_from_to(
&triple!("x86_64-unknown-linux-gnu"),
&triple!("x86_64-unknown-linux-musl")
)
.unwrap()
.is_none());
}
#[test]
fn test_run_python_script() {
// as above, this should be okay in CI where Python is presumed installed
let interpreter = make_interpreter_config()
.expect("could not get InterpreterConfig from installed interpreter");
let out = interpreter
.run_python_script("print(2 + 2)")
.expect("failed to run Python script");
assert_eq!(out.trim_end(), "4");
}
#[test]
fn test_run_python_script_with_envs() {
// as above, this should be okay in CI where Python is presumed installed
let interpreter = make_interpreter_config()
.expect("could not get InterpreterConfig from installed interpreter");
let out = interpreter
.run_python_script_with_envs(
"import os; print(os.getenv('PYO3_TEST'))",
vec![("PYO3_TEST", "42")],
)
.expect("failed to run Python script");
assert_eq!(out.trim_end(), "42");
}
#[test]
fn test_build_script_outputs_base() {
let interpreter_config = InterpreterConfig {
implementation: PythonImplementation::CPython,
version: PythonVersion { major: 3, minor: 9 },
shared: true,
abi3: false,
lib_name: Some("python3".into()),
lib_dir: None,
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
};
assert_eq!(
interpreter_config.build_script_outputs(),
[
"cargo:rustc-cfg=Py_3_7".to_owned(),
"cargo:rustc-cfg=Py_3_8".to_owned(),
"cargo:rustc-cfg=Py_3_9".to_owned(),
]
);
let interpreter_config = InterpreterConfig {
implementation: PythonImplementation::PyPy,
..interpreter_config
};
assert_eq!(
interpreter_config.build_script_outputs(),
[
"cargo:rustc-cfg=Py_3_7".to_owned(),
"cargo:rustc-cfg=Py_3_8".to_owned(),
"cargo:rustc-cfg=Py_3_9".to_owned(),
"cargo:rustc-cfg=PyPy".to_owned(),
]
);
}
#[test]
fn test_build_script_outputs_abi3() {
let interpreter_config = InterpreterConfig {
implementation: PythonImplementation::CPython,
version: PythonVersion { major: 3, minor: 9 },
shared: true,
abi3: true,
lib_name: Some("python3".into()),
lib_dir: None,
executable: None,
pointer_width: None,
build_flags: BuildFlags::default(),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
};
assert_eq!(
interpreter_config.build_script_outputs(),
[
"cargo:rustc-cfg=Py_3_7".to_owned(),
"cargo:rustc-cfg=Py_3_8".to_owned(),
"cargo:rustc-cfg=Py_3_9".to_owned(),
"cargo:rustc-cfg=Py_LIMITED_API".to_owned(),
]
);
let interpreter_config = InterpreterConfig {
implementation: PythonImplementation::PyPy,
..interpreter_config
};
assert_eq!(
interpreter_config.build_script_outputs(),
[
"cargo:rustc-cfg=Py_3_7".to_owned(),
"cargo:rustc-cfg=Py_3_8".to_owned(),
"cargo:rustc-cfg=Py_3_9".to_owned(),
"cargo:rustc-cfg=PyPy".to_owned(),
"cargo:rustc-cfg=Py_LIMITED_API".to_owned(),
]
);
}
#[test]
fn test_build_script_outputs_gil_disabled() {
let mut build_flags = BuildFlags::default();
build_flags.0.insert(BuildFlag::Py_GIL_DISABLED);
let interpreter_config = InterpreterConfig {
implementation: PythonImplementation::CPython,
version: PythonVersion {
major: 3,
minor: 13,
},
shared: true,
abi3: false,
lib_name: Some("python3".into()),
lib_dir: None,
executable: None,
pointer_width: None,
build_flags,
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
};
assert_eq!(
interpreter_config.build_script_outputs(),
[
"cargo:rustc-cfg=Py_3_7".to_owned(),
"cargo:rustc-cfg=Py_3_8".to_owned(),
"cargo:rustc-cfg=Py_3_9".to_owned(),
"cargo:rustc-cfg=Py_3_10".to_owned(),
"cargo:rustc-cfg=Py_3_11".to_owned(),
"cargo:rustc-cfg=Py_3_12".to_owned(),
"cargo:rustc-cfg=Py_3_13".to_owned(),
"cargo:rustc-cfg=Py_GIL_DISABLED".to_owned(),
]
);
}
#[test]
fn test_build_script_outputs_debug() {
let mut build_flags = BuildFlags::default();
build_flags.0.insert(BuildFlag::Py_DEBUG);
let interpreter_config = InterpreterConfig {
implementation: PythonImplementation::CPython,
version: PythonVersion { major: 3, minor: 7 },
shared: true,
abi3: false,
lib_name: Some("python3".into()),
lib_dir: None,
executable: None,
pointer_width: None,
build_flags,
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
};
assert_eq!(
interpreter_config.build_script_outputs(),
[
"cargo:rustc-cfg=Py_3_7".to_owned(),
"cargo:rustc-cfg=py_sys_config=\"Py_DEBUG\"".to_owned(),
]
);
}
#[test]
fn test_find_sysconfigdata_in_invalid_lib_dir() {
let e = find_all_sysconfigdata(&CrossCompileConfig {
lib_dir: Some(PathBuf::from("/abc/123/not/a/real/path")),
version: None,
implementation: None,
target: triple!("x86_64-unknown-linux-gnu"),
})
.unwrap_err();
// actual error message is platform-dependent, so just check the context we add
assert!(e.report().to_string().starts_with(
"failed to search the lib dir at 'PYO3_CROSS_LIB_DIR=/abc/123/not/a/real/path'\n\
caused by:\n \
- 0: failed to list the entries in '/abc/123/not/a/real/path'\n \
- 1: \
"
));
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config/src/import_lib.rs | //! Optional `python3.dll` import library generator for Windows
use std::env;
use std::path::PathBuf;
use python3_dll_a::ImportLibraryGenerator;
use target_lexicon::{Architecture, OperatingSystem, Triple};
use super::{PythonImplementation, PythonVersion};
use crate::errors::{Context, Error, Result};
/// Generates the `python3.dll` or `pythonXY.dll` import library for Windows targets.
///
/// Places the generated import library into the build script output directory
/// and returns the full library directory path.
///
/// Does nothing if the target OS is not Windows.
pub(super) fn generate_import_lib(
target: &Triple,
py_impl: PythonImplementation,
py_version: Option<PythonVersion>,
) -> Result<Option<String>> {
if target.operating_system != OperatingSystem::Windows {
return Ok(None);
}
let out_dir =
env::var_os("OUT_DIR").expect("generate_import_lib() must be called from a build script");
// Put the newly created import library into the build script output directory.
let mut out_lib_dir = PathBuf::from(out_dir);
out_lib_dir.push("lib");
// Convert `Architecture` enum to rustc `target_arch` option format.
let arch = match target.architecture {
// i686, i586, etc.
Architecture::X86_32(_) => "x86".to_string(),
other => other.to_string(),
};
let env = target.environment.to_string();
let implementation = match py_impl {
PythonImplementation::CPython => python3_dll_a::PythonImplementation::CPython,
PythonImplementation::PyPy => python3_dll_a::PythonImplementation::PyPy,
PythonImplementation::GraalPy => {
return Err(Error::from("No support for GraalPy on Windows"))
}
};
ImportLibraryGenerator::new(&arch, &env)
.version(py_version.map(|v| (v.major, v.minor)))
.implementation(implementation)
.generate(&out_lib_dir)
.context("failed to generate python3.dll import library")?;
let out_lib_dir_string = out_lib_dir
.to_str()
.ok_or("build directory is not a valid UTF-8 string")?
.to_owned();
Ok(Some(out_lib_dir_string))
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config/src/lib.rs | //! Configuration used by PyO3 for conditional support of varying Python versions.
//!
//! This crate exposes functionality to be called from build scripts to simplify building crates
//! which depend on PyO3.
//!
//! It used internally by the PyO3 crate's build script to apply the same configuration.
#![warn(elided_lifetimes_in_paths, unused_lifetimes)]
mod errors;
mod impl_;
#[cfg(feature = "resolve-config")]
use std::{
io::Cursor,
path::{Path, PathBuf},
};
use std::{env, process::Command, str::FromStr};
use once_cell::sync::OnceCell;
pub use impl_::{
cross_compiling_from_to, find_all_sysconfigdata, parse_sysconfigdata, BuildFlag, BuildFlags,
CrossCompileConfig, InterpreterConfig, PythonImplementation, PythonVersion, Triple,
};
use target_lexicon::OperatingSystem;
/// Adds all the [`#[cfg]` flags](index.html) to the current compilation.
///
/// This should be called from a build script.
///
/// The full list of attributes added are the following:
///
/// | Flag | Description |
/// | ---- | ----------- |
/// | `#[cfg(Py_3_7)]`, `#[cfg(Py_3_8)]`, `#[cfg(Py_3_9)]`, `#[cfg(Py_3_10)]` | These attributes mark code only for a given Python version and up. For example, `#[cfg(Py_3_7)]` marks code which can run on Python 3.7 **and newer**. |
/// | `#[cfg(Py_LIMITED_API)]` | This marks code which is run when compiling with PyO3's `abi3` feature enabled. |
/// | `#[cfg(PyPy)]` | This marks code which is run when compiling for PyPy. |
/// | `#[cfg(GraalPy)]` | This marks code which is run when compiling for GraalPy. |
///
/// For examples of how to use these attributes,
#[doc = concat!("[see PyO3's guide](https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/building-and-distribution/multiple_python_versions.html)")]
/// .
#[cfg(feature = "resolve-config")]
pub fn use_pyo3_cfgs() {
print_expected_cfgs();
for cargo_command in get().build_script_outputs() {
println!("{}", cargo_command)
}
}
/// Adds linker arguments suitable for PyO3's `extension-module` feature.
///
/// This should be called from a build script.
///
/// The following link flags are added:
/// - macOS: `-undefined dynamic_lookup`
/// - wasm32-unknown-emscripten: `-sSIDE_MODULE=2 -sWASM_BIGINT`
///
/// All other platforms currently are no-ops, however this may change as necessary
/// in future.
pub fn add_extension_module_link_args() {
_add_extension_module_link_args(&impl_::target_triple_from_env(), std::io::stdout())
}
fn _add_extension_module_link_args(triple: &Triple, mut writer: impl std::io::Write) {
if triple.operating_system == OperatingSystem::Darwin {
writeln!(writer, "cargo:rustc-cdylib-link-arg=-undefined").unwrap();
writeln!(writer, "cargo:rustc-cdylib-link-arg=dynamic_lookup").unwrap();
} else if triple == &Triple::from_str("wasm32-unknown-emscripten").unwrap() {
writeln!(writer, "cargo:rustc-cdylib-link-arg=-sSIDE_MODULE=2").unwrap();
writeln!(writer, "cargo:rustc-cdylib-link-arg=-sWASM_BIGINT").unwrap();
}
}
/// Loads the configuration determined from the build environment.
///
/// Because this will never change in a given compilation run, this is cached in a `once_cell`.
#[cfg(feature = "resolve-config")]
pub fn get() -> &'static InterpreterConfig {
static CONFIG: OnceCell<InterpreterConfig> = OnceCell::new();
CONFIG.get_or_init(|| {
// Check if we are in a build script and cross compiling to a different target.
let cross_compile_config_path = resolve_cross_compile_config_path();
let cross_compiling = cross_compile_config_path
.as_ref()
.map(|path| path.exists())
.unwrap_or(false);
// CONFIG_FILE is generated in build.rs, so it's content can vary
#[allow(unknown_lints, clippy::const_is_empty)]
if let Some(interpreter_config) = InterpreterConfig::from_cargo_dep_env() {
interpreter_config
} else if !CONFIG_FILE.is_empty() {
InterpreterConfig::from_reader(Cursor::new(CONFIG_FILE))
} else if cross_compiling {
InterpreterConfig::from_path(cross_compile_config_path.as_ref().unwrap())
} else {
InterpreterConfig::from_reader(Cursor::new(HOST_CONFIG))
}
.expect("failed to parse PyO3 config")
})
}
/// Build configuration provided by `PYO3_CONFIG_FILE`. May be empty if env var not set.
#[doc(hidden)]
#[cfg(feature = "resolve-config")]
const CONFIG_FILE: &str = include_str!(concat!(env!("OUT_DIR"), "/pyo3-build-config-file.txt"));
/// Build configuration discovered by `pyo3-build-config` build script. Not aware of
/// cross-compilation settings.
#[doc(hidden)]
#[cfg(feature = "resolve-config")]
const HOST_CONFIG: &str = include_str!(concat!(env!("OUT_DIR"), "/pyo3-build-config.txt"));
/// Returns the path where PyO3's build.rs writes its cross compile configuration.
///
/// The config file will be named `$OUT_DIR/<triple>/pyo3-build-config.txt`.
///
/// Must be called from a build script, returns `None` if not.
#[doc(hidden)]
#[cfg(feature = "resolve-config")]
fn resolve_cross_compile_config_path() -> Option<PathBuf> {
env::var_os("TARGET").map(|target| {
let mut path = PathBuf::from(env!("OUT_DIR"));
path.push(Path::new(&target));
path.push("pyo3-build-config.txt");
path
})
}
/// Use certain features if we detect the compiler being used supports them.
///
/// Features may be removed or added as MSRV gets bumped or new features become available,
/// so this function is unstable.
#[doc(hidden)]
pub fn print_feature_cfgs() {
let rustc_minor_version = rustc_minor_version().unwrap_or(0);
if rustc_minor_version >= 70 {
println!("cargo:rustc-cfg=rustc_has_once_lock");
}
// invalid_from_utf8 lint was added in Rust 1.74
if rustc_minor_version >= 74 {
println!("cargo:rustc-cfg=invalid_from_utf8_lint");
}
if rustc_minor_version >= 79 {
println!("cargo:rustc-cfg=c_str_lit");
}
// Actually this is available on 1.78, but we should avoid
// https://github.com/rust-lang/rust/issues/124651 just in case
if rustc_minor_version >= 79 {
println!("cargo:rustc-cfg=diagnostic_namespace");
}
}
/// Registers `pyo3`s config names as reachable cfg expressions
///
/// - <https://github.com/rust-lang/cargo/pull/13571>
/// - <https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#rustc-check-cfg>
#[doc(hidden)]
pub fn print_expected_cfgs() {
if rustc_minor_version().map_or(false, |version| version < 80) {
// rustc 1.80.0 stabilized `rustc-check-cfg` feature, don't emit before
return;
}
println!("cargo:rustc-check-cfg=cfg(Py_LIMITED_API)");
println!("cargo:rustc-check-cfg=cfg(Py_GIL_DISABLED)");
println!("cargo:rustc-check-cfg=cfg(PyPy)");
println!("cargo:rustc-check-cfg=cfg(GraalPy)");
println!("cargo:rustc-check-cfg=cfg(py_sys_config, values(\"Py_DEBUG\", \"Py_REF_DEBUG\", \"Py_TRACE_REFS\", \"COUNT_ALLOCS\"))");
println!("cargo:rustc-check-cfg=cfg(invalid_from_utf8_lint)");
println!("cargo:rustc-check-cfg=cfg(pyo3_disable_reference_pool)");
println!("cargo:rustc-check-cfg=cfg(pyo3_leak_on_drop_without_reference_pool)");
println!("cargo:rustc-check-cfg=cfg(diagnostic_namespace)");
println!("cargo:rustc-check-cfg=cfg(c_str_lit)");
println!("cargo:rustc-check-cfg=cfg(rustc_has_once_lock)");
// allow `Py_3_*` cfgs from the minimum supported version up to the
// maximum minor version (+1 for development for the next)
for i in impl_::MINIMUM_SUPPORTED_VERSION.minor..=impl_::ABI3_MAX_MINOR + 1 {
println!("cargo:rustc-check-cfg=cfg(Py_3_{i})");
}
}
/// Private exports used in PyO3's build.rs
///
/// Please don't use these - they could change at any time.
#[doc(hidden)]
pub mod pyo3_build_script_impl {
#[cfg(feature = "resolve-config")]
use crate::errors::{Context, Result};
#[cfg(feature = "resolve-config")]
use super::*;
pub mod errors {
pub use crate::errors::*;
}
pub use crate::impl_::{
cargo_env_var, env_var, is_linking_libpython, make_cross_compile_config, InterpreterConfig,
PythonVersion,
};
/// Gets the configuration for use from PyO3's build script.
///
/// Differs from .get() above only in the cross-compile case, where PyO3's build script is
/// required to generate a new config (as it's the first build script which has access to the
/// correct value for CARGO_CFG_TARGET_OS).
#[cfg(feature = "resolve-config")]
pub fn resolve_interpreter_config() -> Result<InterpreterConfig> {
// CONFIG_FILE is generated in build.rs, so it's content can vary
#[allow(unknown_lints, clippy::const_is_empty)]
if !CONFIG_FILE.is_empty() {
let mut interperter_config = InterpreterConfig::from_reader(Cursor::new(CONFIG_FILE))?;
interperter_config.generate_import_libs()?;
Ok(interperter_config)
} else if let Some(interpreter_config) = make_cross_compile_config()? {
// This is a cross compile and need to write the config file.
let path = resolve_cross_compile_config_path()
.expect("resolve_interpreter_config() must be called from a build script");
let parent_dir = path.parent().ok_or_else(|| {
format!(
"failed to resolve parent directory of config file {}",
path.display()
)
})?;
std::fs::create_dir_all(parent_dir).with_context(|| {
format!(
"failed to create config file directory {}",
parent_dir.display()
)
})?;
interpreter_config.to_writer(&mut std::fs::File::create(&path).with_context(
|| format!("failed to create config file at {}", path.display()),
)?)?;
Ok(interpreter_config)
} else {
InterpreterConfig::from_reader(Cursor::new(HOST_CONFIG))
}
}
}
fn rustc_minor_version() -> Option<u32> {
static RUSTC_MINOR_VERSION: OnceCell<Option<u32>> = OnceCell::new();
*RUSTC_MINOR_VERSION.get_or_init(|| {
let rustc = env::var_os("RUSTC")?;
let output = Command::new(rustc).arg("--version").output().ok()?;
let version = core::str::from_utf8(&output.stdout).ok()?;
let mut pieces = version.split('.');
if pieces.next() != Some("rustc 1") {
return None;
}
pieces.next()?.parse().ok()
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extension_module_link_args() {
let mut buf = Vec::new();
// Does nothing on non-mac
_add_extension_module_link_args(
&Triple::from_str("x86_64-pc-windows-msvc").unwrap(),
&mut buf,
);
assert_eq!(buf, Vec::new());
_add_extension_module_link_args(
&Triple::from_str("x86_64-apple-darwin").unwrap(),
&mut buf,
);
assert_eq!(
std::str::from_utf8(&buf).unwrap(),
"cargo:rustc-cdylib-link-arg=-undefined\n\
cargo:rustc-cdylib-link-arg=dynamic_lookup\n"
);
buf.clear();
_add_extension_module_link_args(
&Triple::from_str("wasm32-unknown-emscripten").unwrap(),
&mut buf,
);
assert_eq!(
std::str::from_utf8(&buf).unwrap(),
"cargo:rustc-cdylib-link-arg=-sSIDE_MODULE=2\n\
cargo:rustc-cdylib-link-arg=-sWASM_BIGINT\n"
);
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config | lc_public_repos/langsmith-sdk/vendor/pyo3/pyo3-build-config/src/errors.rs | /// A simple macro for returning an error. Resembles anyhow::bail.
#[macro_export]
#[doc(hidden)]
macro_rules! bail {
($($args: tt)+) => { return Err(format!($($args)+).into()) };
}
/// A simple macro for checking a condition. Resembles anyhow::ensure.
#[macro_export]
#[doc(hidden)]
macro_rules! ensure {
($condition:expr, $($args: tt)+) => { if !($condition) { bail!($($args)+) } };
}
/// Show warning.
#[macro_export]
#[doc(hidden)]
macro_rules! warn {
($($args: tt)+) => {
println!("{}", $crate::format_warn!($($args)+))
};
}
/// Format warning into string.
#[macro_export]
#[doc(hidden)]
macro_rules! format_warn {
($($args: tt)+) => {
format!("cargo:warning={}", format_args!($($args)+))
};
}
/// A simple error implementation which allows chaining of errors, inspired somewhat by anyhow.
#[derive(Debug)]
pub struct Error {
value: String,
source: Option<Box<dyn std::error::Error>>,
}
/// Error report inspired by
/// <https://blog.rust-lang.org/inside-rust/2021/07/01/What-the-error-handling-project-group-is-working-towards.html#2-error-reporter>
pub struct ErrorReport<'a>(&'a Error);
impl Error {
pub fn report(&self) -> ErrorReport<'_> {
ErrorReport(self)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.value)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_deref()
}
}
impl std::fmt::Display for ErrorReport<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use std::error::Error;
self.0.fmt(f)?;
let mut source = self.0.source();
if source.is_some() {
writeln!(f, "\ncaused by:")?;
let mut index = 0;
while let Some(some_source) = source {
writeln!(f, " - {}: {}", index, some_source)?;
source = some_source.source();
index += 1;
}
}
Ok(())
}
}
impl From<String> for Error {
fn from(value: String) -> Self {
Self {
value,
source: None,
}
}
}
impl From<&'_ str> for Error {
fn from(value: &str) -> Self {
value.to_string().into()
}
}
impl From<std::convert::Infallible> for Error {
fn from(value: std::convert::Infallible) -> Self {
match value {}
}
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub trait Context<T> {
fn context(self, message: impl Into<String>) -> Result<T>;
fn with_context(self, message: impl FnOnce() -> String) -> Result<T>;
}
impl<T, E> Context<T> for Result<T, E>
where
E: std::error::Error + 'static,
{
fn context(self, message: impl Into<String>) -> Result<T> {
self.map_err(|error| Error {
value: message.into(),
source: Some(Box::new(error)),
})
}
fn with_context(self, message: impl FnOnce() -> String) -> Result<T> {
self.map_err(|error| Error {
value: message(),
source: Some(Box::new(error)),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_report() {
let error: Result<()> = Err(Error::from("there was an internal error"))
.with_context(|| format!("failed to do {}", "something difficult"))
.context("things went wrong");
assert_eq!(
error
.unwrap_err()
.report()
.to_string()
.split('\n')
.collect::<Vec<&str>>(),
vec![
"things went wrong",
"caused by:",
" - 0: failed to do something difficult",
" - 1: there was an internal error",
""
]
);
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_sequence.rs | #![cfg(feature = "macros")]
use pyo3::exceptions::{PyIndexError, PyValueError};
use pyo3::types::{IntoPyDict, PyList, PyMapping, PySequence};
use pyo3::{ffi, prelude::*};
use pyo3::py_run;
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
struct ByteSequence {
elements: Vec<u8>,
}
#[pymethods]
impl ByteSequence {
#[new]
#[pyo3(signature=(elements = None))]
fn new(elements: Option<&Bound<'_, PyList>>) -> PyResult<Self> {
if let Some(pylist) = elements {
let mut elems = Vec::with_capacity(pylist.len());
for pyelem in pylist {
let elem = pyelem.extract()?;
elems.push(elem);
}
Ok(Self { elements: elems })
} else {
Ok(Self {
elements: Vec::new(),
})
}
}
fn __len__(&self) -> usize {
self.elements.len()
}
fn __getitem__(&self, idx: isize) -> PyResult<u8> {
self.elements
.get(idx as usize)
.copied()
.ok_or_else(|| PyIndexError::new_err("list index out of range"))
}
fn __setitem__(&mut self, idx: isize, value: u8) {
self.elements[idx as usize] = value;
}
fn __delitem__(&mut self, mut idx: isize) -> PyResult<()> {
let self_len = self.elements.len() as isize;
if idx < 0 {
idx += self_len;
}
if (idx < self_len) && (idx >= 0) {
self.elements.remove(idx as usize);
Ok(())
} else {
Err(PyIndexError::new_err("list index out of range"))
}
}
fn __contains__(&self, other: &Bound<'_, PyAny>) -> bool {
match other.extract::<u8>() {
Ok(x) => self.elements.contains(&x),
Err(_) => false,
}
}
fn __concat__(&self, other: &Self) -> Self {
let mut elements = self.elements.clone();
elements.extend_from_slice(&other.elements);
Self { elements }
}
fn __inplace_concat__(mut slf: PyRefMut<'_, Self>, other: &Self) -> Py<Self> {
slf.elements.extend_from_slice(&other.elements);
slf.into()
}
fn __repeat__(&self, count: isize) -> PyResult<Self> {
if count >= 0 {
let mut elements = Vec::with_capacity(self.elements.len() * count as usize);
for _ in 0..count {
elements.extend(&self.elements);
}
Ok(Self { elements })
} else {
Err(PyValueError::new_err("invalid repeat count"))
}
}
fn __inplace_repeat__(mut slf: PyRefMut<'_, Self>, count: isize) -> PyResult<Py<Self>> {
if count >= 0 {
let mut elements = Vec::with_capacity(slf.elements.len() * count as usize);
for _ in 0..count {
elements.extend(&slf.elements);
}
slf.elements = elements;
Ok(slf.into())
} else {
Err(PyValueError::new_err("invalid repeat count"))
}
}
}
/// Return a dict with `s = ByteSequence([1, 2, 3])`.
fn seq_dict(py: Python<'_>) -> Bound<'_, pyo3::types::PyDict> {
let d = [("ByteSequence", py.get_type::<ByteSequence>())]
.into_py_dict(py)
.unwrap();
// Though we can construct `s` in Rust, let's test `__new__` works.
py_run!(py, *d, "s = ByteSequence([1, 2, 3])");
d
}
#[test]
fn test_getitem() {
Python::with_gil(|py| {
let d = seq_dict(py);
py_assert!(py, *d, "s[0] == 1");
py_assert!(py, *d, "s[1] == 2");
py_assert!(py, *d, "s[2] == 3");
py_expect_exception!(py, *d, "print(s[-4])", PyIndexError);
py_expect_exception!(py, *d, "print(s[4])", PyIndexError);
});
}
#[test]
fn test_setitem() {
Python::with_gil(|py| {
let d = seq_dict(py);
py_run!(py, *d, "s[0] = 4; assert list(s) == [4, 2, 3]");
py_expect_exception!(py, *d, "s[0] = 'hello'", PyTypeError);
});
}
#[test]
fn test_delitem() {
Python::with_gil(|py| {
let d = [("ByteSequence", py.get_type::<ByteSequence>())]
.into_py_dict(py)
.unwrap();
py_run!(
py,
*d,
"s = ByteSequence([1, 2, 3]); del s[0]; assert list(s) == [2, 3]"
);
py_run!(
py,
*d,
"s = ByteSequence([1, 2, 3]); del s[1]; assert list(s) == [1, 3]"
);
py_run!(
py,
*d,
"s = ByteSequence([1, 2, 3]); del s[-1]; assert list(s) == [1, 2]"
);
py_run!(
py,
*d,
"s = ByteSequence([1, 2, 3]); del s[-2]; assert list(s) == [1, 3]"
);
py_expect_exception!(
py,
*d,
"s = ByteSequence([1, 2, 3]); del s[-4]; print(list(s))",
PyIndexError
);
py_expect_exception!(
py,
*d,
"s = ByteSequence([1, 2, 3]); del s[4]",
PyIndexError
);
});
}
#[test]
fn test_contains() {
Python::with_gil(|py| {
let d = seq_dict(py);
py_assert!(py, *d, "1 in s");
py_assert!(py, *d, "2 in s");
py_assert!(py, *d, "3 in s");
py_assert!(py, *d, "4 not in s");
py_assert!(py, *d, "'hello' not in s");
});
}
#[test]
fn test_concat() {
Python::with_gil(|py| {
let d = seq_dict(py);
py_run!(
py,
*d,
"s1 = ByteSequence([1, 2]); s2 = ByteSequence([3, 4]); assert list(s1 + s2) == [1, 2, 3, 4]"
);
py_expect_exception!(
py,
*d,
"s1 = ByteSequence([1, 2]); s2 = 'hello'; s1 + s2",
PyTypeError
);
});
}
#[test]
fn test_inplace_concat() {
Python::with_gil(|py| {
let d = seq_dict(py);
py_run!(
py,
*d,
"s += ByteSequence([4, 5]); assert list(s) == [1, 2, 3, 4, 5]"
);
py_expect_exception!(py, *d, "s += 'hello'", PyTypeError);
});
}
#[test]
fn test_repeat() {
Python::with_gil(|py| {
let d = seq_dict(py);
py_run!(py, *d, "s2 = s * 2; assert list(s2) == [1, 2, 3, 1, 2, 3]");
py_expect_exception!(py, *d, "s2 = s * -1", PyValueError);
});
}
#[test]
fn test_inplace_repeat() {
Python::with_gil(|py| {
let d = [("ByteSequence", py.get_type::<ByteSequence>())]
.into_py_dict(py)
.unwrap();
py_run!(
py,
*d,
"s = ByteSequence([1, 2]); s *= 3; assert list(s) == [1, 2, 1, 2, 1, 2]"
);
py_expect_exception!(py, *d, "s = ByteSequence([1, 2]); s *= -1", PyValueError);
});
}
// Check that #[pyo3(get, set)] works correctly for Vec<PyObject>
#[pyclass]
struct GenericList {
#[pyo3(get, set)]
items: Vec<PyObject>,
}
#[test]
fn test_generic_list_get() {
Python::with_gil(|py| {
let list = GenericList {
items: [1i32, 2, 3]
.iter()
.map(|i| i.into_pyobject(py).unwrap().into_any().unbind())
.collect(),
}
.into_pyobject(py)
.unwrap();
py_assert!(py, list, "list.items == [1, 2, 3]");
});
}
#[test]
fn test_generic_list_set() {
Python::with_gil(|py| {
let list = Bound::new(py, GenericList { items: vec![] }).unwrap();
py_run!(py, list, "list.items = [1, 2, 3]");
assert!(list
.borrow()
.items
.iter()
.zip(&[1u32, 2, 3])
.all(|(a, b)| a.bind(py).eq(b.into_pyobject(py).unwrap()).unwrap()));
});
}
#[pyclass(sequence)]
struct OptionList {
#[pyo3(get, set)]
items: Vec<Option<i64>>,
}
#[pymethods]
impl OptionList {
fn __len__(&self) -> usize {
self.items.len()
}
fn __getitem__(&self, idx: isize) -> PyResult<Option<i64>> {
match self.items.get(idx as usize) {
Some(x) => Ok(*x),
None => Err(PyIndexError::new_err("Index out of bounds")),
}
}
}
#[test]
fn test_option_list_get() {
// Regression test for #798
Python::with_gil(|py| {
let list = Py::new(
py,
OptionList {
items: vec![Some(1), None],
},
)
.unwrap();
py_assert!(py, list, "list[0] == 1");
py_assert!(py, list, "list[1] == None");
py_expect_exception!(py, list, "list[2]", PyIndexError);
});
}
#[test]
fn sequence_is_not_mapping() {
Python::with_gil(|py| {
let list = Bound::new(
py,
OptionList {
items: vec![Some(1), None],
},
)
.unwrap()
.into_any();
PySequence::register::<OptionList>(py).unwrap();
assert!(list.downcast::<PyMapping>().is_err());
assert!(list.downcast::<PySequence>().is_ok());
})
}
#[test]
fn sequence_length() {
Python::with_gil(|py| {
let list = Bound::new(
py,
OptionList {
items: vec![Some(1), None],
},
)
.unwrap()
.into_any();
assert_eq!(list.len().unwrap(), 2);
assert_eq!(unsafe { ffi::PySequence_Length(list.as_ptr()) }, 2);
assert_eq!(unsafe { ffi::PyMapping_Length(list.as_ptr()) }, -1);
unsafe { ffi::PyErr_Clear() };
})
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_gc.rs | #![cfg(feature = "macros")]
use pyo3::class::PyTraverseError;
use pyo3::class::PyVisit;
use pyo3::ffi;
use pyo3::prelude::*;
use pyo3::py_run;
#[cfg(not(target_arch = "wasm32"))]
use std::cell::Cell;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Once;
use std::sync::{Arc, Mutex};
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass(freelist = 2)]
struct ClassWithFreelist {}
#[test]
fn class_with_freelist() {
let ptr = Python::with_gil(|py| {
let inst = Py::new(py, ClassWithFreelist {}).unwrap();
let _inst2 = Py::new(py, ClassWithFreelist {}).unwrap();
let ptr = inst.as_ptr();
drop(inst);
ptr
});
Python::with_gil(|py| {
let inst3 = Py::new(py, ClassWithFreelist {}).unwrap();
assert_eq!(ptr, inst3.as_ptr());
let inst4 = Py::new(py, ClassWithFreelist {}).unwrap();
assert_ne!(ptr, inst4.as_ptr())
});
}
/// Helper function to create a pair of objects that can be used to test drops;
/// the first object is a guard that records when it has been dropped, the second
/// object is a check that can be used to assert that the guard has been dropped.
fn drop_check() -> (DropGuard, DropCheck) {
let flag = Arc::new(Once::new());
(DropGuard(flag.clone()), DropCheck(flag))
}
/// Helper structure that records when it has been dropped in the cor
struct DropGuard(Arc<Once>);
impl Drop for DropGuard {
fn drop(&mut self) {
self.0.call_once(|| ());
}
}
struct DropCheck(Arc<Once>);
impl DropCheck {
#[track_caller]
fn assert_not_dropped(&self) {
assert!(!self.0.is_completed());
}
#[track_caller]
fn assert_dropped(&self) {
assert!(self.0.is_completed());
}
#[track_caller]
fn assert_drops_with_gc(&self, object: *mut pyo3::ffi::PyObject) {
// running the GC might take a few cycles to collect an object
for _ in 0..100 {
if self.0.is_completed() {
return;
}
Python::with_gil(|py| {
py.run(ffi::c_str!("import gc; gc.collect()"), None, None)
.unwrap();
});
#[cfg(Py_GIL_DISABLED)]
{
// on the free-threaded build, the GC might be running in a separate thread, allow
// some time for this
std::thread::sleep(std::time::Duration::from_millis(5));
}
}
panic!(
"Object was not dropped after 100 GC cycles, refcount is {}",
// this could be garbage, but it's in a test and we're just printing the value
unsafe { ffi::Py_REFCNT(object) }
);
}
}
#[test]
fn data_is_dropped() {
#[pyclass]
struct DataIsDropped {
_guard1: DropGuard,
_guard2: DropGuard,
}
let (guard1, check1) = drop_check();
let (guard2, check2) = drop_check();
Python::with_gil(|py| {
let data_is_dropped = DataIsDropped {
_guard1: guard1,
_guard2: guard2,
};
let inst = Py::new(py, data_is_dropped).unwrap();
check1.assert_not_dropped();
check2.assert_not_dropped();
drop(inst);
});
check1.assert_dropped();
check2.assert_dropped();
}
#[pyclass(subclass)]
struct CycleWithClear {
cycle: Option<PyObject>,
_guard: DropGuard,
}
#[pymethods]
impl CycleWithClear {
fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
visit.call(&self.cycle)
}
fn __clear__(slf: &Bound<'_, Self>) {
println!("clear run, refcount before {}", slf.get_refcnt());
slf.borrow_mut().cycle = None;
println!("clear run, refcount after {}", slf.get_refcnt());
}
}
#[test]
fn test_cycle_clear() {
let (guard, check) = drop_check();
let ptr = Python::with_gil(|py| {
let inst = Bound::new(
py,
CycleWithClear {
cycle: None,
_guard: guard,
},
)
.unwrap();
inst.borrow_mut().cycle = Some(inst.clone().into_any().unbind());
py_run!(py, inst, "import gc; assert inst in gc.get_objects()");
check.assert_not_dropped();
inst.as_ptr()
});
check.assert_drops_with_gc(ptr);
}
/// Test that traversing `None` of `Option<Py<T>>` does not cause a segfault
#[test]
fn gc_null_traversal() {
#[pyclass]
struct GcNullTraversal {
cycle: Option<Py<Self>>,
null: Option<Py<Self>>,
}
#[pymethods]
impl GcNullTraversal {
fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
visit.call(&self.cycle)?;
visit.call(&self.null)?; // Should not segfault
Ok(())
}
fn __clear__(&mut self) {
self.cycle = None;
self.null = None;
}
}
Python::with_gil(|py| {
let obj = Py::new(
py,
GcNullTraversal {
cycle: None,
null: None,
},
)
.unwrap();
obj.borrow_mut(py).cycle = Some(obj.clone_ref(py));
// the object doesn't have to be cleaned up, it just needs to be traversed.
py.run(ffi::c_str!("import gc; gc.collect()"), None, None)
.unwrap();
});
}
#[test]
fn inheritance_with_new_methods_with_drop() {
#[pyclass(subclass)]
struct BaseClassWithDrop {
guard: Option<DropGuard>,
}
#[pymethods]
impl BaseClassWithDrop {
#[new]
fn new() -> BaseClassWithDrop {
BaseClassWithDrop { guard: None }
}
}
#[pyclass(extends = BaseClassWithDrop)]
struct SubClassWithDrop {
guard: Option<DropGuard>,
}
#[pymethods]
impl SubClassWithDrop {
#[new]
fn new() -> (Self, BaseClassWithDrop) {
(
SubClassWithDrop { guard: None },
BaseClassWithDrop { guard: None },
)
}
}
let (guard_base, check_base) = drop_check();
let (guard_sub, check_sub) = drop_check();
Python::with_gil(|py| {
let typeobj = py.get_type::<SubClassWithDrop>();
let inst = typeobj
.call((), None)
.unwrap()
.downcast_into::<SubClassWithDrop>()
.unwrap();
inst.as_super().borrow_mut().guard = Some(guard_base);
inst.borrow_mut().guard = Some(guard_sub);
check_base.assert_not_dropped();
check_sub.assert_not_dropped();
});
check_base.assert_dropped();
check_sub.assert_dropped();
}
#[test]
fn gc_during_borrow() {
#[pyclass]
struct TraversableClass {
traversed: AtomicBool,
}
impl TraversableClass {
fn new() -> Self {
Self {
traversed: AtomicBool::new(false),
}
}
}
#[pymethods]
impl TraversableClass {
fn __clear__(&mut self) {}
#[allow(clippy::unnecessary_wraps)]
fn __traverse__(&self, _visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
self.traversed.store(true, Ordering::Relaxed);
Ok(())
}
}
Python::with_gil(|py| {
// get the traverse function
let ty = py.get_type::<TraversableClass>();
let traverse = unsafe { get_type_traverse(ty.as_type_ptr()).unwrap() };
// create an object and check that traversing it works normally
// when it's not borrowed
let cell = Bound::new(py, TraversableClass::new()).unwrap();
assert!(!cell.borrow().traversed.load(Ordering::Relaxed));
unsafe { traverse(cell.as_ptr(), novisit, std::ptr::null_mut()) };
assert!(cell.borrow().traversed.load(Ordering::Relaxed));
// create an object and check that it is not traversed if the GC
// is invoked while it is already borrowed mutably
let cell2 = Bound::new(py, TraversableClass::new()).unwrap();
let guard = cell2.borrow_mut();
assert!(!guard.traversed.load(Ordering::Relaxed));
unsafe { traverse(cell2.as_ptr(), novisit, std::ptr::null_mut()) };
assert!(!guard.traversed.load(Ordering::Relaxed));
drop(guard);
});
}
#[test]
fn traverse_partial() {
#[pyclass]
struct PartialTraverse {
member: PyObject,
}
impl PartialTraverse {
fn new(py: Python<'_>) -> Self {
Self { member: py.None() }
}
}
#[pymethods]
impl PartialTraverse {
fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
visit.call(&self.member)?;
// In the test, we expect this to never be hit
unreachable!()
}
}
Python::with_gil(|py| {
// get the traverse function
let ty = py.get_type::<PartialTraverse>();
let traverse = unsafe { get_type_traverse(ty.as_type_ptr()).unwrap() };
// confirm that traversing errors
let obj = Py::new(py, PartialTraverse::new(py)).unwrap();
assert_eq!(
unsafe { traverse(obj.as_ptr(), visit_error, std::ptr::null_mut()) },
-1
);
})
}
#[test]
fn traverse_panic() {
#[pyclass]
struct PanickyTraverse {
member: PyObject,
}
impl PanickyTraverse {
fn new(py: Python<'_>) -> Self {
Self { member: py.None() }
}
}
#[pymethods]
impl PanickyTraverse {
fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
visit.call(&self.member)?;
panic!("at the disco");
}
}
Python::with_gil(|py| {
// get the traverse function
let ty = py.get_type::<PanickyTraverse>();
let traverse = unsafe { get_type_traverse(ty.as_type_ptr()).unwrap() };
// confirm that traversing errors
let obj = Py::new(py, PanickyTraverse::new(py)).unwrap();
assert_eq!(
unsafe { traverse(obj.as_ptr(), novisit, std::ptr::null_mut()) },
-1
);
})
}
#[test]
fn tries_gil_in_traverse() {
#[pyclass]
struct TriesGILInTraverse {}
#[pymethods]
impl TriesGILInTraverse {
fn __traverse__(&self, _visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
Python::with_gil(|_py| Ok(()))
}
}
Python::with_gil(|py| {
// get the traverse function
let ty = py.get_type::<TriesGILInTraverse>();
let traverse = unsafe { get_type_traverse(ty.as_type_ptr()).unwrap() };
// confirm that traversing panicks
let obj = Py::new(py, TriesGILInTraverse {}).unwrap();
assert_eq!(
unsafe { traverse(obj.as_ptr(), novisit, std::ptr::null_mut()) },
-1
);
})
}
#[test]
fn traverse_cannot_be_hijacked() {
#[pyclass]
struct HijackedTraverse {
traversed: AtomicBool,
hijacked: AtomicBool,
}
impl HijackedTraverse {
fn new() -> Self {
Self {
traversed: AtomicBool::new(false),
hijacked: AtomicBool::new(false),
}
}
fn traversed_and_hijacked(&self) -> (bool, bool) {
(
self.traversed.load(Ordering::Acquire),
self.hijacked.load(Ordering::Acquire),
)
}
}
#[pymethods]
impl HijackedTraverse {
#[allow(clippy::unnecessary_wraps)]
fn __traverse__(&self, _visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
self.traversed.store(true, Ordering::Release);
Ok(())
}
}
#[allow(dead_code)]
trait Traversable {
fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError>;
}
impl Traversable for PyRef<'_, HijackedTraverse> {
fn __traverse__(&self, _visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
self.hijacked.store(true, Ordering::Release);
Ok(())
}
}
Python::with_gil(|py| {
// get the traverse function
let ty = py.get_type::<HijackedTraverse>();
let traverse = unsafe { get_type_traverse(ty.as_type_ptr()).unwrap() };
let cell = Bound::new(py, HijackedTraverse::new()).unwrap();
assert_eq!(cell.borrow().traversed_and_hijacked(), (false, false));
unsafe { traverse(cell.as_ptr(), novisit, std::ptr::null_mut()) };
assert_eq!(cell.borrow().traversed_and_hijacked(), (true, false));
})
}
#[pyclass]
struct DropDuringTraversal {
cycle: Mutex<Option<Py<Self>>>,
_guard: DropGuard,
}
#[pymethods]
impl DropDuringTraversal {
#[allow(clippy::unnecessary_wraps)]
fn __traverse__(&self, _visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
let mut cycle_ref = self.cycle.lock().unwrap();
*cycle_ref = None;
Ok(())
}
}
#[cfg(not(pyo3_disable_reference_pool))]
#[test]
fn drop_during_traversal_with_gil() {
let (guard, check) = drop_check();
let ptr = Python::with_gil(|py| {
let cycle = Mutex::new(None);
let inst = Py::new(
py,
DropDuringTraversal {
cycle,
_guard: guard,
},
)
.unwrap();
*inst.borrow_mut(py).cycle.lock().unwrap() = Some(inst.clone_ref(py));
check.assert_not_dropped();
let ptr = inst.as_ptr();
drop(inst); // drop the object while holding the GIL
#[cfg(not(Py_GIL_DISABLED))]
{
// other thread might have caused GC on free-threaded build
check.assert_not_dropped();
}
ptr
});
check.assert_drops_with_gc(ptr);
}
#[cfg(not(pyo3_disable_reference_pool))]
#[test]
fn drop_during_traversal_without_gil() {
let (guard, check) = drop_check();
let inst = Python::with_gil(|py| {
let cycle = Mutex::new(None);
let inst = Py::new(
py,
DropDuringTraversal {
cycle,
_guard: guard,
},
)
.unwrap();
*inst.borrow_mut(py).cycle.lock().unwrap() = Some(inst.clone_ref(py));
check.assert_not_dropped();
inst
});
let ptr = inst.as_ptr();
drop(inst); // drop the object without holding the GIL
check.assert_drops_with_gc(ptr);
}
#[test]
#[cfg(not(target_arch = "wasm32"))] // We are building wasm Python with pthreads disabled
fn unsendable_are_not_traversed_on_foreign_thread() {
#[pyclass(unsendable)]
struct UnsendableTraversal {
traversed: Cell<bool>,
}
#[pymethods]
impl UnsendableTraversal {
fn __clear__(&mut self) {}
#[allow(clippy::unnecessary_wraps)]
fn __traverse__(&self, _visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
self.traversed.set(true);
Ok(())
}
}
#[derive(Clone, Copy)]
struct SendablePtr(*mut pyo3::ffi::PyObject);
unsafe impl Send for SendablePtr {}
Python::with_gil(|py| {
let ty = py.get_type::<UnsendableTraversal>();
let traverse = unsafe { get_type_traverse(ty.as_type_ptr()).unwrap() };
let obj = Bound::new(
py,
UnsendableTraversal {
traversed: Cell::new(false),
},
)
.unwrap();
let ptr = SendablePtr(obj.as_ptr());
std::thread::spawn(move || {
// traversal on foreign thread is a no-op
assert_eq!(
unsafe { traverse({ ptr }.0, novisit, std::ptr::null_mut()) },
0
);
})
.join()
.unwrap();
assert!(!obj.borrow().traversed.get());
// traversal on home thread still works
assert_eq!(
unsafe { traverse({ ptr }.0, novisit, std::ptr::null_mut()) },
0
);
assert!(obj.borrow().traversed.get());
});
}
#[test]
fn test_traverse_subclass() {
#[pyclass(extends = CycleWithClear)]
struct SubOverrideTraverse {}
#[pymethods]
impl SubOverrideTraverse {
#[allow(clippy::unnecessary_wraps)]
fn __traverse__(&self, _visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
// subclass traverse overrides the base class traverse
Ok(())
}
}
let (guard, check) = drop_check();
Python::with_gil(|py| {
let base = CycleWithClear {
cycle: None,
_guard: guard,
};
let obj = Bound::new(
py,
PyClassInitializer::from(base).add_subclass(SubOverrideTraverse {}),
)
.unwrap();
obj.borrow_mut().as_super().cycle = Some(obj.clone().into_any().unbind());
check.assert_not_dropped();
let ptr = obj.as_ptr();
drop(obj);
#[cfg(not(Py_GIL_DISABLED))]
{
// other thread might have caused GC on free-threaded build
check.assert_not_dropped();
}
#[cfg(not(Py_GIL_DISABLED))]
{
// FIXME: seems like a bug that this is flaky on the free-threaded build
// https://github.com/PyO3/pyo3/issues/4627
check.assert_drops_with_gc(ptr);
}
#[cfg(Py_GIL_DISABLED)]
{
// silence unused ptr warning
let _ = ptr;
}
});
}
#[test]
fn test_traverse_subclass_override_clear() {
#[pyclass(extends = CycleWithClear)]
struct SubOverrideClear {}
#[pymethods]
impl SubOverrideClear {
#[allow(clippy::unnecessary_wraps)]
fn __traverse__(&self, _visit: PyVisit<'_>) -> Result<(), PyTraverseError> {
// subclass traverse overrides the base class traverse, necessary for
// the sub clear to be called
// FIXME: should this really need to be the case?
Ok(())
}
fn __clear__(&self) {
// subclass clear overrides the base class clear
}
}
let (guard, check) = drop_check();
Python::with_gil(|py| {
let base = CycleWithClear {
cycle: None,
_guard: guard,
};
let obj = Bound::new(
py,
PyClassInitializer::from(base).add_subclass(SubOverrideClear {}),
)
.unwrap();
obj.borrow_mut().as_super().cycle = Some(obj.clone().into_any().unbind());
check.assert_not_dropped();
let ptr = obj.as_ptr();
drop(obj);
#[cfg(not(Py_GIL_DISABLED))]
{
// other thread might have caused GC on free-threaded build
check.assert_not_dropped();
}
#[cfg(not(Py_GIL_DISABLED))]
{
// FIXME: seems like a bug that this is flaky on the free-threaded build
// https://github.com/PyO3/pyo3/issues/4627
check.assert_drops_with_gc(ptr);
}
#[cfg(Py_GIL_DISABLED)]
{
// silence unused ptr warning
let _ = ptr;
}
});
}
// Manual traversal utilities
unsafe fn get_type_traverse(tp: *mut pyo3::ffi::PyTypeObject) -> Option<pyo3::ffi::traverseproc> {
std::mem::transmute(pyo3::ffi::PyType_GetSlot(tp, pyo3::ffi::Py_tp_traverse))
}
// a dummy visitor function
extern "C" fn novisit(
_object: *mut pyo3::ffi::PyObject,
_arg: *mut core::ffi::c_void,
) -> std::os::raw::c_int {
0
}
// a visitor function which errors (returns nonzero code)
extern "C" fn visit_error(
_object: *mut pyo3::ffi::PyObject,
_arg: *mut core::ffi::c_void,
) -> std::os::raw::c_int {
-1
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_multiple_pymethods.rs | #![cfg(feature = "multiple-pymethods")]
use pyo3::prelude::*;
use pyo3::types::PyType;
#[macro_use]
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
struct PyClassWithMultiplePyMethods {}
#[pymethods]
impl PyClassWithMultiplePyMethods {
#[new]
fn new() -> Self {
Self {}
}
}
#[pymethods]
impl PyClassWithMultiplePyMethods {
fn __call__(&self) -> &'static str {
"call"
}
}
#[pymethods]
impl PyClassWithMultiplePyMethods {
fn method(&self) -> &'static str {
"method"
}
}
#[pymethods]
impl PyClassWithMultiplePyMethods {
#[classmethod]
fn classmethod(_ty: &Bound<'_, PyType>) -> &'static str {
"classmethod"
}
}
#[pymethods]
impl PyClassWithMultiplePyMethods {
#[staticmethod]
fn staticmethod() -> &'static str {
"staticmethod"
}
}
#[pymethods]
impl PyClassWithMultiplePyMethods {
#[classattr]
fn class_attribute() -> &'static str {
"class_attribute"
}
}
#[pymethods]
impl PyClassWithMultiplePyMethods {
#[classattr]
const CLASS_ATTRIBUTE: &'static str = "CLASS_ATTRIBUTE";
}
#[test]
fn test_class_with_multiple_pymethods() {
Python::with_gil(|py| {
let cls = py.get_type::<PyClassWithMultiplePyMethods>();
py_assert!(py, cls, "cls()() == 'call'");
py_assert!(py, cls, "cls().method() == 'method'");
py_assert!(py, cls, "cls.classmethod() == 'classmethod'");
py_assert!(py, cls, "cls.staticmethod() == 'staticmethod'");
py_assert!(py, cls, "cls.class_attribute == 'class_attribute'");
py_assert!(py, cls, "cls.CLASS_ATTRIBUTE == 'CLASS_ATTRIBUTE'");
})
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_pyself.rs | #![cfg(feature = "macros")]
//! Test slf: PyRef/PyMutRef<Self>(especially, slf.into::<Py>) works
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyString};
use std::collections::HashMap;
#[path = "../src/tests/common.rs"]
mod common;
/// Assumes it's a file reader or so.
/// Inspired by https://github.com/jothan/cordoba, thanks.
#[pyclass]
#[derive(Clone, Debug)]
struct Reader {
inner: HashMap<u8, String>,
}
#[pymethods]
impl Reader {
fn clone_ref<'a, 'py>(slf: &'a Bound<'py, Self>) -> &'a Bound<'py, Self> {
slf
}
fn clone_ref_with_py<'a, 'py>(
slf: &'a Bound<'py, Self>,
_py: Python<'py>,
) -> &'a Bound<'py, Self> {
slf
}
fn get_iter(slf: &Bound<'_, Self>, keys: Py<PyBytes>) -> Iter {
Iter {
reader: slf.clone().unbind(),
keys,
idx: 0,
}
}
fn get_iter_and_reset(
mut slf: PyRefMut<'_, Self>,
keys: Py<PyBytes>,
py: Python<'_>,
) -> PyResult<Iter> {
let reader = Py::new(py, slf.clone())?;
slf.inner.clear();
Ok(Iter {
reader,
keys,
idx: 0,
})
}
}
#[pyclass]
#[derive(Debug)]
struct Iter {
reader: Py<Reader>,
keys: Py<PyBytes>,
idx: usize,
}
#[pymethods]
impl Iter {
#[allow(clippy::self_named_constructors)]
fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __next__(mut slf: PyRefMut<'_, Self>) -> PyResult<Option<PyObject>> {
let bytes = slf.keys.bind(slf.py()).as_bytes();
match bytes.get(slf.idx) {
Some(&b) => {
slf.idx += 1;
let py = slf.py();
let reader = slf.reader.bind(py);
let reader_ref = reader.try_borrow()?;
let res = reader_ref
.inner
.get(&b)
.map(|s| PyString::new(py, s).into());
Ok(res)
}
None => Ok(None),
}
}
}
fn reader() -> Reader {
let reader = [(1, "a"), (2, "b"), (3, "c"), (4, "d"), (5, "e")];
Reader {
inner: reader.iter().map(|(k, v)| (*k, (*v).to_string())).collect(),
}
}
#[test]
fn test_nested_iter() {
Python::with_gil(|py| {
let reader = reader().into_pyobject(py).unwrap();
py_assert!(
py,
reader,
"list(reader.get_iter(bytes([3, 5, 2]))) == ['c', 'e', 'b']"
);
});
}
#[test]
fn test_clone_ref() {
Python::with_gil(|py| {
let reader = reader().into_pyobject(py).unwrap();
py_assert!(py, reader, "reader == reader.clone_ref()");
py_assert!(py, reader, "reader == reader.clone_ref_with_py()");
});
}
#[test]
fn test_nested_iter_reset() {
Python::with_gil(|py| {
let reader = Bound::new(py, reader()).unwrap();
py_assert!(
py,
reader,
"list(reader.get_iter_and_reset(bytes([3, 5, 2]))) == ['c', 'e', 'b']"
);
let reader_ref = reader.borrow();
assert!(reader_ref.inner.is_empty());
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_compile_error.rs | #![cfg(feature = "macros")]
#[cfg(not(target_arch = "wasm32"))] // Not possible to invoke compiler from wasm
#[test]
fn test_compile_errors() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/invalid_property_args.rs");
t.compile_fail("tests/ui/invalid_proto_pymethods.rs");
t.compile_fail("tests/ui/invalid_pyclass_args.rs");
t.compile_fail("tests/ui/invalid_pyclass_enum.rs");
t.compile_fail("tests/ui/invalid_pyclass_item.rs");
t.compile_fail("tests/ui/invalid_pyfunction_signatures.rs");
t.compile_fail("tests/ui/invalid_pyfunction_definition.rs");
#[cfg(any(not(Py_LIMITED_API), Py_3_11))]
t.compile_fail("tests/ui/invalid_pymethods_buffer.rs");
// The output is not stable across abi3 / not abi3 and features
#[cfg(all(not(Py_LIMITED_API), feature = "full"))]
t.compile_fail("tests/ui/invalid_pymethods_duplicates.rs");
t.compile_fail("tests/ui/invalid_pymethod_enum.rs");
t.compile_fail("tests/ui/invalid_pymethod_names.rs");
t.compile_fail("tests/ui/invalid_pymodule_args.rs");
t.compile_fail("tests/ui/reject_generics.rs");
t.compile_fail("tests/ui/deprecations.rs");
t.compile_fail("tests/ui/invalid_closure.rs");
t.compile_fail("tests/ui/pyclass_send.rs");
t.compile_fail("tests/ui/invalid_argument_attributes.rs");
t.compile_fail("tests/ui/invalid_intopy_derive.rs");
t.compile_fail("tests/ui/invalid_frompy_derive.rs");
t.compile_fail("tests/ui/static_ref.rs");
t.compile_fail("tests/ui/wrong_aspyref_lifetimes.rs");
t.compile_fail("tests/ui/invalid_pyfunctions.rs");
#[cfg(not(any(feature = "hashbrown", feature = "indexmap")))]
t.compile_fail("tests/ui/invalid_pymethods.rs");
// output changes with async feature
#[cfg(all(Py_LIMITED_API, feature = "experimental-async"))]
t.compile_fail("tests/ui/abi3_nativetype_inheritance.rs");
t.compile_fail("tests/ui/invalid_intern_arg.rs");
t.compile_fail("tests/ui/invalid_frozen_pyclass_borrow.rs");
#[cfg(not(any(feature = "hashbrown", feature = "indexmap")))]
t.compile_fail("tests/ui/invalid_pymethod_receiver.rs");
t.compile_fail("tests/ui/missing_intopy.rs");
// adding extra error conversion impls changes the output
#[cfg(not(any(windows, feature = "eyre", feature = "anyhow", Py_LIMITED_API)))]
t.compile_fail("tests/ui/invalid_result_conversion.rs");
t.compile_fail("tests/ui/not_send.rs");
t.compile_fail("tests/ui/not_send2.rs");
t.compile_fail("tests/ui/get_set_all.rs");
t.compile_fail("tests/ui/traverse.rs");
t.compile_fail("tests/ui/invalid_pymodule_in_root.rs");
t.compile_fail("tests/ui/invalid_pymodule_glob.rs");
t.compile_fail("tests/ui/invalid_pymodule_trait.rs");
t.compile_fail("tests/ui/invalid_pymodule_two_pymodule_init.rs");
#[cfg(feature = "experimental-async")]
#[cfg(any(not(Py_LIMITED_API), Py_3_10))] // to avoid PyFunctionArgument for &str
t.compile_fail("tests/ui/invalid_cancel_handle.rs");
t.pass("tests/ui/pymodule_missing_docs.rs");
#[cfg(not(Py_LIMITED_API))]
t.pass("tests/ui/forbid_unsafe.rs");
#[cfg(all(Py_LIMITED_API, not(feature = "experimental-async")))]
// output changes with async feature
t.compile_fail("tests/ui/abi3_inheritance.rs");
#[cfg(all(Py_LIMITED_API, not(Py_3_9)))]
t.compile_fail("tests/ui/abi3_weakref.rs");
#[cfg(all(Py_LIMITED_API, not(Py_3_9)))]
t.compile_fail("tests/ui/abi3_dict.rs");
t.compile_fail("tests/ui/duplicate_pymodule_submodule.rs");
#[cfg(all(not(Py_LIMITED_API), Py_3_11))]
t.compile_fail("tests/ui/invalid_base_class.rs");
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_default_impls.rs | #![cfg(feature = "macros")]
use pyo3::prelude::*;
#[path = "../src/tests/common.rs"]
mod common;
// Test default generated __repr__.
#[pyclass(eq, eq_int)]
#[derive(PartialEq)]
enum TestDefaultRepr {
Var,
}
#[test]
fn test_default_slot_exists() {
Python::with_gil(|py| {
let test_object = Py::new(py, TestDefaultRepr::Var).unwrap();
py_assert!(
py,
test_object,
"repr(test_object) == 'TestDefaultRepr.Var'"
);
})
}
#[pyclass(eq, eq_int)]
#[derive(PartialEq)]
enum OverrideSlot {
Var,
}
#[pymethods]
impl OverrideSlot {
fn __repr__(&self) -> &str {
"overridden"
}
}
#[test]
fn test_override_slot() {
Python::with_gil(|py| {
let test_object = Py::new(py, OverrideSlot::Var).unwrap();
py_assert!(py, test_object, "repr(test_object) == 'overridden'");
})
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_declarative_module.rs | #![cfg(feature = "macros")]
use std::sync::Once;
use pyo3::create_exception;
use pyo3::exceptions::PyException;
use pyo3::prelude::*;
use pyo3::sync::{GILOnceCell, OnceExt};
#[path = "../src/tests/common.rs"]
mod common;
mod some_module {
use pyo3::create_exception;
use pyo3::exceptions::PyException;
use pyo3::prelude::*;
#[pyclass]
pub struct SomePyClass;
create_exception!(some_module, SomeException, PyException);
}
#[pyclass]
struct ValueClass {
value: usize,
}
#[pymethods]
impl ValueClass {
#[new]
fn new(value: usize) -> Self {
Self { value }
}
}
#[pyclass(module = "module")]
pub struct LocatedClass {}
#[pyfunction]
fn double(x: usize) -> usize {
x * 2
}
create_exception!(
declarative_module,
MyError,
PyException,
"Some description."
);
#[pymodule(submodule)]
mod external_submodule {}
/// A module written using declarative syntax.
#[pymodule]
mod declarative_module {
#[pymodule_export]
use super::declarative_submodule;
#[pymodule_export]
// This is not a real constraint but to test cfg attribute support
#[cfg(not(Py_LIMITED_API))]
use super::LocatedClass;
use super::*;
#[pymodule_export]
use super::{declarative_module2, double, MyError, ValueClass as Value};
// test for #4036
#[pymodule_export]
use super::some_module::SomePyClass;
// test for #4036
#[pymodule_export]
use super::some_module::SomeException;
#[pymodule_export]
use super::external_submodule;
#[pymodule]
mod inner {
use super::*;
#[pyfunction]
fn triple(x: usize) -> usize {
x * 3
}
#[pyclass(name = "Struct")]
struct Struct;
#[pymethods]
impl Struct {
#[new]
fn new() -> Self {
Self
}
}
#[pyclass(module = "foo")]
struct StructInCustomModule;
#[pyclass(eq, eq_int, name = "Enum")]
#[derive(PartialEq)]
enum Enum {
A,
B,
}
#[pyclass(eq, eq_int, module = "foo")]
#[derive(PartialEq)]
enum EnumInCustomModule {
A,
B,
}
}
#[pymodule]
#[pyo3(module = "custom_root")]
mod inner_custom_root {
use super::*;
#[pyclass]
struct Struct;
}
#[pyo3::prelude::pymodule]
mod full_path_inner {}
#[pymodule_init]
fn init(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add("double2", m.getattr("double")?)
}
}
#[pyfunction]
fn double_value(v: &ValueClass) -> usize {
v.value * 2
}
#[pymodule]
mod declarative_submodule {
#[pymodule_export]
use super::{double, double_value};
}
#[pymodule(name = "declarative_module_renamed")]
mod declarative_module2 {
#[pymodule_export]
use super::double;
}
fn declarative_module(py: Python<'_>) -> &Bound<'_, PyModule> {
static MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
static ONCE: Once = Once::new();
// Guarantee that the module is only ever initialized once; GILOnceCell can race.
// TODO: use OnceLock when MSRV >= 1.70
ONCE.call_once_py_attached(py, || {
MODULE
.set(py, pyo3::wrap_pymodule!(declarative_module)(py))
.expect("only ever set once");
});
MODULE.get(py).expect("once is completed").bind(py)
}
#[test]
fn test_declarative_module() {
Python::with_gil(|py| {
let m = declarative_module(py);
py_assert!(
py,
m,
"m.__doc__ == 'A module written using declarative syntax.'"
);
py_assert!(py, m, "m.double(2) == 4");
py_assert!(py, m, "m.inner.triple(3) == 9");
py_assert!(py, m, "m.declarative_submodule.double(4) == 8");
py_assert!(
py,
m,
"m.declarative_submodule.double_value(m.ValueClass(1)) == 2"
);
py_assert!(py, m, "str(m.MyError('foo')) == 'foo'");
py_assert!(py, m, "m.declarative_module_renamed.double(2) == 4");
#[cfg(Py_LIMITED_API)]
py_assert!(py, m, "not hasattr(m, 'LocatedClass')");
#[cfg(not(Py_LIMITED_API))]
py_assert!(py, m, "hasattr(m, 'LocatedClass')");
py_assert!(py, m, "isinstance(m.inner.Struct(), m.inner.Struct)");
py_assert!(py, m, "isinstance(m.inner.Enum.A, m.inner.Enum)");
py_assert!(py, m, "hasattr(m, 'external_submodule')")
})
}
#[pymodule]
mod r#type {
#[pymodule_export]
use super::double;
}
#[test]
fn test_raw_ident_module() {
Python::with_gil(|py| {
let m = pyo3::wrap_pymodule!(r#type)(py).into_bound(py);
py_assert!(py, m, "m.double(2) == 4");
})
}
#[test]
fn test_module_names() {
Python::with_gil(|py| {
let m = declarative_module(py);
py_assert!(
py,
m,
"m.inner.Struct.__module__ == 'declarative_module.inner'"
);
py_assert!(py, m, "m.inner.StructInCustomModule.__module__ == 'foo'");
py_assert!(
py,
m,
"m.inner.Enum.__module__ == 'declarative_module.inner'"
);
py_assert!(py, m, "m.inner.EnumInCustomModule.__module__ == 'foo'");
py_assert!(
py,
m,
"m.inner_custom_root.Struct.__module__ == 'custom_root.inner_custom_root'"
);
})
}
#[test]
fn test_inner_module_full_path() {
Python::with_gil(|py| {
let m = declarative_module(py);
py_assert!(py, m, "m.full_path_inner");
})
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_enum.rs | #![cfg(feature = "macros")]
use pyo3::prelude::*;
use pyo3::py_run;
use pyo3::types::PyString;
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass(eq, eq_int)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum MyEnum {
Variant,
OtherVariant,
}
#[test]
fn test_enum_class_attr() {
Python::with_gil(|py| {
let my_enum = py.get_type::<MyEnum>();
let var = Py::new(py, MyEnum::Variant).unwrap();
py_assert!(py, my_enum var, "my_enum.Variant == var");
})
}
#[pyfunction]
fn return_enum() -> MyEnum {
MyEnum::Variant
}
#[test]
fn test_return_enum() {
Python::with_gil(|py| {
let f = wrap_pyfunction!(return_enum)(py).unwrap();
let mynum = py.get_type::<MyEnum>();
py_run!(py, f mynum, "assert f() == mynum.Variant")
});
}
#[pyfunction]
fn enum_arg(e: MyEnum) {
assert_eq!(MyEnum::OtherVariant, e)
}
#[test]
fn test_enum_arg() {
Python::with_gil(|py| {
let f = wrap_pyfunction!(enum_arg)(py).unwrap();
let mynum = py.get_type::<MyEnum>();
py_run!(py, f mynum, "f(mynum.OtherVariant)")
})
}
#[pyclass(eq, eq_int)]
#[derive(Debug, PartialEq, Eq, Clone)]
enum CustomDiscriminant {
One = 1,
Two = 2,
}
#[test]
fn test_custom_discriminant() {
Python::with_gil(|py| {
#[allow(non_snake_case)]
let CustomDiscriminant = py.get_type::<CustomDiscriminant>();
let one = Py::new(py, CustomDiscriminant::One).unwrap();
let two = Py::new(py, CustomDiscriminant::Two).unwrap();
py_run!(py, CustomDiscriminant one two, r#"
assert CustomDiscriminant.One == one
assert CustomDiscriminant.Two == two
assert one != two
"#);
})
}
#[test]
fn test_enum_to_int() {
Python::with_gil(|py| {
let one = Py::new(py, CustomDiscriminant::One).unwrap();
py_assert!(py, one, "int(one) == 1");
let v = Py::new(py, MyEnum::Variant).unwrap();
let v_value = MyEnum::Variant as isize;
py_run!(py, v v_value, "int(v) == v_value");
})
}
#[test]
fn test_enum_compare_int() {
Python::with_gil(|py| {
let one = Py::new(py, CustomDiscriminant::One).unwrap();
py_run!(
py,
one,
r#"
assert one == 1
assert 1 == one
assert one != 2
"#
)
})
}
#[pyclass(eq, eq_int)]
#[derive(Debug, PartialEq, Eq, Clone)]
#[repr(u8)]
enum SmallEnum {
V = 1,
}
#[test]
fn test_enum_compare_int_no_throw_when_overflow() {
Python::with_gil(|py| {
let v = Py::new(py, SmallEnum::V).unwrap();
py_assert!(py, v, "v != 1<<30")
})
}
#[pyclass(eq, eq_int)]
#[derive(Debug, PartialEq, Eq, Clone)]
#[repr(usize)]
#[allow(clippy::enum_clike_unportable_variant)]
enum BigEnum {
V = usize::MAX,
}
#[test]
fn test_big_enum_no_overflow() {
Python::with_gil(|py| {
let usize_max = usize::MAX;
let v = Py::new(py, BigEnum::V).unwrap();
py_assert!(py, usize_max v, "v == usize_max");
py_assert!(py, usize_max v, "int(v) == usize_max");
})
}
#[pyclass(eq, eq_int)]
#[derive(Debug, PartialEq, Eq, Clone)]
#[repr(u16, align(8))]
enum TestReprParse {
V,
}
#[test]
fn test_repr_parse() {
assert_eq!(std::mem::align_of::<TestReprParse>(), 8);
}
#[pyclass(eq, eq_int, name = "MyEnum")]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RenameEnum {
Variant,
}
#[test]
fn test_rename_enum_repr_correct() {
Python::with_gil(|py| {
let var1 = Py::new(py, RenameEnum::Variant).unwrap();
py_assert!(py, var1, "repr(var1) == 'MyEnum.Variant'");
})
}
#[pyclass(eq, eq_int)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RenameVariantEnum {
#[pyo3(name = "VARIANT")]
Variant,
}
#[test]
fn test_rename_variant_repr_correct() {
Python::with_gil(|py| {
let var1 = Py::new(py, RenameVariantEnum::Variant).unwrap();
py_assert!(py, var1, "repr(var1) == 'RenameVariantEnum.VARIANT'");
})
}
#[pyclass(eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Debug, PartialEq, Eq, Clone)]
#[allow(clippy::enum_variant_names)]
enum RenameAllVariantsEnum {
VariantOne,
VariantTwo,
#[pyo3(name = "VariantThree")]
VariantFour,
}
#[test]
fn test_renaming_all_enum_variants() {
Python::with_gil(|py| {
let enum_obj = py.get_type::<RenameAllVariantsEnum>();
py_assert!(py, enum_obj, "enum_obj.VARIANT_ONE == enum_obj.VARIANT_ONE");
py_assert!(py, enum_obj, "enum_obj.VARIANT_TWO == enum_obj.VARIANT_TWO");
py_assert!(
py,
enum_obj,
"enum_obj.VariantThree == enum_obj.VariantThree"
);
});
}
#[pyclass(module = "custom_module")]
#[derive(Debug)]
enum CustomModuleComplexEnum {
Variant(),
Py(Py<PyAny>),
}
#[test]
fn test_custom_module() {
Python::with_gil(|py| {
let enum_obj = py.get_type::<CustomModuleComplexEnum>();
py_assert!(
py,
enum_obj,
"enum_obj.Variant.__module__ == 'custom_module'"
);
});
}
#[pyclass(eq)]
#[derive(Debug, Clone, PartialEq)]
pub enum EqOnly {
VariantA,
VariantB,
}
#[test]
fn test_simple_enum_eq_only() {
Python::with_gil(|py| {
let var1 = Py::new(py, EqOnly::VariantA).unwrap();
let var2 = Py::new(py, EqOnly::VariantA).unwrap();
let var3 = Py::new(py, EqOnly::VariantB).unwrap();
py_assert!(py, var1 var2, "var1 == var2");
py_assert!(py, var1 var3, "var1 != var3");
})
}
#[pyclass(frozen, eq, eq_int, hash)]
#[derive(PartialEq, Hash)]
enum SimpleEnumWithHash {
A,
B,
}
#[test]
fn test_simple_enum_with_hash() {
Python::with_gil(|py| {
use pyo3::types::IntoPyDict;
let class = SimpleEnumWithHash::A;
let hash = {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
class.hash(&mut hasher);
hasher.finish() as isize
};
let env = [
("obj", Py::new(py, class).unwrap().into_any()),
("hsh", hash.into_pyobject(py).unwrap().into_any().unbind()),
]
.into_py_dict(py)
.unwrap();
py_assert!(py, *env, "hash(obj) == hsh");
});
}
#[pyclass(eq, hash)]
#[derive(PartialEq, Hash)]
enum ComplexEnumWithHash {
A(u32),
B { msg: String },
}
#[test]
fn test_complex_enum_with_hash() {
Python::with_gil(|py| {
use pyo3::types::IntoPyDict;
let class = ComplexEnumWithHash::B {
msg: String::from("Hello"),
};
let hash = {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
class.hash(&mut hasher);
hasher.finish() as isize
};
let env = [
("obj", Py::new(py, class).unwrap().into_any()),
("hsh", hash.into_pyobject(py).unwrap().into_any().unbind()),
]
.into_py_dict(py)
.unwrap();
py_assert!(py, *env, "hash(obj) == hsh");
});
}
#[allow(deprecated)]
mod deprecated {
use crate::py_assert;
use pyo3::prelude::*;
use pyo3::py_run;
#[pyclass]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum MyEnum {
Variant,
OtherVariant,
}
#[test]
fn test_enum_eq_enum() {
Python::with_gil(|py| {
let var1 = Py::new(py, MyEnum::Variant).unwrap();
let var2 = Py::new(py, MyEnum::Variant).unwrap();
let other_var = Py::new(py, MyEnum::OtherVariant).unwrap();
py_assert!(py, var1 var2, "var1 == var2");
py_assert!(py, var1 other_var, "var1 != other_var");
py_assert!(py, var1 var2, "(var1 != var2) == False");
})
}
#[test]
fn test_enum_eq_incomparable() {
Python::with_gil(|py| {
let var1 = Py::new(py, MyEnum::Variant).unwrap();
py_assert!(py, var1, "(var1 == 'foo') == False");
py_assert!(py, var1, "(var1 != 'foo') == True");
})
}
#[pyclass]
enum CustomDiscriminant {
One = 1,
Two = 2,
}
#[test]
fn test_custom_discriminant() {
Python::with_gil(|py| {
#[allow(non_snake_case)]
let CustomDiscriminant = py.get_type::<CustomDiscriminant>();
let one = Py::new(py, CustomDiscriminant::One).unwrap();
let two = Py::new(py, CustomDiscriminant::Two).unwrap();
py_run!(py, CustomDiscriminant one two, r#"
assert CustomDiscriminant.One == one
assert CustomDiscriminant.Two == two
assert CustomDiscriminant.One == 1
assert CustomDiscriminant.Two == 2
assert one != two
assert CustomDiscriminant.One != 2
assert CustomDiscriminant.Two != 1
"#);
})
}
}
#[test]
fn custom_eq() {
#[pyclass(frozen)]
#[derive(PartialEq)]
pub enum CustomPyEq {
A,
B,
}
#[pymethods]
impl CustomPyEq {
fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool {
if let Ok(rhs) = other.downcast::<PyString>() {
rhs.to_cow().map_or(false, |rhs| self.__str__() == rhs)
} else if let Ok(rhs) = other.downcast::<Self>() {
self == rhs.get()
} else {
false
}
}
fn __str__(&self) -> String {
match self {
CustomPyEq::A => "A".to_string(),
CustomPyEq::B => "B".to_string(),
}
}
}
Python::with_gil(|py| {
let a = Bound::new(py, CustomPyEq::A).unwrap();
let b = Bound::new(py, CustomPyEq::B).unwrap();
assert!(a.as_any().eq(&a).unwrap());
assert!(a.as_any().eq("A").unwrap());
assert!(a.as_any().ne(&b).unwrap());
assert!(a.as_any().ne("B").unwrap());
assert!(b.as_any().eq(&b).unwrap());
assert!(b.as_any().eq("B").unwrap());
assert!(b.as_any().ne(&a).unwrap());
assert!(b.as_any().ne("A").unwrap());
})
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_frompy_intopy_roundtrip.rs | #![cfg(feature = "macros")]
use pyo3::types::{PyDict, PyString};
use pyo3::{prelude::*, IntoPyObject, IntoPyObjectRef};
use std::collections::HashMap;
use std::hash::Hash;
#[macro_use]
#[path = "../src/tests/common.rs"]
mod common;
#[derive(Debug, Clone, IntoPyObject, IntoPyObjectRef, FromPyObject)]
pub struct A<'py> {
#[pyo3(item)]
s: String,
#[pyo3(item)]
t: Bound<'py, PyString>,
#[pyo3(item("foo"))]
p: Bound<'py, PyAny>,
}
#[test]
fn test_named_fields_struct() {
Python::with_gil(|py| {
let a = A {
s: "Hello".into(),
t: PyString::new(py, "World"),
p: 42i32.into_pyobject(py).unwrap().into_any(),
};
let pya = (&a).into_pyobject(py).unwrap();
let new_a = pya.extract::<A<'_>>().unwrap();
assert_eq!(a.s, new_a.s);
assert_eq!(a.t.to_cow().unwrap(), new_a.t.to_cow().unwrap());
assert_eq!(
a.p.extract::<i32>().unwrap(),
new_a.p.extract::<i32>().unwrap()
);
let pya = a.clone().into_pyobject(py).unwrap();
let new_a = pya.extract::<A<'_>>().unwrap();
assert_eq!(a.s, new_a.s);
assert_eq!(a.t.to_cow().unwrap(), new_a.t.to_cow().unwrap());
assert_eq!(
a.p.extract::<i32>().unwrap(),
new_a.p.extract::<i32>().unwrap()
);
});
}
#[derive(Debug, Clone, PartialEq, IntoPyObject, IntoPyObjectRef, FromPyObject)]
#[pyo3(transparent)]
pub struct B {
test: String,
}
#[test]
fn test_transparent_named_field_struct() {
Python::with_gil(|py| {
let b = B {
test: "test".into(),
};
let pyb = (&b).into_pyobject(py).unwrap();
let new_b = pyb.extract::<B>().unwrap();
assert_eq!(b, new_b);
let pyb = b.clone().into_pyobject(py).unwrap();
let new_b = pyb.extract::<B>().unwrap();
assert_eq!(b, new_b);
});
}
#[derive(Debug, Clone, PartialEq, IntoPyObject, IntoPyObjectRef, FromPyObject)]
#[pyo3(transparent)]
pub struct D<T> {
test: T,
}
#[test]
fn test_generic_transparent_named_field_struct() {
Python::with_gil(|py| {
let d = D {
test: String::from("test"),
};
let pyd = (&d).into_pyobject(py).unwrap();
let new_d = pyd.extract::<D<String>>().unwrap();
assert_eq!(d, new_d);
let d = D { test: 1usize };
let pyd = (&d).into_pyobject(py).unwrap();
let new_d = pyd.extract::<D<usize>>().unwrap();
assert_eq!(d, new_d);
let d = D {
test: String::from("test"),
};
let pyd = d.clone().into_pyobject(py).unwrap();
let new_d = pyd.extract::<D<String>>().unwrap();
assert_eq!(d, new_d);
let d = D { test: 1usize };
let pyd = d.clone().into_pyobject(py).unwrap();
let new_d = pyd.extract::<D<usize>>().unwrap();
assert_eq!(d, new_d);
});
}
#[derive(Debug, IntoPyObject, IntoPyObjectRef, FromPyObject)]
pub struct GenericWithBound<K: Hash + Eq, V>(HashMap<K, V>);
#[test]
fn test_generic_with_bound() {
Python::with_gil(|py| {
let mut hash_map = HashMap::<String, i32>::new();
hash_map.insert("1".into(), 1);
hash_map.insert("2".into(), 2);
let map = GenericWithBound(hash_map);
let py_map = (&map).into_pyobject(py).unwrap();
assert_eq!(py_map.len(), 2);
assert_eq!(
py_map
.get_item("1")
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap(),
1
);
assert_eq!(
py_map
.get_item("2")
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap(),
2
);
assert!(py_map.get_item("3").unwrap().is_none());
let py_map = map.into_pyobject(py).unwrap();
assert_eq!(py_map.len(), 2);
assert_eq!(
py_map
.get_item("1")
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap(),
1
);
assert_eq!(
py_map
.get_item("2")
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap(),
2
);
assert!(py_map.get_item("3").unwrap().is_none());
});
}
#[derive(Debug, Clone, PartialEq, IntoPyObject, IntoPyObjectRef, FromPyObject)]
pub struct Tuple(String, usize);
#[test]
fn test_tuple_struct() {
Python::with_gil(|py| {
let tup = Tuple(String::from("test"), 1);
let tuple = (&tup).into_pyobject(py).unwrap();
let new_tup = tuple.extract::<Tuple>().unwrap();
assert_eq!(tup, new_tup);
let tuple = tup.clone().into_pyobject(py).unwrap();
let new_tup = tuple.extract::<Tuple>().unwrap();
assert_eq!(tup, new_tup);
});
}
#[derive(Debug, Clone, PartialEq, IntoPyObject, IntoPyObjectRef, FromPyObject)]
pub struct TransparentTuple(String);
#[test]
fn test_transparent_tuple_struct() {
Python::with_gil(|py| {
let tup = TransparentTuple(String::from("test"));
let tuple = (&tup).into_pyobject(py).unwrap();
let new_tup = tuple.extract::<TransparentTuple>().unwrap();
assert_eq!(tup, new_tup);
let tuple = tup.clone().into_pyobject(py).unwrap();
let new_tup = tuple.extract::<TransparentTuple>().unwrap();
assert_eq!(tup, new_tup);
});
}
#[derive(Debug, Clone, PartialEq, IntoPyObject, IntoPyObjectRef, FromPyObject)]
pub enum Foo {
TupleVar(usize, String),
StructVar {
#[pyo3(item)]
test: char,
},
#[pyo3(transparent)]
TransparentTuple(usize),
#[pyo3(transparent)]
TransparentStructVar {
a: Option<String>,
},
}
#[test]
fn test_enum() {
Python::with_gil(|py| {
let tuple_var = Foo::TupleVar(1, "test".into());
let foo = (&tuple_var).into_pyobject(py).unwrap();
assert_eq!(tuple_var, foo.extract::<Foo>().unwrap());
let foo = tuple_var.clone().into_pyobject(py).unwrap();
assert_eq!(tuple_var, foo.extract::<Foo>().unwrap());
let struct_var = Foo::StructVar { test: 'b' };
let foo = (&struct_var)
.into_pyobject(py)
.unwrap()
.downcast_into::<PyDict>()
.unwrap();
assert_eq!(struct_var, foo.extract::<Foo>().unwrap());
let foo = struct_var
.clone()
.into_pyobject(py)
.unwrap()
.downcast_into::<PyDict>()
.unwrap();
assert_eq!(struct_var, foo.extract::<Foo>().unwrap());
let transparent_tuple = Foo::TransparentTuple(1);
let foo = (&transparent_tuple).into_pyobject(py).unwrap();
assert_eq!(transparent_tuple, foo.extract::<Foo>().unwrap());
let foo = transparent_tuple.clone().into_pyobject(py).unwrap();
assert_eq!(transparent_tuple, foo.extract::<Foo>().unwrap());
let transparent_struct_var = Foo::TransparentStructVar { a: None };
let foo = (&transparent_struct_var).into_pyobject(py).unwrap();
assert_eq!(transparent_struct_var, foo.extract::<Foo>().unwrap());
let foo = transparent_struct_var.clone().into_pyobject(py).unwrap();
assert_eq!(transparent_struct_var, foo.extract::<Foo>().unwrap());
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_frompyobject.rs | #![cfg(feature = "macros")]
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyDict, PyList, PyString, PyTuple};
#[macro_use]
#[path = "../src/tests/common.rs"]
mod common;
/// Helper function that concatenates the error message from
/// each error in the traceback into a single string that can
/// be tested.
fn extract_traceback(py: Python<'_>, mut error: PyErr) -> String {
let mut error_msg = error.to_string();
while let Some(cause) = error.cause(py) {
error_msg.push_str(": ");
error_msg.push_str(&cause.to_string());
error = cause
}
error_msg
}
#[derive(Debug, FromPyObject)]
pub struct A<'py> {
#[pyo3(attribute)]
s: String,
#[pyo3(item)]
t: Bound<'py, PyString>,
#[pyo3(attribute("foo"))]
p: Bound<'py, PyAny>,
}
#[pyclass]
pub struct PyA {
#[pyo3(get)]
s: String,
#[pyo3(get)]
foo: Option<String>,
}
#[pymethods]
impl PyA {
fn __getitem__(&self, key: String) -> pyo3::PyResult<String> {
if key == "t" {
Ok("bar".into())
} else {
Err(PyValueError::new_err("Failed"))
}
}
}
#[test]
fn test_named_fields_struct() {
Python::with_gil(|py| {
let pya = PyA {
s: "foo".into(),
foo: None,
};
let py_c = Py::new(py, pya).unwrap();
let a = py_c
.extract::<A<'_>>(py)
.expect("Failed to extract A from PyA");
assert_eq!(a.s, "foo");
assert_eq!(a.t.to_string_lossy(), "bar");
assert!(a.p.is_none());
});
}
#[derive(Debug, FromPyObject)]
#[pyo3(transparent)]
pub struct B {
test: String,
}
#[test]
fn test_transparent_named_field_struct() {
Python::with_gil(|py| {
let test = "test".into_pyobject(py).unwrap();
let b = test
.extract::<B>()
.expect("Failed to extract B from String");
assert_eq!(b.test, "test");
let test = 1i32.into_pyobject(py).unwrap();
let b = test.extract::<B>();
assert!(b.is_err());
});
}
#[derive(Debug, FromPyObject)]
#[pyo3(transparent)]
pub struct D<T> {
test: T,
}
#[test]
fn test_generic_transparent_named_field_struct() {
Python::with_gil(|py| {
let test = "test".into_pyobject(py).unwrap();
let d = test
.extract::<D<String>>()
.expect("Failed to extract D<String> from String");
assert_eq!(d.test, "test");
let test = 1usize.into_pyobject(py).unwrap();
let d = test
.extract::<D<usize>>()
.expect("Failed to extract D<usize> from String");
assert_eq!(d.test, 1);
});
}
#[derive(Debug, FromPyObject)]
pub struct GenericWithBound<K: std::hash::Hash + Eq, V>(std::collections::HashMap<K, V>);
#[test]
fn test_generic_with_bound() {
Python::with_gil(|py| {
let dict = [("1", 1), ("2", 2)].into_py_dict(py).unwrap();
let map = dict.extract::<GenericWithBound<String, i32>>().unwrap().0;
assert_eq!(map.len(), 2);
assert_eq!(map["1"], 1);
assert_eq!(map["2"], 2);
assert!(!map.contains_key("3"));
});
}
#[derive(Debug, FromPyObject)]
pub struct E<T, T2> {
test: T,
test2: T2,
}
#[pyclass]
#[derive(Clone)]
pub struct PyE {
#[pyo3(get)]
test: String,
#[pyo3(get)]
test2: usize,
}
#[test]
fn test_generic_named_fields_struct() {
Python::with_gil(|py| {
let pye = PyE {
test: "test".into(),
test2: 2,
}
.into_pyobject(py)
.unwrap();
let e = pye
.extract::<E<String, usize>>()
.expect("Failed to extract E<String, usize> from PyE");
assert_eq!(e.test, "test");
assert_eq!(e.test2, 2);
let e = pye.extract::<E<usize, usize>>();
assert!(e.is_err());
});
}
#[derive(Debug, FromPyObject)]
pub struct C {
#[pyo3(attribute("test"))]
test: String,
}
#[test]
fn test_named_field_with_ext_fn() {
Python::with_gil(|py| {
let pyc = PyE {
test: "foo".into(),
test2: 0,
}
.into_pyobject(py)
.unwrap();
let c = pyc.extract::<C>().expect("Failed to extract C from PyE");
assert_eq!(c.test, "foo");
});
}
#[derive(Debug, FromPyObject)]
pub struct Tuple(String, usize);
#[test]
fn test_tuple_struct() {
Python::with_gil(|py| {
let tup = PyTuple::new(
py,
&[
1i32.into_pyobject(py).unwrap().into_any(),
"test".into_pyobject(py).unwrap().into_any(),
],
)
.unwrap();
let tup = tup.extract::<Tuple>();
assert!(tup.is_err());
let tup = PyTuple::new(
py,
&[
"test".into_pyobject(py).unwrap().into_any(),
1i32.into_pyobject(py).unwrap().into_any(),
],
)
.unwrap();
let tup = tup
.extract::<Tuple>()
.expect("Failed to extract Tuple from PyTuple");
assert_eq!(tup.0, "test");
assert_eq!(tup.1, 1);
});
}
#[derive(Debug, FromPyObject)]
pub struct TransparentTuple(String);
#[test]
fn test_transparent_tuple_struct() {
Python::with_gil(|py| {
let tup = 1i32.into_pyobject(py).unwrap();
let tup = tup.extract::<TransparentTuple>();
assert!(tup.is_err());
let test = "test".into_pyobject(py).unwrap();
let tup = test
.extract::<TransparentTuple>()
.expect("Failed to extract TransparentTuple from PyTuple");
assert_eq!(tup.0, "test");
});
}
#[pyclass]
struct PyBaz {
#[pyo3(get)]
tup: (String, String),
#[pyo3(get)]
e: PyE,
}
#[derive(Debug, FromPyObject)]
#[allow(dead_code)]
struct Baz<U, T> {
e: E<U, T>,
tup: Tuple,
}
#[test]
fn test_struct_nested_type_errors() {
Python::with_gil(|py| {
let pybaz = PyBaz {
tup: ("test".into(), "test".into()),
e: PyE {
test: "foo".into(),
test2: 0,
},
}
.into_pyobject(py)
.unwrap();
let test = pybaz.extract::<Baz<String, usize>>();
assert!(test.is_err());
assert_eq!(
extract_traceback(py,test.unwrap_err()),
"TypeError: failed to extract field Baz.tup: TypeError: failed to extract field Tuple.1: \
TypeError: \'str\' object cannot be interpreted as an integer"
);
});
}
#[test]
fn test_struct_nested_type_errors_with_generics() {
Python::with_gil(|py| {
let pybaz = PyBaz {
tup: ("test".into(), "test".into()),
e: PyE {
test: "foo".into(),
test2: 0,
},
}
.into_pyobject(py)
.unwrap();
let test = pybaz.extract::<Baz<usize, usize>>();
assert!(test.is_err());
assert_eq!(
extract_traceback(py, test.unwrap_err()),
"TypeError: failed to extract field Baz.e: TypeError: failed to extract field E.test: \
TypeError: \'str\' object cannot be interpreted as an integer",
);
});
}
#[test]
fn test_transparent_struct_error_message() {
Python::with_gil(|py| {
let tup = 1i32.into_pyobject(py).unwrap();
let tup = tup.extract::<B>();
assert!(tup.is_err());
assert_eq!(
extract_traceback(py,tup.unwrap_err()),
"TypeError: failed to extract field B.test: TypeError: \'int\' object cannot be converted \
to \'PyString\'"
);
});
}
#[test]
fn test_tuple_struct_error_message() {
Python::with_gil(|py| {
let tup = (1, "test").into_pyobject(py).unwrap();
let tup = tup.extract::<Tuple>();
assert!(tup.is_err());
assert_eq!(
extract_traceback(py, tup.unwrap_err()),
"TypeError: failed to extract field Tuple.0: TypeError: \'int\' object cannot be \
converted to \'PyString\'"
);
});
}
#[test]
fn test_transparent_tuple_error_message() {
Python::with_gil(|py| {
let tup = 1i32.into_pyobject(py).unwrap();
let tup = tup.extract::<TransparentTuple>();
assert!(tup.is_err());
assert_eq!(
extract_traceback(py, tup.unwrap_err()),
"TypeError: failed to extract field TransparentTuple.0: TypeError: 'int' object \
cannot be converted to 'PyString'",
);
});
}
#[derive(Debug, FromPyObject)]
pub enum Foo<'py> {
TupleVar(usize, String),
StructVar {
test: Bound<'py, PyString>,
},
#[pyo3(transparent)]
TransparentTuple(usize),
#[pyo3(transparent)]
TransparentStructVar {
a: Option<String>,
},
StructVarGetAttrArg {
#[pyo3(attribute("bla"))]
a: bool,
},
StructWithGetItem {
#[pyo3(item)]
a: String,
},
StructWithGetItemArg {
#[pyo3(item("foo"))]
a: String,
},
}
#[pyclass]
pub struct PyBool {
#[pyo3(get)]
bla: bool,
}
#[test]
fn test_enum() {
Python::with_gil(|py| {
let tup = PyTuple::new(
py,
&[
1i32.into_pyobject(py).unwrap().into_any(),
"test".into_pyobject(py).unwrap().into_any(),
],
)
.unwrap();
let f = tup
.extract::<Foo<'_>>()
.expect("Failed to extract Foo from tuple");
match f {
Foo::TupleVar(test, test2) => {
assert_eq!(test, 1);
assert_eq!(test2, "test");
}
_ => panic!("Expected extracting Foo::TupleVar, got {:?}", f),
}
let pye = PyE {
test: "foo".into(),
test2: 0,
}
.into_pyobject(py)
.unwrap();
let f = pye
.extract::<Foo<'_>>()
.expect("Failed to extract Foo from PyE");
match f {
Foo::StructVar { test } => assert_eq!(test.to_string_lossy(), "foo"),
_ => panic!("Expected extracting Foo::StructVar, got {:?}", f),
}
let int = 1i32.into_pyobject(py).unwrap();
let f = int
.extract::<Foo<'_>>()
.expect("Failed to extract Foo from int");
match f {
Foo::TransparentTuple(test) => assert_eq!(test, 1),
_ => panic!("Expected extracting Foo::TransparentTuple, got {:?}", f),
}
let none = py.None();
let f = none
.extract::<Foo<'_>>(py)
.expect("Failed to extract Foo from int");
match f {
Foo::TransparentStructVar { a } => assert!(a.is_none()),
_ => panic!("Expected extracting Foo::TransparentStructVar, got {:?}", f),
}
let pybool = PyBool { bla: true }.into_pyobject(py).unwrap();
let f = pybool
.extract::<Foo<'_>>()
.expect("Failed to extract Foo from PyBool");
match f {
Foo::StructVarGetAttrArg { a } => assert!(a),
_ => panic!("Expected extracting Foo::StructVarGetAttrArg, got {:?}", f),
}
let dict = PyDict::new(py);
dict.set_item("a", "test").expect("Failed to set item");
let f = dict
.extract::<Foo<'_>>()
.expect("Failed to extract Foo from dict");
match f {
Foo::StructWithGetItem { a } => assert_eq!(a, "test"),
_ => panic!("Expected extracting Foo::StructWithGetItem, got {:?}", f),
}
let dict = PyDict::new(py);
dict.set_item("foo", "test").expect("Failed to set item");
let f = dict
.extract::<Foo<'_>>()
.expect("Failed to extract Foo from dict");
match f {
Foo::StructWithGetItemArg { a } => assert_eq!(a, "test"),
_ => panic!("Expected extracting Foo::StructWithGetItemArg, got {:?}", f),
}
});
}
#[test]
fn test_enum_error() {
Python::with_gil(|py| {
let dict = PyDict::new(py);
let err = dict.extract::<Foo<'_>>().unwrap_err();
assert_eq!(
err.to_string(),
"\
TypeError: failed to extract enum Foo ('TupleVar | StructVar | TransparentTuple | TransparentStructVar | StructVarGetAttrArg | StructWithGetItem | StructWithGetItemArg')
- variant TupleVar (TupleVar): TypeError: 'dict' object cannot be converted to 'PyTuple'
- variant StructVar (StructVar): AttributeError: 'dict' object has no attribute 'test'
- variant TransparentTuple (TransparentTuple): TypeError: failed to extract field Foo::TransparentTuple.0, caused by TypeError: 'dict' object cannot be interpreted as an integer
- variant TransparentStructVar (TransparentStructVar): TypeError: failed to extract field Foo::TransparentStructVar.a, caused by TypeError: 'dict' object cannot be converted to 'PyString'
- variant StructVarGetAttrArg (StructVarGetAttrArg): AttributeError: 'dict' object has no attribute 'bla'
- variant StructWithGetItem (StructWithGetItem): KeyError: 'a'
- variant StructWithGetItemArg (StructWithGetItemArg): KeyError: 'foo'"
);
let tup = PyTuple::empty(py);
let err = tup.extract::<Foo<'_>>().unwrap_err();
assert_eq!(
err.to_string(),
"\
TypeError: failed to extract enum Foo ('TupleVar | StructVar | TransparentTuple | TransparentStructVar | StructVarGetAttrArg | StructWithGetItem | StructWithGetItemArg')
- variant TupleVar (TupleVar): ValueError: expected tuple of length 2, but got tuple of length 0
- variant StructVar (StructVar): AttributeError: 'tuple' object has no attribute 'test'
- variant TransparentTuple (TransparentTuple): TypeError: failed to extract field Foo::TransparentTuple.0, caused by TypeError: 'tuple' object cannot be interpreted as an integer
- variant TransparentStructVar (TransparentStructVar): TypeError: failed to extract field Foo::TransparentStructVar.a, caused by TypeError: 'tuple' object cannot be converted to 'PyString'
- variant StructVarGetAttrArg (StructVarGetAttrArg): AttributeError: 'tuple' object has no attribute 'bla'
- variant StructWithGetItem (StructWithGetItem): TypeError: tuple indices must be integers or slices, not str
- variant StructWithGetItemArg (StructWithGetItemArg): TypeError: tuple indices must be integers or slices, not str"
);
});
}
#[derive(Debug, FromPyObject)]
enum EnumWithCatchAll<'py> {
#[allow(dead_code)]
#[pyo3(transparent)]
Foo(Foo<'py>),
#[pyo3(transparent)]
CatchAll(Bound<'py, PyAny>),
}
#[test]
fn test_enum_catch_all() {
Python::with_gil(|py| {
let dict = PyDict::new(py);
let f = dict
.extract::<EnumWithCatchAll<'_>>()
.expect("Failed to extract EnumWithCatchAll from dict");
match f {
EnumWithCatchAll::CatchAll(any) => {
let d = any.extract::<Bound<'_, PyDict>>().expect("Expected pydict");
assert!(d.is_empty());
}
_ => panic!(
"Expected extracting EnumWithCatchAll::CatchAll, got {:?}",
f
),
}
});
}
#[derive(Debug, FromPyObject)]
pub enum Bar {
#[pyo3(annotation = "str")]
A(String),
#[pyo3(annotation = "uint")]
B(usize),
#[pyo3(annotation = "int", transparent)]
C(isize),
}
#[test]
fn test_err_rename() {
Python::with_gil(|py| {
let dict = PyDict::new(py);
let f = dict.extract::<Bar>();
assert!(f.is_err());
assert_eq!(
f.unwrap_err().to_string(),
"\
TypeError: failed to extract enum Bar ('str | uint | int')
- variant A (str): TypeError: failed to extract field Bar::A.0, caused by TypeError: 'dict' object cannot be converted to 'PyString'
- variant B (uint): TypeError: failed to extract field Bar::B.0, caused by TypeError: 'dict' object cannot be interpreted as an integer
- variant C (int): TypeError: failed to extract field Bar::C.0, caused by TypeError: 'dict' object cannot be interpreted as an integer"
);
});
}
#[derive(Debug, FromPyObject)]
pub struct Zap {
#[pyo3(item)]
name: String,
#[pyo3(from_py_with = "Bound::<'_, PyAny>::len", item("my_object"))]
some_object_length: usize,
}
#[test]
fn test_from_py_with() {
Python::with_gil(|py| {
let py_zap = py
.eval(
pyo3_ffi::c_str!(r#"{"name": "whatever", "my_object": [1, 2, 3]}"#),
None,
None,
)
.expect("failed to create dict");
let zap = py_zap.extract::<Zap>().unwrap();
assert_eq!(zap.name, "whatever");
assert_eq!(zap.some_object_length, 3usize);
});
}
#[derive(Debug, FromPyObject)]
pub struct ZapTuple(
String,
#[pyo3(from_py_with = "Bound::<'_, PyAny>::len")] usize,
);
#[test]
fn test_from_py_with_tuple_struct() {
Python::with_gil(|py| {
let py_zap = py
.eval(pyo3_ffi::c_str!(r#"("whatever", [1, 2, 3])"#), None, None)
.expect("failed to create tuple");
let zap = py_zap.extract::<ZapTuple>().unwrap();
assert_eq!(zap.0, "whatever");
assert_eq!(zap.1, 3usize);
});
}
#[test]
fn test_from_py_with_tuple_struct_error() {
Python::with_gil(|py| {
let py_zap = py
.eval(
pyo3_ffi::c_str!(r#"("whatever", [1, 2, 3], "third")"#),
None,
None,
)
.expect("failed to create tuple");
let f = py_zap.extract::<ZapTuple>();
assert!(f.is_err());
assert_eq!(
f.unwrap_err().to_string(),
"ValueError: expected tuple of length 2, but got tuple of length 3"
);
});
}
#[derive(Debug, FromPyObject, PartialEq, Eq)]
pub enum ZapEnum {
Zip(#[pyo3(from_py_with = "Bound::<'_, PyAny>::len")] usize),
Zap(
String,
#[pyo3(from_py_with = "Bound::<'_, PyAny>::len")] usize,
),
}
#[test]
fn test_from_py_with_enum() {
Python::with_gil(|py| {
let py_zap = py
.eval(pyo3_ffi::c_str!(r#"("whatever", [1, 2, 3])"#), None, None)
.expect("failed to create tuple");
let zap = py_zap.extract::<ZapEnum>().unwrap();
let expected_zap = ZapEnum::Zip(2);
assert_eq!(zap, expected_zap);
});
}
#[derive(Debug, FromPyObject, PartialEq, Eq)]
#[pyo3(transparent)]
pub struct TransparentFromPyWith {
#[pyo3(from_py_with = "Bound::<'_, PyAny>::len")]
len: usize,
}
#[test]
fn test_transparent_from_py_with() {
Python::with_gil(|py| {
let result = PyList::new(py, [1, 2, 3])
.unwrap()
.extract::<TransparentFromPyWith>()
.unwrap();
let expected = TransparentFromPyWith { len: 3 };
assert_eq!(result, expected);
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_mapping.rs | #![cfg(feature = "macros")]
use std::collections::HashMap;
use pyo3::exceptions::PyKeyError;
use pyo3::prelude::*;
use pyo3::py_run;
use pyo3::types::IntoPyDict;
use pyo3::types::PyList;
use pyo3::types::PyMapping;
use pyo3::types::PySequence;
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass(mapping)]
struct Mapping {
index: HashMap<String, usize>,
}
#[pymethods]
impl Mapping {
#[new]
#[pyo3(signature=(elements=None))]
fn new(elements: Option<&Bound<'_, PyList>>) -> PyResult<Self> {
if let Some(pylist) = elements {
let mut elems = HashMap::with_capacity(pylist.len());
for (i, pyelem) in pylist.into_iter().enumerate() {
let elem = pyelem.extract()?;
elems.insert(elem, i);
}
Ok(Self { index: elems })
} else {
Ok(Self {
index: HashMap::new(),
})
}
}
fn __len__(&self) -> usize {
self.index.len()
}
fn __getitem__(&self, query: String) -> PyResult<usize> {
self.index
.get(&query)
.copied()
.ok_or_else(|| PyKeyError::new_err("unknown key"))
}
fn __setitem__(&mut self, key: String, value: usize) {
self.index.insert(key, value);
}
fn __delitem__(&mut self, key: String) -> PyResult<()> {
if self.index.remove(&key).is_none() {
Err(PyKeyError::new_err("unknown key"))
} else {
Ok(())
}
}
#[pyo3(signature=(key, default=None))]
fn get(
&self,
py: Python<'_>,
key: &str,
default: Option<PyObject>,
) -> PyResult<Option<PyObject>> {
match self.index.get(key) {
Some(value) => Ok(Some(value.into_pyobject(py)?.into_any().unbind())),
None => Ok(default),
}
}
}
/// Return a dict with `m = Mapping(['1', '2', '3'])`.
fn map_dict(py: Python<'_>) -> Bound<'_, pyo3::types::PyDict> {
let d = [("Mapping", py.get_type::<Mapping>())]
.into_py_dict(py)
.unwrap();
py_run!(py, *d, "m = Mapping(['1', '2', '3'])");
d
}
#[test]
fn test_getitem() {
Python::with_gil(|py| {
let d = map_dict(py);
py_assert!(py, *d, "m['1'] == 0");
py_assert!(py, *d, "m['2'] == 1");
py_assert!(py, *d, "m['3'] == 2");
py_expect_exception!(py, *d, "print(m['4'])", PyKeyError);
});
}
#[test]
fn test_setitem() {
Python::with_gil(|py| {
let d = map_dict(py);
py_run!(py, *d, "m['1'] = 4; assert m['1'] == 4");
py_run!(py, *d, "m['0'] = 0; assert m['0'] == 0");
py_assert!(py, *d, "len(m) == 4");
py_expect_exception!(py, *d, "m[0] = 'hello'", PyTypeError);
py_expect_exception!(py, *d, "m[0] = -1", PyTypeError);
});
}
#[test]
fn test_delitem() {
Python::with_gil(|py| {
let d = map_dict(py);
py_run!(
py,
*d,
"del m['1']; assert len(m) == 2 and m['2'] == 1 and m['3'] == 2"
);
py_expect_exception!(py, *d, "del m[-1]", PyTypeError);
py_expect_exception!(py, *d, "del m['4']", PyKeyError);
});
}
#[test]
fn mapping_is_not_sequence() {
Python::with_gil(|py| {
let mut index = HashMap::new();
index.insert("Foo".into(), 1);
index.insert("Bar".into(), 2);
let m = Py::new(py, Mapping { index }).unwrap();
PyMapping::register::<Mapping>(py).unwrap();
assert!(m.bind(py).downcast::<PyMapping>().is_ok());
assert!(m.bind(py).downcast::<PySequence>().is_err());
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_macro_docs.rs | #![cfg(feature = "macros")]
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
#[macro_use]
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
/// The MacroDocs class.
#[doc = concat!("Some macro ", "class ", "docs.")]
/// A very interesting type!
struct MacroDocs {}
#[pymethods]
impl MacroDocs {
#[doc = concat!("A macro ", "example.")]
/// With mixed doc types.
fn macro_doc(&self) {}
}
#[test]
fn meth_doc() {
Python::with_gil(|py| {
let d = [("C", py.get_type::<MacroDocs>())]
.into_py_dict(py)
.unwrap();
py_assert!(
py,
*d,
"C.__doc__ == 'The MacroDocs class.\\nSome macro class docs.\\nA very interesting type!'"
);
py_assert!(
py,
*d,
"C.macro_doc.__doc__ == 'A macro example.\\nWith mixed doc types.'"
);
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_class_new.rs | #![cfg(feature = "macros")]
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::sync::GILOnceCell;
use pyo3::types::IntoPyDict;
#[pyclass]
struct EmptyClassWithNew {}
#[pymethods]
impl EmptyClassWithNew {
#[new]
fn new() -> EmptyClassWithNew {
EmptyClassWithNew {}
}
}
#[test]
fn empty_class_with_new() {
Python::with_gil(|py| {
let typeobj = py.get_type::<EmptyClassWithNew>();
assert!(typeobj
.call((), None)
.unwrap()
.downcast::<EmptyClassWithNew>()
.is_ok());
// Calling with arbitrary args or kwargs is not ok
assert!(typeobj.call(("some", "args"), None).is_err());
assert!(typeobj
.call((), Some(&[("some", "kwarg")].into_py_dict(py).unwrap()))
.is_err());
});
}
#[pyclass]
struct UnitClassWithNew;
#[pymethods]
impl UnitClassWithNew {
#[new]
fn new() -> Self {
Self
}
}
#[test]
fn unit_class_with_new() {
Python::with_gil(|py| {
let typeobj = py.get_type::<UnitClassWithNew>();
assert!(typeobj
.call((), None)
.unwrap()
.downcast::<UnitClassWithNew>()
.is_ok());
});
}
#[pyclass]
struct TupleClassWithNew(i32);
#[pymethods]
impl TupleClassWithNew {
#[new]
fn new(arg: i32) -> Self {
Self(arg)
}
}
#[test]
fn tuple_class_with_new() {
Python::with_gil(|py| {
let typeobj = py.get_type::<TupleClassWithNew>();
let wrp = typeobj.call((42,), None).unwrap();
let obj = wrp.downcast::<TupleClassWithNew>().unwrap();
let obj_ref = obj.borrow();
assert_eq!(obj_ref.0, 42);
});
}
#[pyclass]
#[derive(Debug)]
struct NewWithOneArg {
data: i32,
}
#[pymethods]
impl NewWithOneArg {
#[new]
fn new(arg: i32) -> NewWithOneArg {
NewWithOneArg { data: arg }
}
}
#[test]
fn new_with_one_arg() {
Python::with_gil(|py| {
let typeobj = py.get_type::<NewWithOneArg>();
let wrp = typeobj.call((42,), None).unwrap();
let obj = wrp.downcast::<NewWithOneArg>().unwrap();
let obj_ref = obj.borrow();
assert_eq!(obj_ref.data, 42);
});
}
#[pyclass]
struct NewWithTwoArgs {
data1: i32,
data2: i32,
}
#[pymethods]
impl NewWithTwoArgs {
#[new]
fn new(arg1: i32, arg2: i32) -> Self {
NewWithTwoArgs {
data1: arg1,
data2: arg2,
}
}
}
#[test]
fn new_with_two_args() {
Python::with_gil(|py| {
let typeobj = py.get_type::<NewWithTwoArgs>();
let wrp = typeobj
.call((10, 20), None)
.map_err(|e| e.display(py))
.unwrap();
let obj = wrp.downcast::<NewWithTwoArgs>().unwrap();
let obj_ref = obj.borrow();
assert_eq!(obj_ref.data1, 10);
assert_eq!(obj_ref.data2, 20);
});
}
#[pyclass(subclass)]
struct SuperClass {
#[pyo3(get)]
from_rust: bool,
}
#[pymethods]
impl SuperClass {
#[new]
fn new() -> Self {
SuperClass { from_rust: true }
}
}
/// Checks that `subclass.__new__` works correctly.
/// See https://github.com/PyO3/pyo3/issues/947 for the corresponding bug.
#[test]
fn subclass_new() {
Python::with_gil(|py| {
let super_cls = py.get_type::<SuperClass>();
let source = pyo3_ffi::c_str!(pyo3::indoc::indoc!(
r#"
class Class(SuperClass):
def __new__(cls):
return super().__new__(cls) # This should return an instance of Class
@property
def from_rust(self):
return False
c = Class()
assert c.from_rust is False
"#
));
let globals = PyModule::import(py, "__main__").unwrap().dict();
globals.set_item("SuperClass", super_cls).unwrap();
py.run(source, Some(&globals), None)
.map_err(|e| e.display(py))
.unwrap();
});
}
#[pyclass]
#[derive(Debug)]
struct NewWithCustomError {}
struct CustomError;
impl From<CustomError> for PyErr {
fn from(_error: CustomError) -> PyErr {
PyValueError::new_err("custom error")
}
}
#[pymethods]
impl NewWithCustomError {
#[new]
fn new() -> Result<NewWithCustomError, CustomError> {
Err(CustomError)
}
}
#[test]
fn new_with_custom_error() {
Python::with_gil(|py| {
let typeobj = py.get_type::<NewWithCustomError>();
let err = typeobj.call0().unwrap_err();
assert_eq!(err.to_string(), "ValueError: custom error");
});
}
#[pyclass]
struct NewExisting {
#[pyo3(get)]
num: usize,
}
#[pymethods]
impl NewExisting {
#[new]
fn new(py: pyo3::Python<'_>, val: usize) -> pyo3::Py<NewExisting> {
static PRE_BUILT: GILOnceCell<[pyo3::Py<NewExisting>; 2]> = GILOnceCell::new();
let existing = PRE_BUILT.get_or_init(py, || {
[
pyo3::Py::new(py, NewExisting { num: 0 }).unwrap(),
pyo3::Py::new(py, NewExisting { num: 1 }).unwrap(),
]
});
if val < existing.len() {
return existing[val].clone_ref(py);
}
pyo3::Py::new(py, NewExisting { num: val }).unwrap()
}
}
#[test]
fn test_new_existing() {
Python::with_gil(|py| {
let typeobj = py.get_type::<NewExisting>();
let obj1 = typeobj.call1((0,)).unwrap();
let obj2 = typeobj.call1((0,)).unwrap();
let obj3 = typeobj.call1((1,)).unwrap();
let obj4 = typeobj.call1((1,)).unwrap();
let obj5 = typeobj.call1((2,)).unwrap();
let obj6 = typeobj.call1((2,)).unwrap();
assert!(obj1.getattr("num").unwrap().extract::<u32>().unwrap() == 0);
assert!(obj2.getattr("num").unwrap().extract::<u32>().unwrap() == 0);
assert!(obj3.getattr("num").unwrap().extract::<u32>().unwrap() == 1);
assert!(obj4.getattr("num").unwrap().extract::<u32>().unwrap() == 1);
assert!(obj5.getattr("num").unwrap().extract::<u32>().unwrap() == 2);
assert!(obj6.getattr("num").unwrap().extract::<u32>().unwrap() == 2);
assert!(obj1.is(&obj2));
assert!(obj3.is(&obj4));
assert!(!obj1.is(&obj3));
assert!(!obj1.is(&obj5));
assert!(!obj5.is(&obj6));
});
}
#[pyclass]
struct NewReturnsPy;
#[pymethods]
impl NewReturnsPy {
#[new]
fn new(py: Python<'_>) -> PyResult<Py<NewReturnsPy>> {
Py::new(py, NewReturnsPy)
}
}
#[test]
fn test_new_returns_py() {
Python::with_gil(|py| {
let type_ = py.get_type::<NewReturnsPy>();
let obj = type_.call0().unwrap();
assert!(obj.is_exact_instance_of::<NewReturnsPy>());
})
}
#[pyclass]
struct NewReturnsBound;
#[pymethods]
impl NewReturnsBound {
#[new]
fn new(py: Python<'_>) -> PyResult<Bound<'_, NewReturnsBound>> {
Bound::new(py, NewReturnsBound)
}
}
#[test]
fn test_new_returns_bound() {
Python::with_gil(|py| {
let type_ = py.get_type::<NewReturnsBound>();
let obj = type_.call0().unwrap();
assert!(obj.is_exact_instance_of::<NewReturnsBound>());
})
}
#[pyo3::pyclass]
struct NewClassMethod {
#[pyo3(get)]
cls: pyo3::PyObject,
}
#[pyo3::pymethods]
impl NewClassMethod {
#[new]
#[classmethod]
fn new(cls: &pyo3::Bound<'_, pyo3::types::PyType>) -> Self {
Self {
cls: cls.clone().into_any().unbind(),
}
}
}
#[test]
fn test_new_class_method() {
pyo3::Python::with_gil(|py| {
let cls = py.get_type::<NewClassMethod>();
pyo3::py_run!(py, cls, "assert cls().cls is cls");
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_variable_arguments.rs | #![cfg(feature = "macros")]
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyTuple};
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
struct MyClass {}
#[pymethods]
impl MyClass {
#[staticmethod]
#[pyo3(signature = (*args))]
fn test_args(args: Bound<'_, PyTuple>) -> Bound<'_, PyTuple> {
args
}
#[staticmethod]
#[pyo3(signature = (**kwargs))]
fn test_kwargs(kwargs: Option<Bound<'_, PyDict>>) -> Option<Bound<'_, PyDict>> {
kwargs
}
}
#[test]
fn variable_args() {
Python::with_gil(|py| {
let my_obj = py.get_type::<MyClass>();
py_assert!(py, my_obj, "my_obj.test_args() == ()");
py_assert!(py, my_obj, "my_obj.test_args(1) == (1,)");
py_assert!(py, my_obj, "my_obj.test_args(1, 2) == (1, 2)");
});
}
#[test]
fn variable_kwargs() {
Python::with_gil(|py| {
let my_obj = py.get_type::<MyClass>();
py_assert!(py, my_obj, "my_obj.test_kwargs() == None");
py_assert!(py, my_obj, "my_obj.test_kwargs(test=1) == {'test': 1}");
py_assert!(
py,
my_obj,
"my_obj.test_kwargs(test1=1, test2=2) == {'test1':1, 'test2':2}"
);
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_methods.rs | #![cfg(feature = "macros")]
use pyo3::prelude::*;
use pyo3::py_run;
use pyo3::types::PySequence;
use pyo3::types::{IntoPyDict, PyDict, PyList, PySet, PyString, PyTuple, PyType};
use pyo3::BoundObject;
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
struct InstanceMethod {
member: i32,
}
#[pymethods]
impl InstanceMethod {
/// Test method
fn method(&self) -> i32 {
self.member
}
// Checks that &Self works
fn add_other(&self, other: &Self) -> i32 {
self.member + other.member
}
}
#[test]
fn instance_method() {
Python::with_gil(|py| {
let obj = Bound::new(py, InstanceMethod { member: 42 }).unwrap();
let obj_ref = obj.borrow();
assert_eq!(obj_ref.method(), 42);
py_assert!(py, obj, "obj.method() == 42");
py_assert!(py, obj, "obj.add_other(obj) == 84");
py_assert!(py, obj, "obj.method.__doc__ == 'Test method'");
});
}
#[pyclass]
struct InstanceMethodWithArgs {
member: i32,
}
#[pymethods]
impl InstanceMethodWithArgs {
fn method(&self, multiplier: i32) -> i32 {
self.member * multiplier
}
}
#[test]
fn instance_method_with_args() {
Python::with_gil(|py| {
let obj = Bound::new(py, InstanceMethodWithArgs { member: 7 }).unwrap();
let obj_ref = obj.borrow();
assert_eq!(obj_ref.method(6), 42);
py_assert!(py, obj, "obj.method(3) == 21");
py_assert!(py, obj, "obj.method(multiplier=6) == 42");
});
}
#[pyclass]
struct ClassMethod {}
#[pymethods]
impl ClassMethod {
#[new]
fn new() -> Self {
ClassMethod {}
}
#[classmethod]
/// Test class method.
fn method(cls: &Bound<'_, PyType>) -> PyResult<String> {
Ok(format!("{}.method()!", cls.qualname()?))
}
#[classmethod]
fn method_owned(cls: Py<PyType>, py: Python<'_>) -> PyResult<String> {
Ok(format!("{}.method_owned()!", cls.bind(py).qualname()?))
}
}
#[test]
fn class_method() {
Python::with_gil(|py| {
let d = [("C", py.get_type::<ClassMethod>())]
.into_py_dict(py)
.unwrap();
py_assert!(py, *d, "C.method() == 'ClassMethod.method()!'");
py_assert!(py, *d, "C().method() == 'ClassMethod.method()!'");
py_assert!(
py,
*d,
"C().method_owned() == 'ClassMethod.method_owned()!'"
);
py_assert!(py, *d, "C.method.__doc__ == 'Test class method.'");
py_assert!(py, *d, "C().method.__doc__ == 'Test class method.'");
});
}
#[pyclass]
struct ClassMethodWithArgs {}
#[pymethods]
impl ClassMethodWithArgs {
#[classmethod]
fn method(cls: &Bound<'_, PyType>, input: &Bound<'_, PyString>) -> PyResult<String> {
Ok(format!("{}.method({})", cls.qualname()?, input))
}
}
#[test]
fn class_method_with_args() {
Python::with_gil(|py| {
let d = [("C", py.get_type::<ClassMethodWithArgs>())]
.into_py_dict(py)
.unwrap();
py_assert!(
py,
*d,
"C.method('abc') == 'ClassMethodWithArgs.method(abc)'"
);
});
}
#[pyclass]
struct StaticMethod {}
#[pymethods]
impl StaticMethod {
#[new]
fn new() -> Self {
StaticMethod {}
}
#[staticmethod]
/// Test static method.
fn method(_py: Python<'_>) -> &'static str {
"StaticMethod.method()!"
}
}
#[test]
fn static_method() {
Python::with_gil(|py| {
assert_eq!(StaticMethod::method(py), "StaticMethod.method()!");
let d = [("C", py.get_type::<StaticMethod>())]
.into_py_dict(py)
.unwrap();
py_assert!(py, *d, "C.method() == 'StaticMethod.method()!'");
py_assert!(py, *d, "C().method() == 'StaticMethod.method()!'");
py_assert!(py, *d, "C.method.__doc__ == 'Test static method.'");
py_assert!(py, *d, "C().method.__doc__ == 'Test static method.'");
});
}
#[pyclass]
struct StaticMethodWithArgs {}
#[pymethods]
impl StaticMethodWithArgs {
#[staticmethod]
fn method(_py: Python<'_>, input: i32) -> String {
format!("0x{:x}", input)
}
}
#[test]
fn static_method_with_args() {
Python::with_gil(|py| {
assert_eq!(StaticMethodWithArgs::method(py, 1234), "0x4d2");
let d = [("C", py.get_type::<StaticMethodWithArgs>())]
.into_py_dict(py)
.unwrap();
py_assert!(py, *d, "C.method(1337) == '0x539'");
});
}
#[pyclass]
struct MethSignature {}
#[pymethods]
impl MethSignature {
#[pyo3(signature = (test = None))]
fn get_optional(&self, test: Option<i32>) -> i32 {
test.unwrap_or(10)
}
#[pyo3(signature = (test = None))]
fn get_optional2(&self, test: Option<i32>) -> Option<i32> {
test
}
#[pyo3(signature=(_t1 = None, t2 = None, _t3 = None))]
fn get_optional_positional(
&self,
_t1: Option<i32>,
t2: Option<i32>,
_t3: Option<i32>,
) -> Option<i32> {
t2
}
#[pyo3(signature = (test = 10))]
fn get_default(&self, test: i32) -> i32 {
test
}
#[pyo3(signature = (*, test = 10))]
fn get_kwarg(&self, test: i32) -> i32 {
test
}
#[pyo3(signature = (*args, **kwargs))]
fn get_kwargs<'py>(
&self,
py: Python<'py>,
args: &Bound<'py, PyTuple>,
kwargs: Option<&Bound<'py, PyDict>>,
) -> PyResult<Bound<'py, PyAny>> {
[
args.as_any().clone(),
kwargs.into_pyobject(py)?.into_any().into_bound(),
]
.into_pyobject(py)
}
#[pyo3(signature = (a, *args, **kwargs))]
fn get_pos_arg_kw<'py>(
&self,
py: Python<'py>,
a: i32,
args: &Bound<'py, PyTuple>,
kwargs: Option<&Bound<'py, PyDict>>,
) -> PyResult<Bound<'py, PyAny>> {
[
a.into_pyobject(py)?.into_any().into_bound(),
args.as_any().clone(),
kwargs.into_pyobject(py)?.into_any().into_bound(),
]
.into_pyobject(py)
}
#[pyo3(signature = (a, b, /))]
fn get_pos_only(&self, a: i32, b: i32) -> i32 {
a + b
}
#[pyo3(signature = (a, /, b))]
fn get_pos_only_and_pos(&self, a: i32, b: i32) -> i32 {
a + b
}
#[pyo3(signature = (a, /, b, c = 5))]
fn get_pos_only_and_pos_and_kw(&self, a: i32, b: i32, c: i32) -> i32 {
a + b + c
}
#[pyo3(signature = (a, /, *, b))]
fn get_pos_only_and_kw_only(&self, a: i32, b: i32) -> i32 {
a + b
}
#[pyo3(signature = (a, /, *, b = 3))]
fn get_pos_only_and_kw_only_with_default(&self, a: i32, b: i32) -> i32 {
a + b
}
#[pyo3(signature = (a, /, b, *, c, d = 5))]
fn get_all_arg_types_together(&self, a: i32, b: i32, c: i32, d: i32) -> i32 {
a + b + c + d
}
#[pyo3(signature = (a, /, *args))]
fn get_pos_only_with_varargs(&self, a: i32, args: Vec<i32>) -> i32 {
a + args.iter().sum::<i32>()
}
#[pyo3(signature = (a, /, **kwargs))]
fn get_pos_only_with_kwargs(
&self,
py: Python<'_>,
a: i32,
kwargs: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyObject> {
[
a.into_pyobject(py)?.into_any().into_bound(),
kwargs.into_pyobject(py)?.into_any().into_bound(),
]
.into_pyobject(py)
.map(BoundObject::unbind)
}
#[pyo3(signature = (a=0, /, **kwargs))]
fn get_optional_pos_only_with_kwargs(
&self,
py: Python<'_>,
a: i32,
kwargs: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyObject> {
[
a.into_pyobject(py)?.into_any().into_bound(),
kwargs.into_pyobject(py)?.into_any().into_bound(),
]
.into_pyobject(py)
.map(BoundObject::unbind)
}
#[pyo3(signature = (*, a = 2, b = 3))]
fn get_kwargs_only_with_defaults(&self, a: i32, b: i32) -> i32 {
a + b
}
#[pyo3(signature = (*, a, b))]
fn get_kwargs_only(&self, a: i32, b: i32) -> i32 {
a + b
}
#[pyo3(signature = (*, a = 1, b))]
fn get_kwargs_only_with_some_default(&self, a: i32, b: i32) -> i32 {
a + b
}
#[pyo3(signature = (*args, a))]
fn get_args_and_required_keyword(
&self,
py: Python<'_>,
args: &Bound<'_, PyTuple>,
a: i32,
) -> PyResult<PyObject> {
(args, a)
.into_pyobject(py)
.map(BoundObject::into_any)
.map(BoundObject::unbind)
}
#[pyo3(signature = (a, b = 2, *, c = 3))]
fn get_pos_arg_kw_sep1(&self, a: i32, b: i32, c: i32) -> i32 {
a + b + c
}
#[pyo3(signature = (a, *, b = 2, c = 3))]
fn get_pos_arg_kw_sep2(&self, a: i32, b: i32, c: i32) -> i32 {
a + b + c
}
#[pyo3(signature = (a, **kwargs))]
fn get_pos_kw(
&self,
py: Python<'_>,
a: i32,
kwargs: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyObject> {
[
a.into_pyobject(py)?.into_any().into_bound(),
kwargs.into_pyobject(py)?.into_any().into_bound(),
]
.into_pyobject(py)
.map(BoundObject::unbind)
}
// "args" can be anything that can be extracted from PyTuple
#[pyo3(signature = (*args))]
fn args_as_vec(&self, args: Vec<i32>) -> i32 {
args.iter().sum()
}
}
#[test]
fn meth_signature() {
Python::with_gil(|py| {
let inst = Py::new(py, MethSignature {}).unwrap();
py_run!(py, inst, "assert inst.get_optional() == 10");
py_run!(py, inst, "assert inst.get_optional(100) == 100");
py_run!(py, inst, "assert inst.get_optional2() == None");
py_run!(py, inst, "assert inst.get_optional2(100) == 100");
py_run!(
py,
inst,
"assert inst.get_optional_positional(1, 2, 3) == 2"
);
py_run!(py, inst, "assert inst.get_optional_positional(1) == None");
py_run!(py, inst, "assert inst.get_default() == 10");
py_run!(py, inst, "assert inst.get_default(100) == 100");
py_run!(py, inst, "assert inst.get_kwarg() == 10");
py_expect_exception!(py, inst, "inst.get_kwarg(100)", PyTypeError);
py_run!(py, inst, "assert inst.get_kwarg(test=100) == 100");
py_run!(py, inst, "assert inst.get_kwargs() == [(), None]");
py_run!(py, inst, "assert inst.get_kwargs(1,2,3) == [(1,2,3), None]");
py_run!(
py,
inst,
"assert inst.get_kwargs(t=1,n=2) == [(), {'t': 1, 'n': 2}]"
);
py_run!(
py,
inst,
"assert inst.get_kwargs(1,2,3,t=1,n=2) == [(1,2,3), {'t': 1, 'n': 2}]"
);
py_run!(py, inst, "assert inst.get_pos_arg_kw(1) == [1, (), None]");
py_run!(
py,
inst,
"assert inst.get_pos_arg_kw(1, 2, 3) == [1, (2, 3), None]"
);
py_run!(
py,
inst,
"assert inst.get_pos_arg_kw(1, b=2) == [1, (), {'b': 2}]"
);
py_run!(py, inst, "assert inst.get_pos_arg_kw(a=1) == [1, (), None]");
py_expect_exception!(py, inst, "inst.get_pos_arg_kw()", PyTypeError);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw(1, a=1)", PyTypeError);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw(b=2)", PyTypeError);
py_run!(py, inst, "assert inst.get_pos_only(10, 11) == 21");
py_expect_exception!(py, inst, "inst.get_pos_only(10, b = 11)", PyTypeError);
py_expect_exception!(py, inst, "inst.get_pos_only(a = 10, b = 11)", PyTypeError);
py_run!(py, inst, "assert inst.get_pos_only_and_pos(10, 11) == 21");
py_run!(
py,
inst,
"assert inst.get_pos_only_and_pos(10, b = 11) == 21"
);
py_expect_exception!(
py,
inst,
"inst.get_pos_only_and_pos(a = 10, b = 11)",
PyTypeError
);
py_run!(
py,
inst,
"assert inst.get_pos_only_and_pos_and_kw(10, 11) == 26"
);
py_run!(
py,
inst,
"assert inst.get_pos_only_and_pos_and_kw(10, b = 11) == 26"
);
py_run!(
py,
inst,
"assert inst.get_pos_only_and_pos_and_kw(10, 11, c = 0) == 21"
);
py_run!(
py,
inst,
"assert inst.get_pos_only_and_pos_and_kw(10, b = 11, c = 0) == 21"
);
py_expect_exception!(
py,
inst,
"inst.get_pos_only_and_pos_and_kw(a = 10, b = 11)",
PyTypeError
);
py_run!(
py,
inst,
"assert inst.get_pos_only_and_kw_only(10, b = 11) == 21"
);
py_expect_exception!(
py,
inst,
"inst.get_pos_only_and_kw_only(10, 11)",
PyTypeError
);
py_expect_exception!(
py,
inst,
"inst.get_pos_only_and_kw_only(a = 10, b = 11)",
PyTypeError
);
py_run!(
py,
inst,
"assert inst.get_pos_only_and_kw_only_with_default(10) == 13"
);
py_run!(
py,
inst,
"assert inst.get_pos_only_and_kw_only_with_default(10, b = 11) == 21"
);
py_expect_exception!(
py,
inst,
"inst.get_pos_only_and_kw_only_with_default(10, 11)",
PyTypeError
);
py_expect_exception!(
py,
inst,
"inst.get_pos_only_and_kw_only_with_default(a = 10, b = 11)",
PyTypeError
);
py_run!(
py,
inst,
"assert inst.get_all_arg_types_together(10, 10, c = 10) == 35"
);
py_run!(
py,
inst,
"assert inst.get_all_arg_types_together(10, 10, c = 10, d = 10) == 40"
);
py_run!(
py,
inst,
"assert inst.get_all_arg_types_together(10, b = 10, c = 10, d = 10) == 40"
);
py_expect_exception!(
py,
inst,
"inst.get_all_arg_types_together(10, 10, 10)",
PyTypeError
);
py_expect_exception!(
py,
inst,
"inst.get_all_arg_types_together(a = 10, b = 10, c = 10)",
PyTypeError
);
py_run!(py, inst, "assert inst.get_pos_only_with_varargs(10) == 10");
py_run!(
py,
inst,
"assert inst.get_pos_only_with_varargs(10, 10) == 20"
);
py_run!(
py,
inst,
"assert inst.get_pos_only_with_varargs(10, 10, 10, 10, 10) == 50"
);
py_expect_exception!(
py,
inst,
"inst.get_pos_only_with_varargs(a = 10)",
PyTypeError
);
py_run!(
py,
inst,
"assert inst.get_pos_only_with_kwargs(10) == [10, None]"
);
py_run!(
py,
inst,
"assert inst.get_pos_only_with_kwargs(10, b = 10) == [10, {'b': 10}]"
);
py_run!(
py,
inst,
"assert inst.get_pos_only_with_kwargs(10, b = 10, c = 10, d = 10, e = 10) == [10, {'b': 10, 'c': 10, 'd': 10, 'e': 10}]"
);
py_expect_exception!(
py,
inst,
"inst.get_pos_only_with_kwargs(a = 10)",
PyTypeError
);
py_expect_exception!(
py,
inst,
"inst.get_pos_only_with_kwargs(a = 10, b = 10)",
PyTypeError
);
py_run!(
py,
inst,
"assert inst.get_optional_pos_only_with_kwargs() == [0, None]"
);
py_run!(
py,
inst,
"assert inst.get_optional_pos_only_with_kwargs(10) == [10, None]"
);
py_run!(
py,
inst,
"assert inst.get_optional_pos_only_with_kwargs(a=10) == [0, {'a': 10}]"
);
py_run!(py, inst, "assert inst.get_kwargs_only_with_defaults() == 5");
py_run!(
py,
inst,
"assert inst.get_kwargs_only_with_defaults(a = 8) == 11"
);
py_run!(
py,
inst,
"assert inst.get_kwargs_only_with_defaults(b = 8) == 10"
);
py_run!(
py,
inst,
"assert inst.get_kwargs_only_with_defaults(a = 1, b = 1) == 2"
);
py_run!(
py,
inst,
"assert inst.get_kwargs_only_with_defaults(b = 1, a = 1) == 2"
);
py_run!(py, inst, "assert inst.get_kwargs_only(a = 1, b = 1) == 2");
py_run!(py, inst, "assert inst.get_kwargs_only(b = 1, a = 1) == 2");
py_run!(
py,
inst,
"assert inst.get_kwargs_only_with_some_default(a = 2, b = 1) == 3"
);
py_run!(
py,
inst,
"assert inst.get_kwargs_only_with_some_default(b = 1) == 2"
);
py_run!(
py,
inst,
"assert inst.get_kwargs_only_with_some_default(b = 1, a = 2) == 3"
);
py_expect_exception!(
py,
inst,
"inst.get_kwargs_only_with_some_default()",
PyTypeError
);
py_run!(
py,
inst,
"assert inst.get_args_and_required_keyword(1, 2, a=3) == ((1, 2), 3)"
);
py_run!(
py,
inst,
"assert inst.get_args_and_required_keyword(a=1) == ((), 1)"
);
py_expect_exception!(
py,
inst,
"inst.get_args_and_required_keyword()",
PyTypeError
);
py_run!(py, inst, "assert inst.get_pos_arg_kw_sep1(1) == 6");
py_run!(py, inst, "assert inst.get_pos_arg_kw_sep1(1, 2) == 6");
py_run!(
py,
inst,
"assert inst.get_pos_arg_kw_sep1(1, 2, c=13) == 16"
);
py_run!(
py,
inst,
"assert inst.get_pos_arg_kw_sep1(a=1, b=2, c=13) == 16"
);
py_run!(
py,
inst,
"assert inst.get_pos_arg_kw_sep1(b=2, c=13, a=1) == 16"
);
py_run!(
py,
inst,
"assert inst.get_pos_arg_kw_sep1(c=13, b=2, a=1) == 16"
);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw_sep1(1, 2, 3)", PyTypeError);
py_run!(py, inst, "assert inst.get_pos_arg_kw_sep2(1) == 6");
py_run!(
py,
inst,
"assert inst.get_pos_arg_kw_sep2(1, b=12, c=13) == 26"
);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw_sep2(1, 2)", PyTypeError);
py_run!(py, inst, "assert inst.get_pos_kw(1, b=2) == [1, {'b': 2}]");
py_expect_exception!(py, inst, "inst.get_pos_kw(1,2)", PyTypeError);
py_run!(py, inst, "assert inst.args_as_vec(1,2,3) == 6");
});
}
#[pyclass]
/// A class with "documentation".
struct MethDocs {
x: i32,
}
#[pymethods]
impl MethDocs {
/// A method with "documentation" as well.
fn method(&self) -> i32 {
0
}
#[getter]
/// `int`: a very "important" member of 'this' instance.
fn get_x(&self) -> i32 {
self.x
}
}
#[test]
fn meth_doc() {
Python::with_gil(|py| {
let d = [("C", py.get_type::<MethDocs>())].into_py_dict(py).unwrap();
py_assert!(py, *d, "C.__doc__ == 'A class with \"documentation\".'");
py_assert!(
py,
*d,
"C.method.__doc__ == 'A method with \"documentation\" as well.'"
);
py_assert!(
py,
*d,
"C.x.__doc__ == '`int`: a very \"important\" member of \\'this\\' instance.'"
);
});
}
#[pyclass]
struct MethodWithLifeTime {}
#[pymethods]
impl MethodWithLifeTime {
fn set_to_list<'py>(&self, set: &Bound<'py, PySet>) -> PyResult<Bound<'py, PyList>> {
let py = set.py();
let mut items = vec![];
for _ in 0..set.len() {
items.push(set.pop().unwrap());
}
let list = PyList::new(py, items)?;
list.sort()?;
Ok(list)
}
}
#[test]
fn method_with_lifetime() {
Python::with_gil(|py| {
let obj = Py::new(py, MethodWithLifeTime {}).unwrap();
py_run!(
py,
obj,
"assert obj.set_to_list(set((1, 2, 3))) == [1, 2, 3]"
);
});
}
#[pyclass]
struct MethodWithPyClassArg {
#[pyo3(get)]
value: i64,
}
#[pymethods]
impl MethodWithPyClassArg {
fn add(&self, other: &MethodWithPyClassArg) -> MethodWithPyClassArg {
MethodWithPyClassArg {
value: self.value + other.value,
}
}
fn add_pyref(&self, other: PyRef<'_, MethodWithPyClassArg>) -> MethodWithPyClassArg {
MethodWithPyClassArg {
value: self.value + other.value,
}
}
fn inplace_add(&self, other: &mut MethodWithPyClassArg) {
other.value += self.value;
}
fn inplace_add_pyref(&self, mut other: PyRefMut<'_, MethodWithPyClassArg>) {
other.value += self.value;
}
#[pyo3(signature=(other = None))]
fn optional_add(&self, other: Option<&MethodWithPyClassArg>) -> MethodWithPyClassArg {
MethodWithPyClassArg {
value: self.value + other.map(|o| o.value).unwrap_or(10),
}
}
#[pyo3(signature=(other = None))]
fn optional_inplace_add(&self, other: Option<&mut MethodWithPyClassArg>) {
if let Some(other) = other {
other.value += self.value;
}
}
}
#[test]
fn method_with_pyclassarg() {
Python::with_gil(|py| {
let obj1 = Py::new(py, MethodWithPyClassArg { value: 10 }).unwrap();
let obj2 = Py::new(py, MethodWithPyClassArg { value: 10 }).unwrap();
let d = [("obj1", obj1), ("obj2", obj2)].into_py_dict(py).unwrap();
py_run!(py, *d, "obj = obj1.add(obj2); assert obj.value == 20");
py_run!(py, *d, "obj = obj1.add_pyref(obj2); assert obj.value == 20");
py_run!(py, *d, "obj = obj1.optional_add(); assert obj.value == 20");
py_run!(
py,
*d,
"obj = obj1.optional_add(obj2); assert obj.value == 20"
);
py_run!(py, *d, "obj1.inplace_add(obj2); assert obj.value == 20");
py_run!(
py,
*d,
"obj1.inplace_add_pyref(obj2); assert obj2.value == 30"
);
py_run!(
py,
*d,
"obj1.optional_inplace_add(); assert obj2.value == 30"
);
py_run!(
py,
*d,
"obj1.optional_inplace_add(obj2); assert obj2.value == 40"
);
});
}
#[pyclass]
#[cfg(unix)]
struct CfgStruct {}
#[pyclass]
#[cfg(not(unix))]
struct CfgStruct {}
#[pymethods]
#[cfg(unix)]
impl CfgStruct {
fn unix_method(&self) -> &str {
"unix"
}
#[cfg(not(unix))]
fn never_compiled_method(&self) {}
}
#[pymethods]
#[cfg(not(unix))]
impl CfgStruct {
fn not_unix_method(&self) -> &str {
"not unix"
}
#[cfg(unix)]
fn never_compiled_method(&self) {}
}
#[test]
fn test_cfg_attrs() {
Python::with_gil(|py| {
let inst = Py::new(py, CfgStruct {}).unwrap();
#[cfg(unix)]
{
py_assert!(py, inst, "inst.unix_method() == 'unix'");
py_assert!(py, inst, "not hasattr(inst, 'not_unix_method')");
}
#[cfg(not(unix))]
{
py_assert!(py, inst, "not hasattr(inst, 'unix_method')");
py_assert!(py, inst, "inst.not_unix_method() == 'not unix'");
}
py_assert!(py, inst, "not hasattr(inst, 'never_compiled_method')");
});
}
#[pyclass]
#[derive(Default)]
struct FromSequence {
#[pyo3(get)]
numbers: Vec<i64>,
}
#[pymethods]
impl FromSequence {
#[new]
#[pyo3(signature=(seq = None))]
fn new(seq: Option<&Bound<'_, PySequence>>) -> PyResult<Self> {
if let Some(seq) = seq {
Ok(FromSequence {
numbers: seq.as_ref().extract::<Vec<_>>()?,
})
} else {
Ok(FromSequence::default())
}
}
}
#[test]
fn test_from_sequence() {
Python::with_gil(|py| {
let typeobj = py.get_type::<FromSequence>();
py_assert!(py, typeobj, "typeobj(range(0, 4)).numbers == [0, 1, 2, 3]");
});
}
#[pyclass]
struct r#RawIdents {
#[pyo3(get, set)]
r#type: PyObject,
r#subtype: PyObject,
r#subsubtype: PyObject,
}
#[pymethods]
impl r#RawIdents {
#[new]
pub fn r#new(
r#_py: Python<'_>,
r#type: PyObject,
r#subtype: PyObject,
r#subsubtype: PyObject,
) -> Self {
Self {
r#type,
r#subtype,
r#subsubtype,
}
}
#[getter(r#subtype)]
pub fn r#get_subtype(&self, py: Python<'_>) -> PyObject {
self.r#subtype.clone_ref(py)
}
#[setter(r#subtype)]
pub fn r#set_subtype(&mut self, r#subtype: PyObject) {
self.r#subtype = r#subtype;
}
#[getter]
pub fn r#get_subsubtype(&self, py: Python<'_>) -> PyObject {
self.r#subsubtype.clone_ref(py)
}
#[setter]
pub fn r#set_subsubtype(&mut self, r#subsubtype: PyObject) {
self.r#subsubtype = r#subsubtype;
}
pub fn r#__call__(&mut self, r#type: PyObject) {
self.r#type = r#type;
}
#[staticmethod]
pub fn r#static_method(r#type: PyObject) -> PyObject {
r#type
}
#[classmethod]
pub fn r#class_method(_: &Bound<'_, PyType>, r#type: PyObject) -> PyObject {
r#type
}
#[classattr]
pub fn r#class_attr_fn() -> i32 {
5
}
#[classattr]
const r#CLASS_ATTR_CONST: i32 = 6;
#[pyo3(signature = (r#struct = "foo"))]
fn method_with_keyword<'a>(&self, r#struct: &'a str) -> &'a str {
r#struct
}
}
#[test]
fn test_raw_idents() {
Python::with_gil(|py| {
let raw_idents_type = py.get_type::<r#RawIdents>();
assert_eq!(raw_idents_type.qualname().unwrap(), "RawIdents");
py_run!(
py,
raw_idents_type,
r#"
instance = raw_idents_type(type=None, subtype=5, subsubtype="foo")
assert instance.type is None
assert instance.subtype == 5
assert instance.subsubtype == "foo"
instance.type = 1
instance.subtype = 2
instance.subsubtype = 3
assert instance.type == 1
assert instance.subtype == 2
assert instance.subsubtype == 3
assert raw_idents_type.static_method(type=30) == 30
assert instance.class_method(type=40) == 40
instance(type=50)
assert instance.type == 50
assert raw_idents_type.class_attr_fn == 5
assert raw_idents_type.CLASS_ATTR_CONST == 6
assert instance.method_with_keyword() == "foo"
assert instance.method_with_keyword("bar") == "bar"
assert instance.method_with_keyword(struct="baz") == "baz"
"#
);
})
}
// Regression test for issue 1505 - Python argument not detected correctly when inside a macro.
#[pyclass]
struct Issue1505 {}
macro_rules! pymethods {
(
#[pymethods]
impl $ty: ty {
fn $fn:ident (&self, $arg:ident : $arg_ty:ty) {}
}
) => {
#[pymethods]
impl $ty {
fn $fn(&self, $arg: $arg_ty) {}
}
};
}
pymethods!(
#[pymethods]
impl Issue1505 {
fn issue_1505(&self, _py: Python<'_>) {}
}
);
// Regression test for issue 1506 - incorrect macro hygiene.
// By applying the `#[pymethods]` attribute inside a macro_rules! macro, this separates the macro
// call scope from the scope of the impl block. For this to work our macros must be careful to not
// cheat hygiene!
#[pyclass]
struct Issue1506 {}
macro_rules! issue_1506 {
(#[pymethods] $($body:tt)*) => {
#[pymethods]
$($body)*
};
}
issue_1506!(
#[pymethods]
impl Issue1506 {
#[pyo3(signature = (_arg, _args, _kwargs=None))]
fn issue_1506(
&self,
_py: Python<'_>,
_arg: &Bound<'_, PyAny>,
_args: &Bound<'_, PyTuple>,
_kwargs: Option<&Bound<'_, PyDict>>,
) {
}
#[pyo3(signature = (_arg, _args, _kwargs=None))]
fn issue_1506_mut(
&mut self,
_py: Python<'_>,
_arg: &Bound<'_, PyAny>,
_args: &Bound<'_, PyTuple>,
_kwargs: Option<&Bound<'_, PyDict>>,
) {
}
#[pyo3(signature = (_arg, _args, _kwargs=None))]
fn issue_1506_custom_receiver(
_slf: Py<Self>,
_py: Python<'_>,
_arg: &Bound<'_, PyAny>,
_args: &Bound<'_, PyTuple>,
_kwargs: Option<&Bound<'_, PyDict>>,
) {
}
#[pyo3(signature = (_arg, _args, _kwargs=None))]
fn issue_1506_custom_receiver_explicit(
_slf: Py<Issue1506>,
_py: Python<'_>,
_arg: &Bound<'_, PyAny>,
_args: &Bound<'_, PyTuple>,
_kwargs: Option<&Bound<'_, PyDict>>,
) {
}
#[new]
#[pyo3(signature = (_arg, _args, _kwargs=None))]
fn issue_1506_new(
_py: Python<'_>,
_arg: &Bound<'_, PyAny>,
_args: &Bound<'_, PyTuple>,
_kwargs: Option<&Bound<'_, PyDict>>,
) -> Self {
Issue1506 {}
}
#[getter("foo")]
fn issue_1506_getter(&self, _py: Python<'_>) -> i32 {
5
}
#[setter("foo")]
fn issue_1506_setter(&self, _py: Python<'_>, _value: i32) {}
#[staticmethod]
#[pyo3(signature = (_arg, _args, _kwargs=None))]
fn issue_1506_static(
_py: Python<'_>,
_arg: &Bound<'_, PyAny>,
_args: &Bound<'_, PyTuple>,
_kwargs: Option<&Bound<'_, PyDict>>,
) {
}
#[classmethod]
#[pyo3(signature = (_arg, _args, _kwargs=None))]
fn issue_1506_class(
_cls: &Bound<'_, PyType>,
_py: Python<'_>,
_arg: &Bound<'_, PyAny>,
_args: &Bound<'_, PyTuple>,
_kwargs: Option<&Bound<'_, PyDict>>,
) {
}
}
);
#[pyclass]
struct Issue1696 {}
pymethods!(
#[pymethods]
impl Issue1696 {
fn issue_1696(&self, _x: &InstanceMethod) {}
}
);
#[test]
fn test_option_pyclass_arg() {
// Option<&PyClass> argument with a default set in a signature regressed to a compile
// error in PyO3 0.17.0 - this test it continues to be accepted.
#[pyclass]
struct SomePyClass {}
#[pyfunction(signature = (arg=None))]
fn option_class_arg(arg: Option<&SomePyClass>) -> Option<SomePyClass> {
arg.map(|_| SomePyClass {})
}
Python::with_gil(|py| {
let f = wrap_pyfunction!(option_class_arg, py).unwrap();
assert!(f.call0().unwrap().is_none());
let obj = Py::new(py, SomePyClass {}).unwrap();
assert!(f
.call1((obj,))
.unwrap()
.extract::<Py<SomePyClass>>()
.is_ok());
})
}
#[test]
fn test_issue_2988() {
#[pyfunction]
#[pyo3(signature = (
_data = vec![],
_data2 = vec![],
))]
pub fn _foo(
_data: Vec<i32>,
// The from_py_with here looks a little odd, we just need some way
// to encourage the macro to expand the from_py_with default path too
#[pyo3(from_py_with = "<Bound<'_, _> as PyAnyMethods>::extract")] _data2: Vec<i32>,
) {
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_various.rs | #![cfg(feature = "macros")]
use pyo3::prelude::*;
use pyo3::py_run;
use pyo3::types::PyTuple;
use std::fmt;
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
struct MutRefArg {
n: i32,
}
#[pymethods]
impl MutRefArg {
fn get(&self) -> i32 {
self.n
}
fn set_other(&self, mut other: PyRefMut<'_, MutRefArg>) {
other.n = 100;
}
}
#[test]
fn mut_ref_arg() {
Python::with_gil(|py| {
let inst1 = Py::new(py, MutRefArg { n: 0 }).unwrap();
let inst2 = Py::new(py, MutRefArg { n: 0 }).unwrap();
py_run!(py, inst1 inst2, "inst1.set_other(inst2)");
let inst2 = inst2.bind(py).borrow();
assert_eq!(inst2.n, 100);
});
}
#[pyclass]
struct PyUsize {
#[pyo3(get)]
pub value: usize,
}
#[pyfunction]
fn get_zero() -> PyUsize {
PyUsize { value: 0 }
}
#[test]
/// Checks that we can use return a custom class in arbitrary function and use those functions
/// both in rust and python
fn return_custom_class() {
Python::with_gil(|py| {
// Using from rust
assert_eq!(get_zero().value, 0);
// Using from python
let get_zero = wrap_pyfunction!(get_zero)(py).unwrap();
py_assert!(py, get_zero, "get_zero().value == 0");
});
}
#[test]
fn intopytuple_primitive() {
Python::with_gil(|py| {
let tup = (1, 2, "foo");
py_assert!(py, tup, "tup == (1, 2, 'foo')");
py_assert!(py, tup, "tup[0] == 1");
py_assert!(py, tup, "tup[1] == 2");
py_assert!(py, tup, "tup[2] == 'foo'");
});
}
#[pyclass]
struct SimplePyClass {}
#[test]
fn intopytuple_pyclass() {
Python::with_gil(|py| {
let tup = (
Py::new(py, SimplePyClass {}).unwrap(),
Py::new(py, SimplePyClass {}).unwrap(),
);
py_assert!(py, tup, "type(tup[0]).__name__ == 'SimplePyClass'");
py_assert!(py, tup, "type(tup[0]).__name__ == type(tup[1]).__name__");
py_assert!(py, tup, "tup[0] != tup[1]");
});
}
#[test]
fn pytuple_primitive_iter() {
Python::with_gil(|py| {
let tup = PyTuple::new(py, [1u32, 2, 3].iter()).unwrap();
py_assert!(py, tup, "tup == (1, 2, 3)");
});
}
#[test]
fn pytuple_pyclass_iter() {
Python::with_gil(|py| {
let tup = PyTuple::new(
py,
[
Py::new(py, SimplePyClass {}).unwrap(),
Py::new(py, SimplePyClass {}).unwrap(),
]
.iter(),
)
.unwrap();
py_assert!(py, tup, "type(tup[0]).__name__ == 'SimplePyClass'");
py_assert!(py, tup, "type(tup[0]).__name__ == type(tup[0]).__name__");
py_assert!(py, tup, "tup[0] != tup[1]");
});
}
#[test]
#[cfg(any(Py_3_9, not(Py_LIMITED_API)))]
fn test_pickle() {
use pyo3::types::PyDict;
#[pyclass(dict, module = "test_module")]
struct PickleSupport {}
#[pymethods]
impl PickleSupport {
#[new]
fn new() -> PickleSupport {
PickleSupport {}
}
pub fn __reduce__<'py>(
slf: &Bound<'py, Self>,
py: Python<'py>,
) -> PyResult<(Bound<'py, PyAny>, Bound<'py, PyTuple>, Bound<'py, PyAny>)> {
let cls = slf.getattr("__class__")?;
let dict = slf.getattr("__dict__")?;
Ok((cls, PyTuple::empty(py), dict))
}
}
fn add_module(module: Bound<'_, PyModule>) -> PyResult<()> {
PyModule::import(module.py(), "sys")?
.dict()
.get_item("modules")
.unwrap()
.unwrap()
.downcast::<PyDict>()?
.set_item(module.name()?, module)
}
Python::with_gil(|py| {
let module = PyModule::new(py, "test_module").unwrap();
module.add_class::<PickleSupport>().unwrap();
add_module(module).unwrap();
let inst = Py::new(py, PickleSupport {}).unwrap();
py_run!(
py,
inst,
r#"
inst.a = 1
assert inst.__dict__ == {'a': 1}
import pickle
inst2 = pickle.loads(pickle.dumps(inst))
assert inst2.__dict__ == {'a': 1}
"#
);
});
}
/// Testing https://github.com/PyO3/pyo3/issues/1106. A result type that
/// implements `From<MyError> for PyErr` should be automatically converted
/// when using `#[pyfunction]`.
///
/// This only makes sure that valid `Result` types do work. For an invalid
/// enum type, see `ui/invalid_result_conversion.py`.
#[derive(Debug)]
struct MyError {
pub descr: &'static str,
}
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "My error message: {}", self.descr)
}
}
/// Important for the automatic conversion to `PyErr`.
impl From<MyError> for PyErr {
fn from(err: MyError) -> pyo3::PyErr {
pyo3::exceptions::PyOSError::new_err(err.to_string())
}
}
#[pyfunction]
fn result_conversion_function() -> Result<(), MyError> {
Err(MyError {
descr: "something went wrong",
})
}
#[test]
fn test_result_conversion() {
Python::with_gil(|py| {
wrap_pyfunction!(result_conversion_function)(py).unwrap();
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_buffer.rs | #![cfg(feature = "macros")]
#![cfg(any(not(Py_LIMITED_API), Py_3_11))]
use pyo3::{buffer::PyBuffer, exceptions::PyBufferError, ffi, prelude::*};
use std::{
os::raw::{c_int, c_void},
ptr,
};
#[macro_use]
#[path = "../src/tests/common.rs"]
mod common;
enum TestGetBufferError {
NullShape,
NullStrides,
IncorrectItemSize,
IncorrectFormat,
IncorrectAlignment,
}
#[pyclass]
struct TestBufferErrors {
buf: Vec<u32>,
error: Option<TestGetBufferError>,
}
#[pymethods]
impl TestBufferErrors {
unsafe fn __getbuffer__(
slf: PyRefMut<'_, Self>,
view: *mut ffi::Py_buffer,
flags: c_int,
) -> PyResult<()> {
if view.is_null() {
return Err(PyBufferError::new_err("View is null"));
}
if (flags & ffi::PyBUF_WRITABLE) == ffi::PyBUF_WRITABLE {
return Err(PyBufferError::new_err("Object is not writable"));
}
let bytes = &slf.buf;
(*view).buf = bytes.as_ptr() as *mut c_void;
(*view).len = bytes.len() as isize;
(*view).readonly = 1;
(*view).itemsize = std::mem::size_of::<u32>() as isize;
let msg = ffi::c_str!("I");
(*view).format = msg.as_ptr() as *mut _;
(*view).ndim = 1;
(*view).shape = &mut (*view).len;
(*view).strides = &mut (*view).itemsize;
(*view).suboffsets = ptr::null_mut();
(*view).internal = ptr::null_mut();
if let Some(err) = &slf.error {
use TestGetBufferError::*;
match err {
NullShape => {
(*view).shape = std::ptr::null_mut();
}
NullStrides => {
(*view).strides = std::ptr::null_mut();
}
IncorrectItemSize => {
(*view).itemsize += 1;
}
IncorrectFormat => {
(*view).format = ffi::c_str!("B").as_ptr() as _;
}
IncorrectAlignment => (*view).buf = (*view).buf.add(1),
}
}
(*view).obj = slf.into_ptr();
Ok(())
}
}
#[test]
fn test_get_buffer_errors() {
Python::with_gil(|py| {
let instance = Py::new(
py,
TestBufferErrors {
buf: vec![0, 1, 2, 3],
error: None,
},
)
.unwrap();
assert!(PyBuffer::<u32>::get(instance.bind(py)).is_ok());
instance.borrow_mut(py).error = Some(TestGetBufferError::NullShape);
assert_eq!(
PyBuffer::<u32>::get(instance.bind(py))
.unwrap_err()
.to_string(),
"BufferError: shape is null"
);
instance.borrow_mut(py).error = Some(TestGetBufferError::NullStrides);
assert_eq!(
PyBuffer::<u32>::get(instance.bind(py))
.unwrap_err()
.to_string(),
"BufferError: strides is null"
);
instance.borrow_mut(py).error = Some(TestGetBufferError::IncorrectItemSize);
assert_eq!(
PyBuffer::<u32>::get(instance.bind(py))
.unwrap_err()
.to_string(),
"BufferError: buffer contents are not compatible with u32"
);
instance.borrow_mut(py).error = Some(TestGetBufferError::IncorrectFormat);
assert_eq!(
PyBuffer::<u32>::get(instance.bind(py))
.unwrap_err()
.to_string(),
"BufferError: buffer contents are not compatible with u32"
);
instance.borrow_mut(py).error = Some(TestGetBufferError::IncorrectAlignment);
assert_eq!(
PyBuffer::<u32>::get(instance.bind(py))
.unwrap_err()
.to_string(),
"BufferError: buffer contents are insufficiently aligned for u32"
);
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_serde.rs | #[cfg(feature = "serde")]
mod test_serde {
use pyo3::prelude::*;
use serde::{Deserialize, Serialize};
#[pyclass]
#[derive(Debug, Serialize, Deserialize)]
struct Group {
name: String,
}
#[pyclass]
#[derive(Debug, Serialize, Deserialize)]
struct User {
username: String,
group: Option<Py<Group>>,
friends: Vec<Py<User>>,
}
#[test]
fn test_serialize() {
let friend1 = User {
username: "friend 1".into(),
group: None,
friends: vec![],
};
let friend2 = User {
username: "friend 2".into(),
group: None,
friends: vec![],
};
let user = Python::with_gil(|py| {
let py_friend1 = Py::new(py, friend1).expect("failed to create friend 1");
let py_friend2 = Py::new(py, friend2).expect("failed to create friend 2");
let friends = vec![py_friend1, py_friend2];
let py_group = Py::new(
py,
Group {
name: "group name".into(),
},
)
.unwrap();
User {
username: "danya".into(),
group: Some(py_group),
friends,
}
});
let serialized = serde_json::to_string(&user).expect("failed to serialize");
assert_eq!(
serialized,
r#"{"username":"danya","group":{"name":"group name"},"friends":[{"username":"friend 1","group":null,"friends":[]},{"username":"friend 2","group":null,"friends":[]}]}"#
);
}
#[test]
fn test_deserialize() {
let serialized = r#"{"username": "danya", "friends":
[{"username": "friend", "group": {"name": "danya's friends"}, "friends": []}]}"#;
let user: User = serde_json::from_str(serialized).expect("failed to deserialize");
assert_eq!(user.username, "danya");
assert!(user.group.is_none());
assert_eq!(user.friends.len(), 1usize);
let friend = user.friends.first().unwrap();
Python::with_gil(|py| {
assert_eq!(friend.borrow(py).username, "friend");
assert_eq!(
friend.borrow(py).group.as_ref().unwrap().borrow(py).name,
"danya's friends"
)
});
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_class_formatting.rs | #![cfg(feature = "macros")]
use pyo3::prelude::*;
use pyo3::py_run;
use std::fmt::{Display, Formatter};
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass(eq, str)]
#[derive(Debug, PartialEq)]
pub enum MyEnum2 {
Variant,
OtherVariant,
}
impl Display for MyEnum2 {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
#[pyclass(eq, str)]
#[derive(Debug, PartialEq)]
pub enum MyEnum3 {
#[pyo3(name = "AwesomeVariant")]
Variant,
OtherVariant,
}
impl Display for MyEnum3 {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let variant = match self {
MyEnum3::Variant => "AwesomeVariant",
MyEnum3::OtherVariant => "OtherVariant",
};
write!(f, "MyEnum.{}", variant)
}
}
#[test]
fn test_enum_class_fmt() {
Python::with_gil(|py| {
let var2 = Py::new(py, MyEnum2::Variant).unwrap();
let var3 = Py::new(py, MyEnum3::Variant).unwrap();
let var4 = Py::new(py, MyEnum3::OtherVariant).unwrap();
py_assert!(py, var2, "str(var2) == 'Variant'");
py_assert!(py, var3, "str(var3) == 'MyEnum.AwesomeVariant'");
py_assert!(py, var4, "str(var4) == 'MyEnum.OtherVariant'");
})
}
#[pyclass(str = "X: {x}, Y: {y}, Z: {z}")]
#[derive(PartialEq, Eq, Clone, PartialOrd)]
pub struct Point {
x: i32,
y: i32,
z: i32,
}
#[test]
fn test_custom_struct_custom_str() {
Python::with_gil(|py| {
let var1 = Py::new(py, Point { x: 1, y: 2, z: 3 }).unwrap();
py_assert!(py, var1, "str(var1) == 'X: 1, Y: 2, Z: 3'");
})
}
#[pyclass(str)]
#[derive(PartialEq, Eq, Clone, PartialOrd)]
pub struct Point2 {
x: i32,
y: i32,
z: i32,
}
impl Display for Point2 {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "({}, {}, {})", self.x, self.y, self.z)
}
}
#[test]
fn test_struct_str() {
Python::with_gil(|py| {
let var1 = Py::new(py, Point2 { x: 1, y: 2, z: 3 }).unwrap();
py_assert!(py, var1, "str(var1) == '(1, 2, 3)'");
})
}
#[pyclass(str)]
#[derive(PartialEq, Debug)]
enum ComplexEnumWithStr {
A(u32),
B { msg: String },
}
impl Display for ComplexEnumWithStr {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
#[test]
fn test_custom_complex_enum_str() {
Python::with_gil(|py| {
let var1 = Py::new(py, ComplexEnumWithStr::A(45)).unwrap();
let var2 = Py::new(
py,
ComplexEnumWithStr::B {
msg: "Hello".to_string(),
},
)
.unwrap();
py_assert!(py, var1, "str(var1) == 'A(45)'");
py_assert!(py, var2, "str(var2) == 'B { msg: \"Hello\" }'");
})
}
#[pyclass(str = "{0}, {1}, {2}")]
#[derive(PartialEq)]
struct Coord(u32, u32, u32);
#[pyclass(str = "{{{0}, {1}, {2}}}")]
#[derive(PartialEq)]
struct Coord2(u32, u32, u32);
#[test]
fn test_str_representation_by_position() {
Python::with_gil(|py| {
let var1 = Py::new(py, Coord(1, 2, 3)).unwrap();
let var2 = Py::new(py, Coord2(1, 2, 3)).unwrap();
py_assert!(py, var1, "str(var1) == '1, 2, 3'");
py_assert!(py, var2, "str(var2) == '{1, 2, 3}'");
})
}
#[pyclass(str = "name: {name}: {name}, idn: {idn:03} with message: {msg}")]
#[derive(PartialEq, Debug)]
struct Point4 {
name: String,
msg: String,
idn: u32,
}
#[test]
fn test_mixed_and_repeated_str_formats() {
Python::with_gil(|py| {
let var1 = Py::new(
py,
Point4 {
name: "aaa".to_string(),
msg: "hello".to_string(),
idn: 1,
},
)
.unwrap();
py_run!(
py,
var1,
r#"
assert str(var1) == 'name: aaa: aaa, idn: 001 with message: hello'
"#
);
})
}
#[pyclass(str = "type: {r#type}")]
struct Foo {
r#type: u32,
}
#[test]
fn test_raw_identifier_struct_custom_str() {
Python::with_gil(|py| {
let var1 = Py::new(py, Foo { r#type: 3 }).unwrap();
py_assert!(py, var1, "str(var1) == 'type: 3'");
})
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_coroutine.rs | #![cfg(feature = "experimental-async")]
#![cfg(not(target_arch = "wasm32"))]
use std::{ffi::CString, task::Poll, thread, time::Duration};
use futures::{channel::oneshot, future::poll_fn, FutureExt};
#[cfg(not(target_has_atomic = "64"))]
use portable_atomic::{AtomicBool, Ordering};
use pyo3::{
coroutine::CancelHandle,
prelude::*,
py_run,
types::{IntoPyDict, PyType},
};
#[cfg(target_has_atomic = "64")]
use std::sync::atomic::{AtomicBool, Ordering};
#[path = "../src/tests/common.rs"]
mod common;
fn handle_windows(test: &str) -> String {
let set_event_loop_policy = r#"
import asyncio, sys
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
"#;
pyo3::unindent::unindent(set_event_loop_policy) + &pyo3::unindent::unindent(test)
}
#[test]
fn noop_coroutine() {
#[pyfunction]
async fn noop() -> usize {
42
}
Python::with_gil(|gil| {
let noop = wrap_pyfunction!(noop, gil).unwrap();
let test = "import asyncio; assert asyncio.run(noop()) == 42";
py_run!(gil, noop, &handle_windows(test));
})
}
#[test]
fn test_coroutine_qualname() {
#[pyfunction]
async fn my_fn() {}
#[pyclass]
struct MyClass;
#[pymethods]
impl MyClass {
#[new]
fn new() -> Self {
Self
}
// TODO use &self when possible
async fn my_method(_self: Py<Self>) {}
#[classmethod]
async fn my_classmethod(_cls: Py<PyType>) {}
#[staticmethod]
async fn my_staticmethod() {}
}
Python::with_gil(|gil| {
let test = r#"
for coro, name, qualname in [
(my_fn(), "my_fn", "my_fn"),
(MyClass().my_method(), "my_method", "MyClass.my_method"),
#(MyClass().my_classmethod(), "my_classmethod", "MyClass.my_classmethod"),
(MyClass.my_staticmethod(), "my_staticmethod", "MyClass.my_staticmethod"),
]:
assert coro.__name__ == name and coro.__qualname__ == qualname
"#;
let locals = [
("my_fn", wrap_pyfunction!(my_fn, gil).unwrap().as_any()),
("MyClass", gil.get_type::<MyClass>().as_any()),
]
.into_py_dict(gil)
.unwrap();
py_run!(gil, *locals, &handle_windows(test));
})
}
#[test]
fn sleep_0_like_coroutine() {
#[pyfunction]
async fn sleep_0() -> usize {
let mut waken = false;
poll_fn(|cx| {
if !waken {
cx.waker().wake_by_ref();
waken = true;
return Poll::Pending;
}
Poll::Ready(42)
})
.await
}
Python::with_gil(|gil| {
let sleep_0 = wrap_pyfunction!(sleep_0, gil).unwrap();
let test = "import asyncio; assert asyncio.run(sleep_0()) == 42";
py_run!(gil, sleep_0, &handle_windows(test));
})
}
#[pyfunction]
async fn sleep(seconds: f64) -> usize {
let (tx, rx) = oneshot::channel();
thread::spawn(move || {
thread::sleep(Duration::from_secs_f64(seconds));
tx.send(42).unwrap();
});
rx.await.unwrap()
}
#[test]
fn sleep_coroutine() {
Python::with_gil(|gil| {
let sleep = wrap_pyfunction!(sleep, gil).unwrap();
let test = r#"import asyncio; assert asyncio.run(sleep(0.1)) == 42"#;
py_run!(gil, sleep, &handle_windows(test));
})
}
#[pyfunction]
async fn return_tuple() -> (usize, usize) {
(42, 43)
}
#[test]
fn tuple_coroutine() {
Python::with_gil(|gil| {
let func = wrap_pyfunction!(return_tuple, gil).unwrap();
let test = r#"import asyncio; assert asyncio.run(func()) == (42, 43)"#;
py_run!(gil, func, &handle_windows(test));
})
}
#[test]
fn cancelled_coroutine() {
Python::with_gil(|gil| {
let sleep = wrap_pyfunction!(sleep, gil).unwrap();
let test = r#"
import asyncio
async def main():
task = asyncio.create_task(sleep(999))
await asyncio.sleep(0)
task.cancel()
await task
asyncio.run(main())
"#;
let globals = gil.import("__main__").unwrap().dict();
globals.set_item("sleep", sleep).unwrap();
let err = gil
.run(
&CString::new(pyo3::unindent::unindent(&handle_windows(test))).unwrap(),
Some(&globals),
None,
)
.unwrap_err();
assert_eq!(
err.value(gil).get_type().qualname().unwrap(),
"CancelledError"
);
})
}
#[test]
fn coroutine_cancel_handle() {
#[pyfunction]
async fn cancellable_sleep(
seconds: f64,
#[pyo3(cancel_handle)] mut cancel: CancelHandle,
) -> usize {
futures::select! {
_ = sleep(seconds).fuse() => 42,
_ = cancel.cancelled().fuse() => 0,
}
}
Python::with_gil(|gil| {
let cancellable_sleep = wrap_pyfunction!(cancellable_sleep, gil).unwrap();
let test = r#"
import asyncio;
async def main():
task = asyncio.create_task(cancellable_sleep(999))
await asyncio.sleep(0)
task.cancel()
return await task
assert asyncio.run(main()) == 0
"#;
let globals = gil.import("__main__").unwrap().dict();
globals
.set_item("cancellable_sleep", cancellable_sleep)
.unwrap();
gil.run(
&CString::new(pyo3::unindent::unindent(&handle_windows(test))).unwrap(),
Some(&globals),
None,
)
.unwrap();
})
}
#[test]
fn coroutine_is_cancelled() {
#[pyfunction]
async fn sleep_loop(#[pyo3(cancel_handle)] cancel: CancelHandle) {
while !cancel.is_cancelled() {
sleep(0.001).await;
}
}
Python::with_gil(|gil| {
let sleep_loop = wrap_pyfunction!(sleep_loop, gil).unwrap();
let test = r#"
import asyncio;
async def main():
task = asyncio.create_task(sleep_loop())
await asyncio.sleep(0)
task.cancel()
await task
asyncio.run(main())
"#;
let globals = gil.import("__main__").unwrap().dict();
globals.set_item("sleep_loop", sleep_loop).unwrap();
gil.run(
&CString::new(pyo3::unindent::unindent(&handle_windows(test))).unwrap(),
Some(&globals),
None,
)
.unwrap();
})
}
#[test]
fn coroutine_panic() {
#[pyfunction]
async fn panic() {
panic!("test panic");
}
Python::with_gil(|gil| {
let panic = wrap_pyfunction!(panic, gil).unwrap();
let test = r#"
import asyncio
coro = panic()
try:
asyncio.run(coro)
except BaseException as err:
assert type(err).__name__ == "PanicException"
assert str(err) == "test panic"
else:
assert False
try:
coro.send(None)
except RuntimeError as err:
assert str(err) == "cannot reuse already awaited coroutine"
else:
assert False;
"#;
py_run!(gil, panic, &handle_windows(test));
})
}
#[test]
fn test_async_method_receiver() {
#[pyclass]
struct Counter(usize);
#[pymethods]
impl Counter {
#[new]
fn new() -> Self {
Self(0)
}
async fn get(&self) -> usize {
self.0
}
async fn incr(&mut self) -> usize {
self.0 += 1;
self.0
}
}
static IS_DROPPED: AtomicBool = AtomicBool::new(false);
impl Drop for Counter {
fn drop(&mut self) {
IS_DROPPED.store(true, Ordering::SeqCst);
}
}
Python::with_gil(|gil| {
let test = r#"
import asyncio
obj = Counter()
coro1 = obj.get()
coro2 = obj.get()
try:
obj.incr() # borrow checking should fail
except RuntimeError as err:
pass
else:
assert False
assert asyncio.run(coro1) == 0
coro2.close()
coro3 = obj.incr()
try:
obj.incr() # borrow checking should fail
except RuntimeError as err:
pass
else:
assert False
try:
obj.get() # borrow checking should fail
except RuntimeError as err:
pass
else:
assert False
assert asyncio.run(coro3) == 1
"#;
let locals = [("Counter", gil.get_type::<Counter>())]
.into_py_dict(gil)
.unwrap();
py_run!(gil, *locals, test);
});
assert!(IS_DROPPED.load(Ordering::SeqCst));
}
#[test]
fn test_async_method_receiver_with_other_args() {
#[pyclass]
struct Value(i32);
#[pymethods]
impl Value {
#[new]
fn new() -> Self {
Self(0)
}
async fn get_value_plus_with(&self, v1: i32, v2: i32) -> i32 {
self.0 + v1 + v2
}
async fn set_value(&mut self, new_value: i32) -> i32 {
self.0 = new_value;
self.0
}
}
Python::with_gil(|gil| {
let test = r#"
import asyncio
v = Value()
assert asyncio.run(v.get_value_plus_with(3, 0)) == 3
assert asyncio.run(v.set_value(10)) == 10
assert asyncio.run(v.get_value_plus_with(1, 1)) == 12
"#;
let locals = [("Value", gil.get_type::<Value>())]
.into_py_dict(gil)
.unwrap();
py_run!(gil, *locals, test);
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_class_attributes.rs | #![cfg(feature = "macros")]
use pyo3::prelude::*;
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
struct Foo {
#[pyo3(get)]
x: i32,
}
#[pyclass]
struct Bar {
#[pyo3(get)]
x: i32,
}
#[pymethods]
impl Foo {
#[classattr]
const MY_CONST: &'static str = "foobar";
#[classattr]
#[pyo3(name = "RENAMED_CONST")]
const MY_CONST_2: &'static str = "foobar_2";
#[classattr]
fn a() -> i32 {
5
}
#[classattr]
#[pyo3(name = "B")]
fn b() -> String {
"bar".to_string()
}
#[classattr]
fn bar() -> Bar {
Bar { x: 2 }
}
#[classattr]
fn a_foo() -> Foo {
Foo { x: 1 }
}
#[classattr]
fn a_foo_with_py(py: Python<'_>) -> Py<Foo> {
Py::new(py, Foo { x: 1 }).unwrap()
}
}
#[test]
fn class_attributes() {
Python::with_gil(|py| {
let foo_obj = py.get_type::<Foo>();
py_assert!(py, foo_obj, "foo_obj.MY_CONST == 'foobar'");
py_assert!(py, foo_obj, "foo_obj.RENAMED_CONST == 'foobar_2'");
py_assert!(py, foo_obj, "foo_obj.a == 5");
py_assert!(py, foo_obj, "foo_obj.B == 'bar'");
py_assert!(py, foo_obj, "foo_obj.a_foo.x == 1");
py_assert!(py, foo_obj, "foo_obj.a_foo_with_py.x == 1");
});
}
// Ignored because heap types are not immutable:
// https://github.com/python/cpython/blob/master/Objects/typeobject.c#L3399-L3409
#[test]
#[ignore]
fn class_attributes_are_immutable() {
Python::with_gil(|py| {
let foo_obj = py.get_type::<Foo>();
py_expect_exception!(py, foo_obj, "foo_obj.a = 6", PyTypeError);
});
}
#[pymethods]
impl Bar {
#[classattr]
fn a_foo() -> Foo {
Foo { x: 3 }
}
}
#[test]
fn recursive_class_attributes() {
Python::with_gil(|py| {
let foo_obj = py.get_type::<Foo>();
let bar_obj = py.get_type::<Bar>();
py_assert!(py, foo_obj, "foo_obj.a_foo.x == 1");
py_assert!(py, foo_obj, "foo_obj.bar.x == 2");
py_assert!(py, bar_obj, "bar_obj.a_foo.x == 3");
});
}
#[test]
fn test_fallible_class_attribute() {
use pyo3::{exceptions::PyValueError, types::PyString};
struct CaptureStdErr<'py> {
oldstderr: Bound<'py, PyAny>,
string_io: Bound<'py, PyAny>,
}
impl<'py> CaptureStdErr<'py> {
fn new(py: Python<'py>) -> PyResult<Self> {
let sys = py.import("sys")?;
let oldstderr = sys.getattr("stderr")?;
let string_io = py.import("io")?.getattr("StringIO")?.call0()?;
sys.setattr("stderr", &string_io)?;
Ok(Self {
oldstderr,
string_io,
})
}
fn reset(self) -> PyResult<String> {
let py = self.string_io.py();
let payload = self
.string_io
.getattr("getvalue")?
.call0()?
.downcast::<PyString>()?
.to_cow()?
.into_owned();
let sys = py.import("sys")?;
sys.setattr("stderr", self.oldstderr)?;
Ok(payload)
}
}
#[pyclass]
struct BrokenClass;
#[pymethods]
impl BrokenClass {
#[classattr]
fn fails_to_init() -> PyResult<i32> {
Err(PyValueError::new_err("failed to create class attribute"))
}
}
Python::with_gil(|py| {
let stderr = CaptureStdErr::new(py).unwrap();
assert!(std::panic::catch_unwind(|| py.get_type::<BrokenClass>()).is_err());
assert_eq!(
stderr.reset().unwrap().trim(),
"\
ValueError: failed to create class attribute
The above exception was the direct cause of the following exception:
RuntimeError: An error occurred while initializing `BrokenClass.fails_to_init`
The above exception was the direct cause of the following exception:
RuntimeError: An error occurred while initializing class BrokenClass"
)
});
}
#[pyclass(get_all, set_all, rename_all = "camelCase")]
struct StructWithRenamedFields {
first_field: bool,
second_field: u8,
#[pyo3(name = "third_field")]
fourth_field: bool,
}
#[pymethods]
impl StructWithRenamedFields {
#[new]
fn new() -> Self {
Self {
first_field: true,
second_field: 5,
fourth_field: false,
}
}
}
#[test]
fn test_renaming_all_struct_fields() {
use pyo3::types::PyBool;
Python::with_gil(|py| {
let struct_class = py.get_type::<StructWithRenamedFields>();
let struct_obj = struct_class.call0().unwrap();
assert!(struct_obj
.setattr("firstField", PyBool::new(py, false))
.is_ok());
py_assert!(py, struct_obj, "struct_obj.firstField == False");
py_assert!(py, struct_obj, "struct_obj.secondField == 5");
assert!(struct_obj
.setattr("third_field", PyBool::new(py, true))
.is_ok());
py_assert!(py, struct_obj, "struct_obj.third_field == True");
});
}
macro_rules! test_case {
($struct_name: ident, $rule: literal, $field_name: ident, $renamed_field_name: literal, $test_name: ident) => {
#[pyclass(get_all, set_all, rename_all = $rule)]
#[allow(non_snake_case)]
struct $struct_name {
$field_name: u8,
}
#[pymethods]
impl $struct_name {
#[new]
fn new() -> Self {
Self { $field_name: 0 }
}
}
#[test]
fn $test_name() {
//use pyo3::types::PyInt;
Python::with_gil(|py| {
let struct_class = py.get_type::<$struct_name>();
let struct_obj = struct_class.call0().unwrap();
assert!(struct_obj.setattr($renamed_field_name, 2).is_ok());
let attr = struct_obj.getattr($renamed_field_name).unwrap();
assert_eq!(2, attr.extract::<u8>().unwrap());
});
}
};
}
test_case!(
LowercaseTest,
"lowercase",
fieldOne,
"fieldone",
test_rename_all_lowercase
);
test_case!(
CamelCaseTest,
"camelCase",
field_one,
"fieldOne",
test_rename_all_camel_case
);
test_case!(
KebabCaseTest,
"kebab-case",
field_one,
"field-one",
test_rename_all_kebab_case
);
test_case!(
PascalCaseTest,
"PascalCase",
field_one,
"FieldOne",
test_rename_all_pascal_case
);
test_case!(
ScreamingSnakeCaseTest,
"SCREAMING_SNAKE_CASE",
field_one,
"FIELD_ONE",
test_rename_all_screaming_snake_case
);
test_case!(
ScreamingKebabCaseTest,
"SCREAMING-KEBAB-CASE",
field_one,
"FIELD-ONE",
test_rename_all_screaming_kebab_case
);
test_case!(
SnakeCaseTest,
"snake_case",
fieldOne,
"field_one",
test_rename_all_snake_case
);
test_case!(
UppercaseTest,
"UPPERCASE",
fieldOne,
"FIELDONE",
test_rename_all_uppercase
);
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_static_slots.rs | #![cfg(feature = "macros")]
use pyo3::exceptions::PyIndexError;
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
use pyo3::py_run;
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
struct Count5();
#[pymethods]
impl Count5 {
#[new]
fn new() -> Self {
Self()
}
#[staticmethod]
fn __len__() -> usize {
5
}
#[staticmethod]
fn __getitem__(idx: isize) -> PyResult<f64> {
if idx < 0 {
Err(PyIndexError::new_err("Count5 cannot count backwards"))
} else if idx > 4 {
Err(PyIndexError::new_err("Count5 cannot count higher than 5"))
} else {
Ok(idx as f64 + 1.0)
}
}
}
/// Return a dict with `s = Count5()`.
fn test_dict(py: Python<'_>) -> Bound<'_, pyo3::types::PyDict> {
let d = [("Count5", py.get_type::<Count5>())]
.into_py_dict(py)
.unwrap();
// Though we can construct `s` in Rust, let's test `__new__` works.
py_run!(py, *d, "s = Count5()");
d
}
#[test]
fn test_len() {
Python::with_gil(|py| {
let d = test_dict(py);
py_assert!(py, *d, "len(s) == 5");
});
}
#[test]
fn test_getitem() {
Python::with_gil(|py| {
let d = test_dict(py);
py_assert!(py, *d, "s[4] == 5.0");
});
}
#[test]
fn test_list() {
Python::with_gil(|py| {
let d = test_dict(py);
py_assert!(py, *d, "list(s) == [1.0, 2.0, 3.0, 4.0, 5.0]");
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_class_conversion.rs | #![cfg(feature = "macros")]
use pyo3::prelude::*;
#[macro_use]
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
#[derive(Clone, Debug, PartialEq)]
struct Cloneable {
x: i32,
}
#[test]
fn test_cloneable_pyclass() {
let c = Cloneable { x: 10 };
Python::with_gil(|py| {
let py_c = Py::new(py, c.clone()).unwrap();
let c2: Cloneable = py_c.extract(py).unwrap();
assert_eq!(c, c2);
{
let rc: PyRef<'_, Cloneable> = py_c.extract(py).unwrap();
assert_eq!(&c, &*rc);
// Drops PyRef before taking PyRefMut
}
let mrc: PyRefMut<'_, Cloneable> = py_c.extract(py).unwrap();
assert_eq!(&c, &*mrc);
});
}
#[pyclass(subclass)]
#[derive(Default)]
struct BaseClass {
value: i32,
}
#[pymethods]
impl BaseClass {
fn foo(&self) -> &'static str {
"BaseClass"
}
}
#[pyclass(extends=BaseClass)]
struct SubClass {}
#[pymethods]
impl SubClass {
fn foo(&self) -> &'static str {
"SubClass"
}
}
#[pyclass]
struct PolymorphicContainer {
#[pyo3(get, set)]
inner: Py<BaseClass>,
}
#[test]
fn test_polymorphic_container_stores_base_class() {
Python::with_gil(|py| {
let p = Py::new(
py,
PolymorphicContainer {
inner: Py::new(py, BaseClass::default()).unwrap(),
},
)
.unwrap();
py_assert!(py, p, "p.inner.foo() == 'BaseClass'");
});
}
#[test]
fn test_polymorphic_container_stores_sub_class() {
Python::with_gil(|py| {
let p = Py::new(
py,
PolymorphicContainer {
inner: Py::new(py, BaseClass::default()).unwrap(),
},
)
.unwrap();
p.bind(py)
.setattr(
"inner",
Py::new(
py,
PyClassInitializer::from(BaseClass::default()).add_subclass(SubClass {}),
)
.unwrap(),
)
.unwrap();
py_assert!(py, p, "p.inner.foo() == 'SubClass'");
});
}
#[test]
fn test_polymorphic_container_does_not_accept_other_types() {
Python::with_gil(|py| {
let p = Py::new(
py,
PolymorphicContainer {
inner: Py::new(py, BaseClass::default()).unwrap(),
},
)
.unwrap();
let setattr = |value: Bound<'_, PyAny>| p.bind(py).setattr("inner", value);
assert!(setattr(1i32.into_pyobject(py).unwrap().into_any()).is_err());
assert!(setattr(py.None().into_bound(py)).is_err());
assert!(setattr((1i32, 2i32).into_pyobject(py).unwrap().into_any()).is_err());
});
}
#[test]
fn test_pyref_as_base() {
Python::with_gil(|py| {
let cell = Bound::new(py, (SubClass {}, BaseClass { value: 120 })).unwrap();
// First try PyRefMut
let sub: PyRefMut<'_, SubClass> = cell.borrow_mut();
let mut base: PyRefMut<'_, BaseClass> = sub.into_super();
assert_eq!(120, base.value);
base.value = 999;
assert_eq!(999, base.value);
drop(base);
// Repeat for PyRef
let sub: PyRef<'_, SubClass> = cell.borrow();
let base: PyRef<'_, BaseClass> = sub.into_super();
assert_eq!(999, base.value);
});
}
#[test]
fn test_pycell_deref() {
Python::with_gil(|py| {
let obj = Bound::new(py, (SubClass {}, BaseClass { value: 120 })).unwrap();
// Should be able to deref as PyAny
assert_eq!(
obj.call_method0("foo")
.and_then(|e| e.extract::<String>())
.unwrap(),
"SubClass"
);
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_buffer_protocol.rs | #![cfg(feature = "macros")]
#![cfg(any(not(Py_LIMITED_API), Py_3_11))]
use pyo3::buffer::PyBuffer;
use pyo3::exceptions::PyBufferError;
use pyo3::ffi;
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
use std::ffi::CString;
use std::os::raw::{c_int, c_void};
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
struct TestBufferClass {
vec: Vec<u8>,
drop_called: Arc<AtomicBool>,
}
#[pymethods]
impl TestBufferClass {
unsafe fn __getbuffer__(
slf: Bound<'_, Self>,
view: *mut ffi::Py_buffer,
flags: c_int,
) -> PyResult<()> {
fill_view_from_readonly_data(view, flags, &slf.borrow().vec, slf.into_any())
}
unsafe fn __releasebuffer__(&self, view: *mut ffi::Py_buffer) {
// Release memory held by the format string
drop(CString::from_raw((*view).format));
}
}
impl Drop for TestBufferClass {
fn drop(&mut self) {
print!("dropped");
self.drop_called.store(true, Ordering::Relaxed);
}
}
#[test]
fn test_buffer() {
let drop_called = Arc::new(AtomicBool::new(false));
Python::with_gil(|py| {
let instance = Py::new(
py,
TestBufferClass {
vec: vec![b' ', b'2', b'3'],
drop_called: drop_called.clone(),
},
)
.unwrap();
let env = [("ob", instance)].into_py_dict(py).unwrap();
py_assert!(py, *env, "bytes(ob) == b' 23'");
});
assert!(drop_called.load(Ordering::Relaxed));
}
#[test]
fn test_buffer_referenced() {
let drop_called = Arc::new(AtomicBool::new(false));
let buf = {
let input = vec![b' ', b'2', b'3'];
Python::with_gil(|py| {
let instance = TestBufferClass {
vec: input.clone(),
drop_called: drop_called.clone(),
}
.into_pyobject(py)
.unwrap();
let buf = PyBuffer::<u8>::get(&instance).unwrap();
assert_eq!(buf.to_vec(py).unwrap(), input);
drop(instance);
buf
})
};
assert!(!drop_called.load(Ordering::Relaxed));
Python::with_gil(|_| {
drop(buf);
});
assert!(drop_called.load(Ordering::Relaxed));
}
#[test]
#[cfg(all(Py_3_8, not(Py_GIL_DISABLED)))] // sys.unraisablehook not available until Python 3.8
fn test_releasebuffer_unraisable_error() {
use common::UnraisableCapture;
use pyo3::exceptions::PyValueError;
#[pyclass]
struct ReleaseBufferError {}
#[pymethods]
impl ReleaseBufferError {
unsafe fn __getbuffer__(
slf: Bound<'_, Self>,
view: *mut ffi::Py_buffer,
flags: c_int,
) -> PyResult<()> {
static BUF_BYTES: &[u8] = b"hello world";
fill_view_from_readonly_data(view, flags, BUF_BYTES, slf.into_any())
}
unsafe fn __releasebuffer__(&self, _view: *mut ffi::Py_buffer) -> PyResult<()> {
Err(PyValueError::new_err("oh dear"))
}
}
Python::with_gil(|py| {
let capture = UnraisableCapture::install(py);
let instance = Py::new(py, ReleaseBufferError {}).unwrap();
let env = [("ob", instance.clone_ref(py))].into_py_dict(py).unwrap();
assert!(capture.borrow(py).capture.is_none());
py_assert!(py, *env, "bytes(ob) == b'hello world'");
let (err, object) = capture.borrow_mut(py).capture.take().unwrap();
assert_eq!(err.to_string(), "ValueError: oh dear");
assert!(object.is(&instance));
capture.borrow_mut(py).uninstall(py);
});
}
/// # Safety
///
/// `view` must be a valid pointer to ffi::Py_buffer, or null
/// `data` must outlive the Python lifetime of `owner` (i.e. data must be owned by owner, or data
/// must be static data)
unsafe fn fill_view_from_readonly_data(
view: *mut ffi::Py_buffer,
flags: c_int,
data: &[u8],
owner: Bound<'_, PyAny>,
) -> PyResult<()> {
if view.is_null() {
return Err(PyBufferError::new_err("View is null"));
}
if (flags & ffi::PyBUF_WRITABLE) == ffi::PyBUF_WRITABLE {
return Err(PyBufferError::new_err("Object is not writable"));
}
(*view).obj = owner.into_ptr();
(*view).buf = data.as_ptr() as *mut c_void;
(*view).len = data.len() as isize;
(*view).readonly = 1;
(*view).itemsize = 1;
(*view).format = if (flags & ffi::PyBUF_FORMAT) == ffi::PyBUF_FORMAT {
let msg = CString::new("B").unwrap();
msg.into_raw()
} else {
ptr::null_mut()
};
(*view).ndim = 1;
(*view).shape = if (flags & ffi::PyBUF_ND) == ffi::PyBUF_ND {
&mut (*view).len
} else {
ptr::null_mut()
};
(*view).strides = if (flags & ffi::PyBUF_STRIDES) == ffi::PyBUF_STRIDES {
&mut (*view).itemsize
} else {
ptr::null_mut()
};
(*view).suboffsets = ptr::null_mut();
(*view).internal = ptr::null_mut();
Ok(())
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_proto_methods.rs | #![cfg(feature = "macros")]
use pyo3::exceptions::{PyAttributeError, PyIndexError, PyValueError};
use pyo3::types::{PyDict, PyList, PyMapping, PySequence, PySlice, PyType};
use pyo3::{prelude::*, py_run};
use std::iter;
use std::sync::Mutex;
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
struct EmptyClass;
#[pyclass]
struct ExampleClass {
#[pyo3(get, set)]
value: i32,
custom_attr: Option<i32>,
}
#[pymethods]
impl ExampleClass {
fn __getattr__(&self, py: Python<'_>, attr: &str) -> PyResult<PyObject> {
if attr == "special_custom_attr" {
Ok(self.custom_attr.into_pyobject(py)?.into_any().unbind())
} else {
Err(PyAttributeError::new_err(attr.to_string()))
}
}
fn __setattr__(&mut self, attr: &str, value: &Bound<'_, PyAny>) -> PyResult<()> {
if attr == "special_custom_attr" {
self.custom_attr = Some(value.extract()?);
Ok(())
} else {
Err(PyAttributeError::new_err(attr.to_string()))
}
}
fn __delattr__(&mut self, attr: &str) -> PyResult<()> {
if attr == "special_custom_attr" {
self.custom_attr = None;
Ok(())
} else {
Err(PyAttributeError::new_err(attr.to_string()))
}
}
fn __str__(&self) -> String {
self.value.to_string()
}
fn __repr__(&self) -> String {
format!("ExampleClass(value={})", self.value)
}
fn __hash__(&self) -> u64 {
let i64_value: i64 = self.value.into();
i64_value as u64
}
fn __bool__(&self) -> bool {
self.value != 0
}
}
fn make_example(py: Python<'_>) -> Bound<'_, ExampleClass> {
Bound::new(
py,
ExampleClass {
value: 5,
custom_attr: Some(20),
},
)
.unwrap()
}
#[test]
fn test_getattr() {
Python::with_gil(|py| {
let example_py = make_example(py);
assert_eq!(
example_py
.getattr("value")
.unwrap()
.extract::<i32>()
.unwrap(),
5,
);
assert_eq!(
example_py
.getattr("special_custom_attr")
.unwrap()
.extract::<i32>()
.unwrap(),
20,
);
assert!(example_py
.getattr("other_attr")
.unwrap_err()
.is_instance_of::<PyAttributeError>(py));
})
}
#[test]
fn test_setattr() {
Python::with_gil(|py| {
let example_py = make_example(py);
example_py.setattr("special_custom_attr", 15).unwrap();
assert_eq!(
example_py
.getattr("special_custom_attr")
.unwrap()
.extract::<i32>()
.unwrap(),
15,
);
})
}
#[test]
fn test_delattr() {
Python::with_gil(|py| {
let example_py = make_example(py);
example_py.delattr("special_custom_attr").unwrap();
assert!(example_py.getattr("special_custom_attr").unwrap().is_none());
})
}
#[test]
fn test_str() {
Python::with_gil(|py| {
let example_py = make_example(py);
assert_eq!(example_py.str().unwrap(), "5");
})
}
#[test]
fn test_repr() {
Python::with_gil(|py| {
let example_py = make_example(py);
assert_eq!(example_py.repr().unwrap(), "ExampleClass(value=5)");
})
}
#[test]
fn test_hash() {
Python::with_gil(|py| {
let example_py = make_example(py);
assert_eq!(example_py.hash().unwrap(), 5);
})
}
#[test]
fn test_bool() {
Python::with_gil(|py| {
let example_py = make_example(py);
assert!(example_py.is_truthy().unwrap());
example_py.borrow_mut().value = 0;
assert!(!example_py.is_truthy().unwrap());
})
}
#[pyclass]
pub struct LenOverflow;
#[pymethods]
impl LenOverflow {
fn __len__(&self) -> usize {
(isize::MAX as usize) + 1
}
}
#[test]
fn len_overflow() {
Python::with_gil(|py| {
let inst = Py::new(py, LenOverflow).unwrap();
py_expect_exception!(py, inst, "len(inst)", PyOverflowError);
});
}
#[pyclass]
pub struct Mapping {
values: Py<PyDict>,
}
#[pymethods]
impl Mapping {
fn __len__(&self, py: Python<'_>) -> usize {
self.values.bind(py).len()
}
fn __getitem__<'py>(&self, key: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
let any: &Bound<'py, PyAny> = self.values.bind(key.py());
any.get_item(key)
}
fn __setitem__<'py>(&self, key: &Bound<'py, PyAny>, value: &Bound<'py, PyAny>) -> PyResult<()> {
self.values.bind(key.py()).set_item(key, value)
}
fn __delitem__(&self, key: &Bound<'_, PyAny>) -> PyResult<()> {
self.values.bind(key.py()).del_item(key)
}
}
#[test]
fn mapping() {
Python::with_gil(|py| {
PyMapping::register::<Mapping>(py).unwrap();
let inst = Py::new(
py,
Mapping {
values: PyDict::new(py).into(),
},
)
.unwrap();
let mapping: &Bound<'_, PyMapping> = inst.bind(py).downcast().unwrap();
py_assert!(py, inst, "len(inst) == 0");
py_run!(py, inst, "inst['foo'] = 'foo'");
py_assert!(py, inst, "inst['foo'] == 'foo'");
py_run!(py, inst, "del inst['foo']");
py_expect_exception!(py, inst, "inst['foo']", PyKeyError);
// Default iteration will call __getitem__ with integer indices
// which fails with a KeyError
py_expect_exception!(py, inst, "[*inst] == []", PyKeyError, "0");
// check mapping protocol
assert_eq!(mapping.len().unwrap(), 0);
mapping.set_item(0, 5).unwrap();
assert_eq!(mapping.len().unwrap(), 1);
assert_eq!(mapping.get_item(0).unwrap().extract::<u8>().unwrap(), 5);
mapping.del_item(0).unwrap();
assert_eq!(mapping.len().unwrap(), 0);
});
}
#[derive(FromPyObject)]
enum SequenceIndex<'py> {
Integer(isize),
Slice(Bound<'py, PySlice>),
}
#[pyclass]
pub struct Sequence {
values: Vec<PyObject>,
}
#[pymethods]
impl Sequence {
fn __len__(&self) -> usize {
self.values.len()
}
fn __getitem__(&self, index: SequenceIndex<'_>, py: Python<'_>) -> PyResult<PyObject> {
match index {
SequenceIndex::Integer(index) => {
let uindex = self.usize_index(index)?;
self.values
.get(uindex)
.map(|o| o.clone_ref(py))
.ok_or_else(|| PyIndexError::new_err(index))
}
// Just to prove that slicing can be implemented
SequenceIndex::Slice(s) => Ok(s.into()),
}
}
fn __setitem__(&mut self, index: isize, value: PyObject) -> PyResult<()> {
let uindex = self.usize_index(index)?;
self.values
.get_mut(uindex)
.map(|place| *place = value)
.ok_or_else(|| PyIndexError::new_err(index))
}
fn __delitem__(&mut self, index: isize) -> PyResult<()> {
let uindex = self.usize_index(index)?;
if uindex >= self.values.len() {
Err(PyIndexError::new_err(index))
} else {
self.values.remove(uindex);
Ok(())
}
}
fn append(&mut self, value: PyObject) {
self.values.push(value);
}
}
impl Sequence {
fn usize_index(&self, index: isize) -> PyResult<usize> {
if index < 0 {
let corrected_index = index + self.values.len() as isize;
if corrected_index < 0 {
Err(PyIndexError::new_err(index))
} else {
Ok(corrected_index as usize)
}
} else {
Ok(index as usize)
}
}
}
#[test]
fn sequence() {
Python::with_gil(|py| {
PySequence::register::<Sequence>(py).unwrap();
let inst = Py::new(py, Sequence { values: vec![] }).unwrap();
let sequence: &Bound<'_, PySequence> = inst.bind(py).downcast().unwrap();
py_assert!(py, inst, "len(inst) == 0");
py_expect_exception!(py, inst, "inst[0]", PyIndexError);
py_run!(py, inst, "inst.append('foo')");
py_assert!(py, inst, "inst[0] == 'foo'");
py_assert!(py, inst, "inst[-1] == 'foo'");
py_expect_exception!(py, inst, "inst[1]", PyIndexError);
py_expect_exception!(py, inst, "inst[-2]", PyIndexError);
py_assert!(py, inst, "[*inst] == ['foo']");
py_run!(py, inst, "del inst[0]");
py_expect_exception!(py, inst, "inst['foo']", PyTypeError);
py_assert!(py, inst, "inst[0:2] == slice(0, 2)");
// check sequence protocol
// we don't implement sequence length so that CPython doesn't attempt to correct negative
// indices.
assert!(sequence.len().is_err());
// however regular python len() works thanks to mp_len slot
assert_eq!(inst.bind(py).len().unwrap(), 0);
py_run!(py, inst, "inst.append(0)");
sequence.set_item(0, 5).unwrap();
assert_eq!(inst.bind(py).len().unwrap(), 1);
assert_eq!(sequence.get_item(0).unwrap().extract::<u8>().unwrap(), 5);
sequence.del_item(0).unwrap();
assert_eq!(inst.bind(py).len().unwrap(), 0);
});
}
#[pyclass]
struct Iterator {
iter: Mutex<Box<dyn iter::Iterator<Item = i32> + Send>>,
}
#[pymethods]
impl Iterator {
fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __next__(slf: PyRefMut<'_, Self>) -> Option<i32> {
slf.iter.lock().unwrap().next()
}
}
#[test]
fn iterator() {
Python::with_gil(|py| {
let inst = Py::new(
py,
Iterator {
iter: Mutex::new(Box::new(5..8)),
},
)
.unwrap();
py_assert!(py, inst, "iter(inst) is inst");
py_assert!(py, inst, "list(inst) == [5, 6, 7]");
});
}
#[pyclass]
struct Callable;
#[pymethods]
impl Callable {
fn __call__(&self, arg: i32) -> i32 {
arg * 6
}
}
#[pyclass]
struct NotCallable;
#[test]
fn callable() {
Python::with_gil(|py| {
let c = Py::new(py, Callable).unwrap();
py_assert!(py, c, "callable(c)");
py_assert!(py, c, "c(7) == 42");
let nc = Py::new(py, NotCallable).unwrap();
py_assert!(py, nc, "not callable(nc)");
});
}
#[pyclass]
#[derive(Debug)]
struct SetItem {
key: i32,
val: i32,
}
#[pymethods]
impl SetItem {
fn __setitem__(&mut self, key: i32, val: i32) {
self.key = key;
self.val = val;
}
}
#[test]
fn setitem() {
Python::with_gil(|py| {
let c = Bound::new(py, SetItem { key: 0, val: 0 }).unwrap();
py_run!(py, c, "c[1] = 2");
{
let c = c.borrow();
assert_eq!(c.key, 1);
assert_eq!(c.val, 2);
}
py_expect_exception!(py, c, "del c[1]", PyNotImplementedError);
});
}
#[pyclass]
struct DelItem {
key: i32,
}
#[pymethods]
impl DelItem {
fn __delitem__(&mut self, key: i32) {
self.key = key;
}
}
#[test]
fn delitem() {
Python::with_gil(|py| {
let c = Bound::new(py, DelItem { key: 0 }).unwrap();
py_run!(py, c, "del c[1]");
{
let c = c.borrow();
assert_eq!(c.key, 1);
}
py_expect_exception!(py, c, "c[1] = 2", PyNotImplementedError);
});
}
#[pyclass]
struct SetDelItem {
val: Option<i32>,
}
#[pymethods]
impl SetDelItem {
fn __setitem__(&mut self, _key: i32, val: i32) {
self.val = Some(val);
}
fn __delitem__(&mut self, _key: i32) {
self.val = None;
}
}
#[test]
fn setdelitem() {
Python::with_gil(|py| {
let c = Bound::new(py, SetDelItem { val: None }).unwrap();
py_run!(py, c, "c[1] = 2");
{
let c = c.borrow();
assert_eq!(c.val, Some(2));
}
py_run!(py, c, "del c[1]");
let c = c.borrow();
assert_eq!(c.val, None);
});
}
#[pyclass]
struct Contains {}
#[pymethods]
impl Contains {
fn __contains__(&self, item: i32) -> bool {
item >= 0
}
}
#[test]
fn contains() {
Python::with_gil(|py| {
let c = Py::new(py, Contains {}).unwrap();
py_run!(py, c, "assert 1 in c");
py_run!(py, c, "assert -1 not in c");
py_expect_exception!(py, c, "assert 'wrong type' not in c", PyTypeError);
});
}
#[pyclass]
struct GetItem {}
#[pymethods]
impl GetItem {
fn __getitem__(&self, idx: &Bound<'_, PyAny>) -> PyResult<&'static str> {
if let Ok(slice) = idx.downcast::<PySlice>() {
let indices = slice.indices(1000)?;
if indices.start == 100 && indices.stop == 200 && indices.step == 1 {
return Ok("slice");
}
} else if let Ok(idx) = idx.extract::<isize>() {
if idx == 1 {
return Ok("int");
}
}
Err(PyValueError::new_err("error"))
}
}
#[test]
fn test_getitem() {
Python::with_gil(|py| {
let ob = Py::new(py, GetItem {}).unwrap();
py_assert!(py, ob, "ob[1] == 'int'");
py_assert!(py, ob, "ob[100:200:1] == 'slice'");
});
}
#[pyclass]
struct ClassWithGetAttr {
#[pyo3(get, set)]
data: u32,
}
#[pymethods]
impl ClassWithGetAttr {
fn __getattr__(&self, _name: &str) -> u32 {
self.data * 2
}
}
#[test]
fn getattr_doesnt_override_member() {
Python::with_gil(|py| {
let inst = Py::new(py, ClassWithGetAttr { data: 4 }).unwrap();
py_assert!(py, inst, "inst.data == 4");
py_assert!(py, inst, "inst.a == 8");
});
}
#[pyclass]
struct ClassWithGetAttribute {
#[pyo3(get, set)]
data: u32,
}
#[pymethods]
impl ClassWithGetAttribute {
fn __getattribute__(&self, _name: &str) -> u32 {
self.data * 2
}
}
#[test]
fn getattribute_overrides_member() {
Python::with_gil(|py| {
let inst = Py::new(py, ClassWithGetAttribute { data: 4 }).unwrap();
py_assert!(py, inst, "inst.data == 8");
py_assert!(py, inst, "inst.y == 8");
});
}
#[pyclass]
struct ClassWithGetAttrAndGetAttribute;
#[pymethods]
impl ClassWithGetAttrAndGetAttribute {
fn __getattribute__(&self, name: &str) -> PyResult<u32> {
if name == "exists" {
Ok(42)
} else if name == "error" {
Err(PyValueError::new_err("bad"))
} else {
Err(PyAttributeError::new_err("fallback"))
}
}
fn __getattr__(&self, name: &str) -> PyResult<u32> {
if name == "lucky" {
Ok(57)
} else {
Err(PyAttributeError::new_err("no chance"))
}
}
}
#[test]
fn getattr_and_getattribute() {
Python::with_gil(|py| {
let inst = Py::new(py, ClassWithGetAttrAndGetAttribute).unwrap();
py_assert!(py, inst, "inst.exists == 42");
py_assert!(py, inst, "inst.lucky == 57");
py_expect_exception!(py, inst, "inst.error", PyValueError);
py_expect_exception!(py, inst, "inst.unlucky", PyAttributeError);
});
}
/// Wraps a Python future and yield it once.
#[pyclass]
#[derive(Debug)]
struct OnceFuture {
future: PyObject,
polled: bool,
}
#[pymethods]
impl OnceFuture {
#[new]
fn new(future: PyObject) -> Self {
OnceFuture {
future,
polled: false,
}
}
fn __await__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __next__<'py>(&mut self, py: Python<'py>) -> Option<&Bound<'py, PyAny>> {
if !self.polled {
self.polled = true;
Some(self.future.bind(py))
} else {
None
}
}
}
#[test]
#[cfg(not(target_arch = "wasm32"))] // Won't work without wasm32 event loop (e.g., Pyodide has WebLoop)
fn test_await() {
Python::with_gil(|py| {
let once = py.get_type::<OnceFuture>();
let source = pyo3_ffi::c_str!(
r#"
import asyncio
import sys
async def main():
res = await Once(await asyncio.sleep(0.1))
assert res is None
# For an odd error similar to https://bugs.python.org/issue38563
if sys.platform == "win32" and sys.version_info >= (3, 8, 0):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
"#
);
let globals = PyModule::import(py, "__main__").unwrap().dict();
globals.set_item("Once", once).unwrap();
py.run(source, Some(&globals), None)
.map_err(|e| e.display(py))
.unwrap();
});
}
#[pyclass]
struct AsyncIterator {
future: Option<Py<OnceFuture>>,
}
#[pymethods]
impl AsyncIterator {
#[new]
fn new(future: Py<OnceFuture>) -> Self {
Self {
future: Some(future),
}
}
fn __aiter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
slf
}
fn __anext__(&mut self) -> Option<Py<OnceFuture>> {
self.future.take()
}
}
#[test]
#[cfg(not(target_arch = "wasm32"))] // Won't work without wasm32 event loop (e.g., Pyodide has WebLoop)
fn test_anext_aiter() {
Python::with_gil(|py| {
let once = py.get_type::<OnceFuture>();
let source = pyo3_ffi::c_str!(
r#"
import asyncio
import sys
async def main():
count = 0
async for result in AsyncIterator(Once(await asyncio.sleep(0.1))):
# The Once is awaited as part of the `async for` and produces None
assert result is None
count +=1
assert count == 1
# For an odd error similar to https://bugs.python.org/issue38563
if sys.platform == "win32" and sys.version_info >= (3, 8, 0):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
"#
);
let globals = PyModule::import(py, "__main__").unwrap().dict();
globals.set_item("Once", once).unwrap();
globals
.set_item("AsyncIterator", py.get_type::<AsyncIterator>())
.unwrap();
py.run(source, Some(&globals), None)
.map_err(|e| e.display(py))
.unwrap();
});
}
/// Increment the count when `__get__` is called.
#[pyclass]
struct DescrCounter {
#[pyo3(get)]
count: usize,
}
#[pymethods]
impl DescrCounter {
#[new]
fn new() -> Self {
DescrCounter { count: 0 }
}
/// Each access will increase the count
fn __get__<'a>(
mut slf: PyRefMut<'a, Self>,
_instance: &Bound<'_, PyAny>,
_owner: Option<&Bound<'_, PyType>>,
) -> PyRefMut<'a, Self> {
slf.count += 1;
slf
}
/// Allow assigning a new counter to the descriptor, copying the count across
fn __set__(&self, _instance: &Bound<'_, PyAny>, new_value: &mut Self) {
new_value.count = self.count;
}
/// Delete to reset the counter
fn __delete__(&mut self, _instance: &Bound<'_, PyAny>) {
self.count = 0;
}
}
#[test]
fn descr_getset() {
Python::with_gil(|py| {
let counter = py.get_type::<DescrCounter>();
let source = pyo3_ffi::c_str!(pyo3::indoc::indoc!(
r#"
class Class:
counter = Counter()
# access via type
counter = Class.counter
assert counter.count == 1
# access with instance directly
assert Counter.__get__(counter, Class()).count == 2
# access via instance
c = Class()
assert c.counter.count == 3
# __set__
c.counter = Counter()
assert c.counter.count == 4
# __delete__
del c.counter
assert c.counter.count == 1
"#
));
let globals = PyModule::import(py, "__main__").unwrap().dict();
globals.set_item("Counter", counter).unwrap();
py.run(source, Some(&globals), None)
.map_err(|e| e.display(py))
.unwrap();
});
}
#[pyclass]
struct NotHashable;
#[pymethods]
impl NotHashable {
#[classattr]
const __hash__: Option<PyObject> = None;
}
#[test]
fn test_hash_opt_out() {
// By default Python provides a hash implementation, which can be disabled by setting __hash__
// to None.
Python::with_gil(|py| {
let empty = Py::new(py, EmptyClass).unwrap();
py_assert!(py, empty, "hash(empty) is not None");
let not_hashable = Py::new(py, NotHashable).unwrap();
py_expect_exception!(py, not_hashable, "hash(not_hashable)", PyTypeError);
})
}
/// Class with __iter__ gets default contains from CPython.
#[pyclass]
struct DefaultedContains;
#[pymethods]
impl DefaultedContains {
fn __iter__(&self, py: Python<'_>) -> PyObject {
PyList::new(py, ["a", "b", "c"])
.unwrap()
.as_ref()
.try_iter()
.unwrap()
.into()
}
}
#[pyclass]
struct NoContains;
#[pymethods]
impl NoContains {
fn __iter__(&self, py: Python<'_>) -> PyObject {
PyList::new(py, ["a", "b", "c"])
.unwrap()
.as_ref()
.try_iter()
.unwrap()
.into()
}
// Equivalent to the opt-out const form in NotHashable above, just more verbose, to confirm this
// also works.
#[classattr]
fn __contains__() -> Option<PyObject> {
None
}
}
#[test]
fn test_contains_opt_out() {
Python::with_gil(|py| {
let defaulted_contains = Py::new(py, DefaultedContains).unwrap();
py_assert!(py, defaulted_contains, "'a' in defaulted_contains");
let no_contains = Py::new(py, NoContains).unwrap();
py_expect_exception!(py, no_contains, "'a' in no_contains", PyTypeError);
})
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_text_signature.rs | #![cfg(feature = "macros")]
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyTuple};
use pyo3::{types::PyType, wrap_pymodule};
#[path = "../src/tests/common.rs"]
mod common;
#[test]
fn class_without_docs_or_signature() {
#[pyclass]
struct MyClass {}
Python::with_gil(|py| {
let typeobj = py.get_type::<MyClass>();
py_assert!(py, typeobj, "typeobj.__doc__ is None");
py_assert!(py, typeobj, "typeobj.__text_signature__ is None");
});
}
#[test]
fn class_with_docs() {
/// docs line1
#[pyclass]
/// docs line2
struct MyClass {}
Python::with_gil(|py| {
let typeobj = py.get_type::<MyClass>();
py_assert!(py, typeobj, "typeobj.__doc__ == 'docs line1\\ndocs line2'");
py_assert!(py, typeobj, "typeobj.__text_signature__ is None");
});
}
#[test]
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_10)), ignore)]
fn class_with_signature_no_doc() {
#[pyclass]
struct MyClass {}
#[pymethods]
impl MyClass {
#[new]
#[pyo3(signature = (a, b=None, *, c=42), text_signature = "(a, b=None, *, c=42)")]
fn __new__(a: i32, b: Option<i32>, c: i32) -> Self {
let _ = (a, b, c);
Self {}
}
}
Python::with_gil(|py| {
let typeobj = py.get_type::<MyClass>();
py_assert!(py, typeobj, "typeobj.__doc__ == ''");
py_assert!(
py,
typeobj,
"typeobj.__text_signature__ == '(a, b=None, *, c=42)'"
);
});
}
#[test]
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_10)), ignore)]
fn class_with_docs_and_signature() {
/// docs line1
#[pyclass]
/// docs line2
struct MyClass {}
#[pymethods]
impl MyClass {
#[new]
#[pyo3(signature = (a, b=None, *, c=42), text_signature = "(a, b=None, *, c=42)")]
fn __new__(a: i32, b: Option<i32>, c: i32) -> Self {
let _ = (a, b, c);
Self {}
}
}
Python::with_gil(|py| {
let typeobj = py.get_type::<MyClass>();
py_assert!(py, typeobj, "typeobj.__doc__ == 'docs line1\\ndocs line2'");
py_assert!(
py,
typeobj,
"typeobj.__text_signature__ == '(a, b=None, *, c=42)'"
);
});
}
#[test]
fn test_function() {
#[pyfunction(signature = (a, b=None, *, c=42))]
#[pyo3(text_signature = "(a, b=None, *, c=42)")]
fn my_function(a: i32, b: Option<i32>, c: i32) {
let _ = (a, b, c);
}
Python::with_gil(|py| {
let f = wrap_pyfunction!(my_function)(py).unwrap();
py_assert!(py, f, "f.__text_signature__ == '(a, b=None, *, c=42)'");
});
}
#[test]
fn test_auto_test_signature_function() {
#[pyfunction]
fn my_function(a: i32, b: i32, c: i32) {
let _ = (a, b, c);
}
#[pyfunction(pass_module)]
fn my_function_2(module: &Bound<'_, PyModule>, a: i32, b: i32, c: i32) {
let _ = (module, a, b, c);
}
#[pyfunction(signature = (a, /, b = None, *, c = 5))]
fn my_function_3(a: i32, b: Option<i32>, c: i32) {
let _ = (a, b, c);
}
#[pyfunction(signature = (a, /, b = None, *args, c, d=5, **kwargs))]
fn my_function_4(
a: i32,
b: Option<i32>,
args: &Bound<'_, PyTuple>,
c: i32,
d: i32,
kwargs: Option<&Bound<'_, PyDict>>,
) {
let _ = (a, b, args, c, d, kwargs);
}
#[pyfunction(signature = (a = 1, /, b = None, c = 1.5, d=5, e = "pyo3", f = 'f', h = true))]
fn my_function_5(a: i32, b: Option<i32>, c: f32, d: i32, e: &str, f: char, h: bool) {
let _ = (a, b, c, d, e, f, h);
}
#[pyfunction]
#[pyo3(signature=(a, b=None, c=None))]
fn my_function_6(a: i32, b: Option<i32>, c: Option<i32>) {
let _ = (a, b, c);
}
Python::with_gil(|py| {
let f = wrap_pyfunction!(my_function)(py).unwrap();
py_assert!(
py,
f,
"f.__text_signature__ == '(a, b, c)', f.__text_signature__"
);
let f = wrap_pyfunction!(my_function_2)(py).unwrap();
py_assert!(
py,
f,
"f.__text_signature__ == '($module, a, b, c)', f.__text_signature__"
);
let f = wrap_pyfunction!(my_function_3)(py).unwrap();
py_assert!(
py,
f,
"f.__text_signature__ == '(a, /, b=None, *, c=5)', f.__text_signature__"
);
let f = wrap_pyfunction!(my_function_4)(py).unwrap();
py_assert!(
py,
f,
"f.__text_signature__ == '(a, /, b=None, *args, c, d=5, **kwargs)', f.__text_signature__"
);
let f = wrap_pyfunction!(my_function_5)(py).unwrap();
py_assert!(
py,
f,
"f.__text_signature__ == '(a=1, /, b=None, c=1.5, d=5, e=\"pyo3\", f=\\'f\\', h=True)', f.__text_signature__"
);
let f = wrap_pyfunction!(my_function_6)(py).unwrap();
py_assert!(
py,
f,
"f.__text_signature__ == '(a, b=None, c=None)', f.__text_signature__"
);
});
}
#[test]
fn test_auto_test_signature_method() {
#[pyclass]
struct MyClass {}
#[pymethods]
impl MyClass {
#[new]
fn new(a: i32, b: i32, c: i32) -> Self {
let _ = (a, b, c);
Self {}
}
fn method(&self, a: i32, b: i32, c: i32) {
let _ = (a, b, c);
}
#[pyo3(signature = (a, /, b = None, *, c = 5))]
fn method_2(&self, a: i32, b: Option<i32>, c: i32) {
let _ = (a, b, c);
}
#[pyo3(signature = (a, /, b = None, *args, c, d=5, **kwargs))]
fn method_3(
&self,
a: i32,
b: Option<i32>,
args: &Bound<'_, PyTuple>,
c: i32,
d: i32,
kwargs: Option<&Bound<'_, PyDict>>,
) {
let _ = (a, b, args, c, d, kwargs);
}
#[staticmethod]
fn staticmethod(a: i32, b: i32, c: i32) {
let _ = (a, b, c);
}
#[classmethod]
fn classmethod(cls: &Bound<'_, PyType>, a: i32, b: i32, c: i32) {
let _ = (cls, a, b, c);
}
}
Python::with_gil(|py| {
let cls = py.get_type::<MyClass>();
#[cfg(any(not(Py_LIMITED_API), Py_3_10))]
py_assert!(py, cls, "cls.__text_signature__ == '(a, b, c)'");
py_assert!(
py,
cls,
"cls.method.__text_signature__ == '($self, a, b, c)'"
);
py_assert!(
py,
cls,
"cls.method_2.__text_signature__ == '($self, a, /, b=None, *, c=5)'"
);
py_assert!(
py,
cls,
"cls.method_3.__text_signature__ == '($self, a, /, b=None, *args, c, d=5, **kwargs)'"
);
py_assert!(
py,
cls,
"cls.staticmethod.__text_signature__ == '(a, b, c)'"
);
py_assert!(
py,
cls,
"cls.classmethod.__text_signature__ == '($cls, a, b, c)'"
);
});
}
#[test]
fn test_auto_test_signature_opt_out() {
#[pyfunction(text_signature = None)]
fn my_function(a: i32, b: i32, c: i32) {
let _ = (a, b, c);
}
#[pyfunction(signature = (a, /, b = None, *, c = 5), text_signature = None)]
fn my_function_2(a: i32, b: Option<i32>, c: i32) {
let _ = (a, b, c);
}
#[pyclass]
struct MyClass {}
#[pymethods]
impl MyClass {
#[new]
#[pyo3(text_signature = None)]
fn new(a: i32, b: i32, c: i32) -> Self {
let _ = (a, b, c);
Self {}
}
#[pyo3(text_signature = None)]
fn method(&self, a: i32, b: i32, c: i32) {
let _ = (a, b, c);
}
#[pyo3(signature = (a, /, b = None, *, c = 5), text_signature = None)]
fn method_2(&self, a: i32, b: Option<i32>, c: i32) {
let _ = (a, b, c);
}
#[staticmethod]
#[pyo3(text_signature = None)]
fn staticmethod(a: i32, b: i32, c: i32) {
let _ = (a, b, c);
}
#[classmethod]
#[pyo3(text_signature = None)]
fn classmethod(cls: &Bound<'_, PyType>, a: i32, b: i32, c: i32) {
let _ = (cls, a, b, c);
}
}
Python::with_gil(|py| {
let f = wrap_pyfunction!(my_function)(py).unwrap();
py_assert!(py, f, "f.__text_signature__ == None");
let f = wrap_pyfunction!(my_function_2)(py).unwrap();
py_assert!(py, f, "f.__text_signature__ == None");
let cls = py.get_type::<MyClass>();
py_assert!(py, cls, "cls.__text_signature__ == None");
py_assert!(py, cls, "cls.method.__text_signature__ == None");
py_assert!(py, cls, "cls.method_2.__text_signature__ == None");
py_assert!(py, cls, "cls.staticmethod.__text_signature__ == None");
py_assert!(py, cls, "cls.classmethod.__text_signature__ == None");
});
}
#[test]
fn test_pyfn() {
#[pymodule]
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
#[pyfn(m, signature = (a, b=None, *, c=42))]
#[pyo3(text_signature = "(a, b=None, *, c=42)")]
fn my_function(a: i32, b: Option<i32>, c: i32) {
let _ = (a, b, c);
}
Ok(())
}
Python::with_gil(|py| {
let m = wrap_pymodule!(my_module)(py);
py_assert!(
py,
m,
"m.my_function.__text_signature__ == '(a, b=None, *, c=42)'"
);
});
}
#[test]
fn test_methods() {
#[pyclass]
struct MyClass {}
#[pymethods]
impl MyClass {
#[pyo3(text_signature = "($self, a)")]
fn method(&self, a: i32) {
let _ = a;
}
#[pyo3(text_signature = "($self, b)")]
fn pyself_method(_this: &Bound<'_, Self>, b: i32) {
let _ = b;
}
#[classmethod]
#[pyo3(text_signature = "($cls, c)")]
fn class_method(_cls: &Bound<'_, PyType>, c: i32) {
let _ = c;
}
#[staticmethod]
#[pyo3(text_signature = "(d)")]
fn static_method(d: i32) {
let _ = d;
}
}
Python::with_gil(|py| {
let typeobj = py.get_type::<MyClass>();
py_assert!(
py,
typeobj,
"typeobj.method.__text_signature__ == '($self, a)'"
);
py_assert!(
py,
typeobj,
"typeobj.pyself_method.__text_signature__ == '($self, b)'"
);
py_assert!(
py,
typeobj,
"typeobj.class_method.__text_signature__ == '($cls, c)'"
);
py_assert!(
py,
typeobj,
"typeobj.static_method.__text_signature__ == '(d)'"
);
});
}
#[test]
#[cfg_attr(all(Py_LIMITED_API, not(Py_3_10)), ignore)]
fn test_raw_identifiers() {
#[pyclass]
struct r#MyClass {}
#[pymethods]
impl MyClass {
#[new]
fn new() -> MyClass {
MyClass {}
}
fn r#method(&self) {}
}
Python::with_gil(|py| {
let typeobj = py.get_type::<MyClass>();
py_assert!(py, typeobj, "typeobj.__text_signature__ == '()'");
py_assert!(
py,
typeobj,
"typeobj.method.__text_signature__ == '($self)'"
);
});
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_arithmetics.rs | #![cfg(feature = "macros")]
use pyo3::class::basic::CompareOp;
use pyo3::py_run;
use pyo3::{prelude::*, BoundObject};
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
struct UnaryArithmetic {
inner: f64,
}
#[pymethods]
impl UnaryArithmetic {
#[new]
fn new(value: f64) -> Self {
UnaryArithmetic { inner: value }
}
fn __repr__(&self) -> String {
format!("UA({})", self.inner)
}
fn __neg__(&self) -> Self {
Self::new(-self.inner)
}
fn __pos__(&self) -> Self {
Self::new(self.inner)
}
fn __abs__(&self) -> Self {
Self::new(self.inner.abs())
}
fn __invert__(&self) -> Self {
Self::new(self.inner.recip())
}
#[pyo3(signature=(_ndigits=None))]
fn __round__(&self, _ndigits: Option<u32>) -> Self {
Self::new(self.inner.round())
}
}
#[test]
fn unary_arithmetic() {
Python::with_gil(|py| {
let c = Py::new(py, UnaryArithmetic::new(2.7)).unwrap();
py_run!(py, c, "assert repr(-c) == 'UA(-2.7)'");
py_run!(py, c, "assert repr(+c) == 'UA(2.7)'");
py_run!(py, c, "assert repr(abs(c)) == 'UA(2.7)'");
py_run!(py, c, "assert repr(~c) == 'UA(0.37037037037037035)'");
py_run!(py, c, "assert repr(round(c)) == 'UA(3)'");
py_run!(py, c, "assert repr(round(c, 1)) == 'UA(3)'");
let c: Bound<'_, PyAny> = c.extract(py).unwrap();
assert_py_eq!(c.neg().unwrap().repr().unwrap().as_any(), "UA(-2.7)");
assert_py_eq!(c.pos().unwrap().repr().unwrap().as_any(), "UA(2.7)");
assert_py_eq!(c.abs().unwrap().repr().unwrap().as_any(), "UA(2.7)");
assert_py_eq!(
c.bitnot().unwrap().repr().unwrap().as_any(),
"UA(0.37037037037037035)"
);
});
}
#[pyclass]
struct Indexable(i32);
#[pymethods]
impl Indexable {
fn __index__(&self) -> i32 {
self.0
}
fn __int__(&self) -> i32 {
self.0
}
fn __float__(&self) -> f64 {
f64::from(self.0)
}
fn __invert__(&self) -> Self {
Self(!self.0)
}
}
#[test]
fn indexable() {
Python::with_gil(|py| {
let i = Py::new(py, Indexable(5)).unwrap();
py_run!(py, i, "assert int(i) == 5");
py_run!(py, i, "assert [0, 1, 2, 3, 4, 5][i] == 5");
py_run!(py, i, "assert float(i) == 5.0");
py_run!(py, i, "assert int(~i) == -6");
})
}
#[pyclass]
struct InPlaceOperations {
value: u32,
}
#[pymethods]
impl InPlaceOperations {
fn __repr__(&self) -> String {
format!("IPO({:?})", self.value)
}
fn __iadd__(&mut self, other: u32) {
self.value += other;
}
fn __isub__(&mut self, other: u32) {
self.value -= other;
}
fn __imul__(&mut self, other: u32) {
self.value *= other;
}
fn __ilshift__(&mut self, other: u32) {
self.value <<= other;
}
fn __irshift__(&mut self, other: u32) {
self.value >>= other;
}
fn __iand__(&mut self, other: u32) {
self.value &= other;
}
fn __ixor__(&mut self, other: u32) {
self.value ^= other;
}
fn __ior__(&mut self, other: u32) {
self.value |= other;
}
fn __ipow__(&mut self, other: u32, _modulo: Option<u32>) {
self.value = self.value.pow(other);
}
}
#[test]
fn inplace_operations() {
Python::with_gil(|py| {
let init = |value, code| {
let c = Py::new(py, InPlaceOperations { value }).unwrap();
py_run!(py, c, code);
};
init(0, "d = c; c += 1; assert repr(c) == repr(d) == 'IPO(1)'");
init(10, "d = c; c -= 1; assert repr(c) == repr(d) == 'IPO(9)'");
init(3, "d = c; c *= 3; assert repr(c) == repr(d) == 'IPO(9)'");
init(3, "d = c; c <<= 2; assert repr(c) == repr(d) == 'IPO(12)'");
init(12, "d = c; c >>= 2; assert repr(c) == repr(d) == 'IPO(3)'");
init(12, "d = c; c &= 10; assert repr(c) == repr(d) == 'IPO(8)'");
init(12, "d = c; c |= 3; assert repr(c) == repr(d) == 'IPO(15)'");
init(12, "d = c; c ^= 5; assert repr(c) == repr(d) == 'IPO(9)'");
init(3, "d = c; c **= 4; assert repr(c) == repr(d) == 'IPO(81)'");
init(
3,
"d = c; c.__ipow__(4); assert repr(c) == repr(d) == 'IPO(81)'",
);
});
}
#[pyclass]
struct BinaryArithmetic {}
#[pymethods]
impl BinaryArithmetic {
fn __repr__(&self) -> &'static str {
"BA"
}
fn __add__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA + {:?}", rhs)
}
fn __sub__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA - {:?}", rhs)
}
fn __mul__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA * {:?}", rhs)
}
fn __matmul__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA @ {:?}", rhs)
}
fn __truediv__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA / {:?}", rhs)
}
fn __floordiv__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA // {:?}", rhs)
}
fn __mod__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA % {:?}", rhs)
}
fn __divmod__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("divmod(BA, {:?})", rhs)
}
fn __lshift__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA << {:?}", rhs)
}
fn __rshift__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA >> {:?}", rhs)
}
fn __and__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA & {:?}", rhs)
}
fn __xor__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA ^ {:?}", rhs)
}
fn __or__(&self, rhs: &Bound<'_, PyAny>) -> String {
format!("BA | {:?}", rhs)
}
fn __pow__(&self, rhs: &Bound<'_, PyAny>, mod_: Option<u32>) -> String {
format!("BA ** {:?} (mod: {:?})", rhs, mod_)
}
}
#[test]
fn binary_arithmetic() {
Python::with_gil(|py| {
let c = Py::new(py, BinaryArithmetic {}).unwrap();
py_run!(py, c, "assert c + c == 'BA + BA'");
py_run!(py, c, "assert c.__add__(c) == 'BA + BA'");
py_run!(py, c, "assert c + 1 == 'BA + 1'");
py_run!(py, c, "assert c - 1 == 'BA - 1'");
py_run!(py, c, "assert c * 1 == 'BA * 1'");
py_run!(py, c, "assert c @ 1 == 'BA @ 1'");
py_run!(py, c, "assert c / 1 == 'BA / 1'");
py_run!(py, c, "assert c // 1 == 'BA // 1'");
py_run!(py, c, "assert c % 1 == 'BA % 1'");
py_run!(py, c, "assert divmod(c, 1) == 'divmod(BA, 1)'");
py_run!(py, c, "assert c << 1 == 'BA << 1'");
py_run!(py, c, "assert c >> 1 == 'BA >> 1'");
py_run!(py, c, "assert c & 1 == 'BA & 1'");
py_run!(py, c, "assert c ^ 1 == 'BA ^ 1'");
py_run!(py, c, "assert c | 1 == 'BA | 1'");
py_run!(py, c, "assert c ** 1 == 'BA ** 1 (mod: None)'");
// Class with __add__ only should not allow the reverse op;
// this is consistent with Python classes.
py_expect_exception!(py, c, "1 + c", PyTypeError);
py_expect_exception!(py, c, "1 - c", PyTypeError);
py_expect_exception!(py, c, "1 * c", PyTypeError);
py_expect_exception!(py, c, "1 @ c", PyTypeError);
py_expect_exception!(py, c, "1 / c", PyTypeError);
py_expect_exception!(py, c, "1 // c", PyTypeError);
py_expect_exception!(py, c, "1 % c", PyTypeError);
py_expect_exception!(py, c, "divmod(1, c)", PyTypeError);
py_expect_exception!(py, c, "1 << c", PyTypeError);
py_expect_exception!(py, c, "1 >> c", PyTypeError);
py_expect_exception!(py, c, "1 & c", PyTypeError);
py_expect_exception!(py, c, "1 ^ c", PyTypeError);
py_expect_exception!(py, c, "1 | c", PyTypeError);
py_expect_exception!(py, c, "1 ** c", PyTypeError);
py_run!(py, c, "assert pow(c, 1, 100) == 'BA ** 1 (mod: Some(100))'");
let c: Bound<'_, PyAny> = c.extract(py).unwrap();
assert_py_eq!(c.add(&c).unwrap(), "BA + BA");
assert_py_eq!(c.sub(&c).unwrap(), "BA - BA");
assert_py_eq!(c.mul(&c).unwrap(), "BA * BA");
assert_py_eq!(c.matmul(&c).unwrap(), "BA @ BA");
assert_py_eq!(c.div(&c).unwrap(), "BA / BA");
assert_py_eq!(c.floor_div(&c).unwrap(), "BA // BA");
assert_py_eq!(c.rem(&c).unwrap(), "BA % BA");
assert_py_eq!(c.divmod(&c).unwrap(), "divmod(BA, BA)");
assert_py_eq!(c.lshift(&c).unwrap(), "BA << BA");
assert_py_eq!(c.rshift(&c).unwrap(), "BA >> BA");
assert_py_eq!(c.bitand(&c).unwrap(), "BA & BA");
assert_py_eq!(c.bitor(&c).unwrap(), "BA | BA");
assert_py_eq!(c.bitxor(&c).unwrap(), "BA ^ BA");
assert_py_eq!(c.pow(&c, py.None()).unwrap(), "BA ** BA (mod: None)");
});
}
#[pyclass]
struct RhsArithmetic {}
#[pymethods]
impl RhsArithmetic {
fn __radd__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} + RA", other)
}
fn __rsub__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} - RA", other)
}
fn __rmul__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} * RA", other)
}
fn __rlshift__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} << RA", other)
}
fn __rrshift__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} >> RA", other)
}
fn __rand__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} & RA", other)
}
fn __rxor__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} ^ RA", other)
}
fn __ror__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} | RA", other)
}
fn __rpow__(&self, other: &Bound<'_, PyAny>, _mod: Option<&Bound<'_, PyAny>>) -> String {
format!("{:?} ** RA", other)
}
}
#[test]
fn rhs_arithmetic() {
Python::with_gil(|py| {
let c = Py::new(py, RhsArithmetic {}).unwrap();
py_run!(py, c, "assert c.__radd__(1) == '1 + RA'");
py_run!(py, c, "assert 1 + c == '1 + RA'");
py_run!(py, c, "assert c.__rsub__(1) == '1 - RA'");
py_run!(py, c, "assert 1 - c == '1 - RA'");
py_run!(py, c, "assert c.__rmul__(1) == '1 * RA'");
py_run!(py, c, "assert 1 * c == '1 * RA'");
py_run!(py, c, "assert c.__rlshift__(1) == '1 << RA'");
py_run!(py, c, "assert 1 << c == '1 << RA'");
py_run!(py, c, "assert c.__rrshift__(1) == '1 >> RA'");
py_run!(py, c, "assert 1 >> c == '1 >> RA'");
py_run!(py, c, "assert c.__rand__(1) == '1 & RA'");
py_run!(py, c, "assert 1 & c == '1 & RA'");
py_run!(py, c, "assert c.__rxor__(1) == '1 ^ RA'");
py_run!(py, c, "assert 1 ^ c == '1 ^ RA'");
py_run!(py, c, "assert c.__ror__(1) == '1 | RA'");
py_run!(py, c, "assert 1 | c == '1 | RA'");
py_run!(py, c, "assert c.__rpow__(1) == '1 ** RA'");
py_run!(py, c, "assert 1 ** c == '1 ** RA'");
});
}
#[pyclass]
struct LhsAndRhs {}
impl std::fmt::Debug for LhsAndRhs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "LR")
}
}
#[pymethods]
impl LhsAndRhs {
// fn __repr__(&self) -> &'static str {
// "BA"
// }
fn __add__(lhs: PyRef<'_, Self>, rhs: &Bound<'_, PyAny>) -> String {
format!("{:?} + {:?}", lhs, rhs)
}
fn __sub__(lhs: PyRef<'_, Self>, rhs: &Bound<'_, PyAny>) -> String {
format!("{:?} - {:?}", lhs, rhs)
}
fn __mul__(lhs: PyRef<'_, Self>, rhs: &Bound<'_, PyAny>) -> String {
format!("{:?} * {:?}", lhs, rhs)
}
fn __lshift__(lhs: PyRef<'_, Self>, rhs: &Bound<'_, PyAny>) -> String {
format!("{:?} << {:?}", lhs, rhs)
}
fn __rshift__(lhs: PyRef<'_, Self>, rhs: &Bound<'_, PyAny>) -> String {
format!("{:?} >> {:?}", lhs, rhs)
}
fn __and__(lhs: PyRef<'_, Self>, rhs: &Bound<'_, PyAny>) -> String {
format!("{:?} & {:?}", lhs, rhs)
}
fn __xor__(lhs: PyRef<'_, Self>, rhs: &Bound<'_, PyAny>) -> String {
format!("{:?} ^ {:?}", lhs, rhs)
}
fn __or__(lhs: PyRef<'_, Self>, rhs: &Bound<'_, PyAny>) -> String {
format!("{:?} | {:?}", lhs, rhs)
}
fn __pow__(lhs: PyRef<'_, Self>, rhs: &Bound<'_, PyAny>, _mod: Option<usize>) -> String {
format!("{:?} ** {:?}", lhs, rhs)
}
fn __matmul__(lhs: PyRef<'_, Self>, rhs: &Bound<'_, PyAny>) -> String {
format!("{:?} @ {:?}", lhs, rhs)
}
fn __radd__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} + RA", other)
}
fn __rsub__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} - RA", other)
}
fn __rmul__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} * RA", other)
}
fn __rlshift__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} << RA", other)
}
fn __rrshift__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} >> RA", other)
}
fn __rand__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} & RA", other)
}
fn __rxor__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} ^ RA", other)
}
fn __ror__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} | RA", other)
}
fn __rpow__(&self, other: &Bound<'_, PyAny>, _mod: Option<&Bound<'_, PyAny>>) -> String {
format!("{:?} ** RA", other)
}
fn __rmatmul__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} @ RA", other)
}
fn __rtruediv__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} / RA", other)
}
fn __rfloordiv__(&self, other: &Bound<'_, PyAny>) -> String {
format!("{:?} // RA", other)
}
}
#[test]
fn lhs_fellback_to_rhs() {
Python::with_gil(|py| {
let c = Py::new(py, LhsAndRhs {}).unwrap();
// If the light hand value is `LhsAndRhs`, LHS is used.
py_run!(py, c, "assert c + 1 == 'LR + 1'");
py_run!(py, c, "assert c - 1 == 'LR - 1'");
py_run!(py, c, "assert c * 1 == 'LR * 1'");
py_run!(py, c, "assert c << 1 == 'LR << 1'");
py_run!(py, c, "assert c >> 1 == 'LR >> 1'");
py_run!(py, c, "assert c & 1 == 'LR & 1'");
py_run!(py, c, "assert c ^ 1 == 'LR ^ 1'");
py_run!(py, c, "assert c | 1 == 'LR | 1'");
py_run!(py, c, "assert c ** 1 == 'LR ** 1'");
py_run!(py, c, "assert c @ 1 == 'LR @ 1'");
// Fellback to RHS because of type mismatching
py_run!(py, c, "assert 1 + c == '1 + RA'");
py_run!(py, c, "assert 1 - c == '1 - RA'");
py_run!(py, c, "assert 1 * c == '1 * RA'");
py_run!(py, c, "assert 1 << c == '1 << RA'");
py_run!(py, c, "assert 1 >> c == '1 >> RA'");
py_run!(py, c, "assert 1 & c == '1 & RA'");
py_run!(py, c, "assert 1 ^ c == '1 ^ RA'");
py_run!(py, c, "assert 1 | c == '1 | RA'");
py_run!(py, c, "assert 1 ** c == '1 ** RA'");
py_run!(py, c, "assert 1 @ c == '1 @ RA'");
});
}
#[pyclass]
struct RichComparisons {}
#[pymethods]
impl RichComparisons {
fn __repr__(&self) -> &'static str {
"RC"
}
fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> String {
match op {
CompareOp::Lt => format!("{} < {:?}", self.__repr__(), other),
CompareOp::Le => format!("{} <= {:?}", self.__repr__(), other),
CompareOp::Eq => format!("{} == {:?}", self.__repr__(), other),
CompareOp::Ne => format!("{} != {:?}", self.__repr__(), other),
CompareOp::Gt => format!("{} > {:?}", self.__repr__(), other),
CompareOp::Ge => format!("{} >= {:?}", self.__repr__(), other),
}
}
}
#[pyclass]
struct RichComparisons2 {}
#[pymethods]
impl RichComparisons2 {
fn __repr__(&self) -> &'static str {
"RC2"
}
fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<PyObject> {
match op {
CompareOp::Eq => true
.into_pyobject(other.py())
.map_err(Into::into)
.map(BoundObject::into_any)
.map(BoundObject::unbind),
CompareOp::Ne => false
.into_pyobject(other.py())
.map_err(Into::into)
.map(BoundObject::into_any)
.map(BoundObject::unbind),
_ => Ok(other.py().NotImplemented()),
}
}
}
#[test]
fn rich_comparisons() {
Python::with_gil(|py| {
let c = Py::new(py, RichComparisons {}).unwrap();
py_run!(py, c, "assert (c < c) == 'RC < RC'");
py_run!(py, c, "assert (c < 1) == 'RC < 1'");
py_run!(py, c, "assert (1 < c) == 'RC > 1'");
py_run!(py, c, "assert (c <= c) == 'RC <= RC'");
py_run!(py, c, "assert (c <= 1) == 'RC <= 1'");
py_run!(py, c, "assert (1 <= c) == 'RC >= 1'");
py_run!(py, c, "assert (c == c) == 'RC == RC'");
py_run!(py, c, "assert (c == 1) == 'RC == 1'");
py_run!(py, c, "assert (1 == c) == 'RC == 1'");
py_run!(py, c, "assert (c != c) == 'RC != RC'");
py_run!(py, c, "assert (c != 1) == 'RC != 1'");
py_run!(py, c, "assert (1 != c) == 'RC != 1'");
py_run!(py, c, "assert (c > c) == 'RC > RC'");
py_run!(py, c, "assert (c > 1) == 'RC > 1'");
py_run!(py, c, "assert (1 > c) == 'RC < 1'");
py_run!(py, c, "assert (c >= c) == 'RC >= RC'");
py_run!(py, c, "assert (c >= 1) == 'RC >= 1'");
py_run!(py, c, "assert (1 >= c) == 'RC <= 1'");
});
}
#[test]
fn rich_comparisons_python_3_type_error() {
Python::with_gil(|py| {
let c2 = Py::new(py, RichComparisons2 {}).unwrap();
py_expect_exception!(py, c2, "c2 < c2", PyTypeError);
py_expect_exception!(py, c2, "c2 < 1", PyTypeError);
py_expect_exception!(py, c2, "1 < c2", PyTypeError);
py_expect_exception!(py, c2, "c2 <= c2", PyTypeError);
py_expect_exception!(py, c2, "c2 <= 1", PyTypeError);
py_expect_exception!(py, c2, "1 <= c2", PyTypeError);
py_run!(py, c2, "assert (c2 == c2) == True");
py_run!(py, c2, "assert (c2 == 1) == True");
py_run!(py, c2, "assert (1 == c2) == True");
py_run!(py, c2, "assert (c2 != c2) == False");
py_run!(py, c2, "assert (c2 != 1) == False");
py_run!(py, c2, "assert (1 != c2) == False");
py_expect_exception!(py, c2, "c2 > c2", PyTypeError);
py_expect_exception!(py, c2, "c2 > 1", PyTypeError);
py_expect_exception!(py, c2, "1 > c2", PyTypeError);
py_expect_exception!(py, c2, "c2 >= c2", PyTypeError);
py_expect_exception!(py, c2, "c2 >= 1", PyTypeError);
py_expect_exception!(py, c2, "1 >= c2", PyTypeError);
});
}
// Checks that binary operations for which the arguments don't match the
// required type, return NotImplemented.
mod return_not_implemented {
use super::*;
#[pyclass]
struct RichComparisonToSelf {}
#[pymethods]
impl RichComparisonToSelf {
fn __repr__(&self) -> &'static str {
"RC_Self"
}
fn __richcmp__(&self, other: PyRef<'_, Self>, _op: CompareOp) -> PyObject {
other.py().None()
}
fn __add__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __sub__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __mul__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __matmul__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __truediv__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __floordiv__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __mod__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __pow__(slf: PyRef<'_, Self>, _other: u8, _modulo: Option<u8>) -> PyRef<'_, Self> {
slf
}
fn __lshift__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __rshift__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __divmod__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __and__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __or__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
fn __xor__<'p>(slf: PyRef<'p, Self>, _other: PyRef<'p, Self>) -> PyRef<'p, Self> {
slf
}
// Inplace assignments
fn __iadd__(&mut self, _other: PyRef<'_, Self>) {}
fn __isub__(&mut self, _other: PyRef<'_, Self>) {}
fn __imul__(&mut self, _other: PyRef<'_, Self>) {}
fn __imatmul__(&mut self, _other: PyRef<'_, Self>) {}
fn __itruediv__(&mut self, _other: PyRef<'_, Self>) {}
fn __ifloordiv__(&mut self, _other: PyRef<'_, Self>) {}
fn __imod__(&mut self, _other: PyRef<'_, Self>) {}
fn __ilshift__(&mut self, _other: PyRef<'_, Self>) {}
fn __irshift__(&mut self, _other: PyRef<'_, Self>) {}
fn __iand__(&mut self, _other: PyRef<'_, Self>) {}
fn __ior__(&mut self, _other: PyRef<'_, Self>) {}
fn __ixor__(&mut self, _other: PyRef<'_, Self>) {}
fn __ipow__(&mut self, _other: PyRef<'_, Self>, _modulo: Option<u8>) {}
}
fn _test_binary_dunder(dunder: &str) {
Python::with_gil(|py| {
let c2 = Py::new(py, RichComparisonToSelf {}).unwrap();
py_run!(
py,
c2,
&format!(
"class Other: pass\nassert c2.__{}__(Other()) is NotImplemented",
dunder
)
);
});
}
fn _test_binary_operator(operator: &str, dunder: &str) {
_test_binary_dunder(dunder);
Python::with_gil(|py| {
let c2 = Py::new(py, RichComparisonToSelf {}).unwrap();
py_expect_exception!(
py,
c2,
format!("class Other: pass\nc2 {} Other()", operator),
PyTypeError
);
});
}
fn _test_inplace_binary_operator(operator: &str, dunder: &str) {
_test_binary_operator(operator, dunder);
}
#[test]
fn equality() {
_test_binary_dunder("eq");
_test_binary_dunder("ne");
}
#[test]
fn ordering() {
_test_binary_operator("<", "lt");
_test_binary_operator("<=", "le");
_test_binary_operator(">", "gt");
_test_binary_operator(">=", "ge");
}
#[test]
fn bitwise() {
_test_binary_operator("&", "and");
_test_binary_operator("|", "or");
_test_binary_operator("^", "xor");
_test_binary_operator("<<", "lshift");
_test_binary_operator(">>", "rshift");
}
#[test]
fn arith() {
_test_binary_operator("+", "add");
_test_binary_operator("-", "sub");
_test_binary_operator("*", "mul");
_test_binary_operator("@", "matmul");
_test_binary_operator("/", "truediv");
_test_binary_operator("//", "floordiv");
_test_binary_operator("%", "mod");
_test_binary_operator("**", "pow");
}
#[test]
fn reverse_arith() {
_test_binary_dunder("radd");
_test_binary_dunder("rsub");
_test_binary_dunder("rmul");
_test_binary_dunder("rmatmul");
_test_binary_dunder("rtruediv");
_test_binary_dunder("rfloordiv");
_test_binary_dunder("rmod");
_test_binary_dunder("rdivmod");
_test_binary_dunder("rpow");
}
#[test]
fn inplace_bitwise() {
_test_inplace_binary_operator("&=", "iand");
_test_inplace_binary_operator("|=", "ior");
_test_inplace_binary_operator("^=", "ixor");
_test_inplace_binary_operator("<<=", "ilshift");
_test_inplace_binary_operator(">>=", "irshift");
}
#[test]
fn inplace_arith() {
_test_inplace_binary_operator("+=", "iadd");
_test_inplace_binary_operator("-=", "isub");
_test_inplace_binary_operator("*=", "imul");
_test_inplace_binary_operator("@=", "imatmul");
_test_inplace_binary_operator("/=", "itruediv");
_test_inplace_binary_operator("//=", "ifloordiv");
_test_inplace_binary_operator("%=", "imod");
_test_inplace_binary_operator("**=", "ipow");
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/pyo3 | lc_public_repos/langsmith-sdk/vendor/pyo3/tests/test_module.rs | #![cfg(feature = "macros")]
use pyo3::prelude::*;
use pyo3::py_run;
use pyo3::types::PyString;
use pyo3::types::{IntoPyDict, PyDict, PyTuple};
use pyo3::BoundObject;
use pyo3_ffi::c_str;
#[path = "../src/tests/common.rs"]
mod common;
#[pyclass]
struct AnonClass {}
#[pyclass]
struct ValueClass {
value: usize,
}
#[pymethods]
impl ValueClass {
#[new]
fn new(value: usize) -> ValueClass {
ValueClass { value }
}
}
#[pyclass(module = "module")]
struct LocatedClass {}
#[pyfunction]
/// Doubles the given value
fn double(x: usize) -> usize {
x * 2
}
/// This module is implemented in Rust.
#[pymodule(gil_used = false)]
fn module_with_functions(m: &Bound<'_, PyModule>) -> PyResult<()> {
#[pyfn(m)]
#[pyo3(name = "no_parameters")]
fn function_with_name() -> usize {
42
}
#[pyfn(m)]
#[pyo3(pass_module)]
fn with_module<'py>(module: &Bound<'py, PyModule>) -> PyResult<Bound<'py, PyString>> {
module.name()
}
#[pyfn(m)]
fn double_value(v: &ValueClass) -> usize {
v.value * 2
}
m.add_class::<AnonClass>()?;
m.add_class::<ValueClass>()?;
m.add_class::<LocatedClass>()?;
m.add("foo", "bar")?;
m.add_function(wrap_pyfunction!(double, m)?)?;
m.add("also_double", wrap_pyfunction!(double, m)?)?;
Ok(())
}
#[test]
fn test_module_with_functions() {
use pyo3::wrap_pymodule;
Python::with_gil(|py| {
let d = [(
"module_with_functions",
wrap_pymodule!(module_with_functions)(py),
)]
.into_py_dict(py)
.unwrap();
py_assert!(
py,
*d,
"module_with_functions.__doc__ == 'This module is implemented in Rust.'"
);
py_assert!(py, *d, "module_with_functions.no_parameters() == 42");
py_assert!(py, *d, "module_with_functions.foo == 'bar'");
py_assert!(py, *d, "module_with_functions.AnonClass != None");
py_assert!(py, *d, "module_with_functions.LocatedClass != None");
py_assert!(
py,
*d,
"module_with_functions.LocatedClass.__module__ == 'module'"
);
py_assert!(py, *d, "module_with_functions.double(3) == 6");
py_assert!(
py,
*d,
"module_with_functions.double.__doc__ == 'Doubles the given value'"
);
py_assert!(py, *d, "module_with_functions.also_double(3) == 6");
py_assert!(
py,
*d,
"module_with_functions.also_double.__doc__ == 'Doubles the given value'"
);
py_assert!(
py,
*d,
"module_with_functions.double_value(module_with_functions.ValueClass(1)) == 2"
);
py_assert!(
py,
*d,
"module_with_functions.with_module() == 'module_with_functions'"
);
});
}
/// This module uses a legacy two-argument module function.
#[pymodule]
fn module_with_explicit_py_arg(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(double, m)?)?;
Ok(())
}
#[test]
fn test_module_with_explicit_py_arg() {
use pyo3::wrap_pymodule;
Python::with_gil(|py| {
let d = [(
"module_with_explicit_py_arg",
wrap_pymodule!(module_with_explicit_py_arg)(py),
)]
.into_py_dict(py)
.unwrap();
py_assert!(py, *d, "module_with_explicit_py_arg.double(3) == 6");
});
}
#[pymodule(name = "other_name")]
fn some_name(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add("other_name", "other_name")?;
Ok(())
}
#[test]
fn test_module_renaming() {
use pyo3::wrap_pymodule;
Python::with_gil(|py| {
let d = [("different_name", wrap_pymodule!(some_name)(py))]
.into_py_dict(py)
.unwrap();
py_run!(py, *d, "assert different_name.__name__ == 'other_name'");
});
}
#[test]
fn test_module_from_code_bound() {
Python::with_gil(|py| {
let adder_mod = PyModule::from_code(
py,
c_str!("def add(a,b):\n\treturn a+b"),
c_str!("adder_mod.py"),
&common::generate_unique_module_name("adder_mod"),
)
.expect("Module code should be loaded");
let add_func = adder_mod
.getattr("add")
.expect("Add function should be in the module");
let ret_value: i32 = add_func
.call1((1, 2))
.expect("A value should be returned")
.extract()
.expect("The value should be able to be converted to an i32");
adder_mod.gil_used(false).expect("Disabling the GIL failed");
assert_eq!(ret_value, 3);
});
}
#[pyfunction]
fn r#move() -> usize {
42
}
#[pymodule]
fn raw_ident_module(module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_function(wrap_pyfunction!(r#move, module)?)
}
#[test]
fn test_raw_idents() {
use pyo3::wrap_pymodule;
Python::with_gil(|py| {
let module = wrap_pymodule!(raw_ident_module)(py);
py_assert!(py, module, "module.move() == 42");
});
}
#[pyfunction]
#[pyo3(name = "foobar")]
fn custom_named_fn() -> usize {
42
}
#[test]
fn test_custom_names() {
#[pymodule]
fn custom_names(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(custom_named_fn, m)?)?;
Ok(())
}
Python::with_gil(|py| {
let module = pyo3::wrap_pymodule!(custom_names)(py);
py_assert!(py, module, "not hasattr(module, 'custom_named_fn')");
py_assert!(py, module, "module.foobar() == 42");
});
}
#[test]
fn test_module_dict() {
#[pymodule]
fn module_dict(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.dict().set_item("yay", "me")?;
Ok(())
}
Python::with_gil(|py| {
let module = pyo3::wrap_pymodule!(module_dict)(py);
py_assert!(py, module, "module.yay == 'me'");
});
}
#[test]
fn test_module_dunder_all() {
Python::with_gil(|py| {
#[pymodule]
fn dunder_all(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.dict().set_item("yay", "me")?;
m.add_function(wrap_pyfunction!(custom_named_fn, m)?)?;
Ok(())
}
let module = pyo3::wrap_pymodule!(dunder_all)(py);
py_assert!(py, module, "module.__all__ == ['foobar']");
});
}
#[pyfunction]
fn subfunction() -> String {
"Subfunction".to_string()
}
fn submodule(module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_function(wrap_pyfunction!(subfunction, module)?)?;
Ok(())
}
#[pymodule]
fn submodule_with_init_fn(module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_function(wrap_pyfunction!(subfunction, module)?)?;
Ok(())
}
#[pyfunction]
fn superfunction() -> String {
"Superfunction".to_string()
}
#[pymodule]
fn supermodule(module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_function(wrap_pyfunction!(superfunction, module)?)?;
let module_to_add = PyModule::new(module.py(), "submodule")?;
submodule(&module_to_add)?;
module.add_submodule(&module_to_add)?;
let module_to_add = PyModule::new(module.py(), "submodule_with_init_fn")?;
submodule_with_init_fn(&module_to_add)?;
module.add_submodule(&module_to_add)?;
Ok(())
}
#[test]
fn test_module_nesting() {
use pyo3::wrap_pymodule;
Python::with_gil(|py| {
let supermodule = wrap_pymodule!(supermodule)(py);
py_assert!(
py,
supermodule,
"supermodule.superfunction() == 'Superfunction'"
);
py_assert!(
py,
supermodule,
"supermodule.submodule.subfunction() == 'Subfunction'"
);
py_assert!(
py,
supermodule,
"supermodule.submodule_with_init_fn.subfunction() == 'Subfunction'"
);
});
}
// Test that argument parsing specification works for pyfunctions
#[pyfunction(signature = (a=5, *args))]
fn ext_vararg_fn(py: Python<'_>, a: i32, args: &Bound<'_, PyTuple>) -> PyResult<PyObject> {
[
a.into_pyobject(py)?.into_any().into_bound(),
args.as_any().clone(),
]
.into_pyobject(py)
.map(BoundObject::unbind)
}
#[pymodule]
fn vararg_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
#[pyfn(m, signature = (a=5, *args))]
fn int_vararg_fn(py: Python<'_>, a: i32, args: &Bound<'_, PyTuple>) -> PyResult<PyObject> {
ext_vararg_fn(py, a, args)
}
m.add_function(wrap_pyfunction!(ext_vararg_fn, m)?).unwrap();
Ok(())
}
#[test]
fn test_vararg_module() {
Python::with_gil(|py| {
let m = pyo3::wrap_pymodule!(vararg_module)(py);
py_assert!(py, m, "m.ext_vararg_fn() == [5, ()]");
py_assert!(py, m, "m.ext_vararg_fn(1, 2) == [1, (2,)]");
py_assert!(py, m, "m.int_vararg_fn() == [5, ()]");
py_assert!(py, m, "m.int_vararg_fn(1, 2) == [1, (2,)]");
});
}
#[test]
fn test_module_with_constant() {
// Regression test for #1102
#[pymodule]
fn module_with_constant(m: &Bound<'_, PyModule>) -> PyResult<()> {
const ANON: AnonClass = AnonClass {};
m.add("ANON", ANON)?;
m.add_class::<AnonClass>()?;
Ok(())
}
Python::with_gil(|py| {
let m = pyo3::wrap_pymodule!(module_with_constant)(py);
py_assert!(py, m, "isinstance(m.ANON, m.AnonClass)");
});
}
#[pyfunction]
#[pyo3(pass_module)]
fn pyfunction_with_module<'py>(module: &Bound<'py, PyModule>) -> PyResult<Bound<'py, PyString>> {
module.name()
}
#[pyfunction]
#[pyo3(pass_module)]
fn pyfunction_with_module_owned(
module: Py<PyModule>,
py: Python<'_>,
) -> PyResult<Bound<'_, PyString>> {
module.bind(py).name()
}
#[pyfunction]
#[pyo3(pass_module)]
fn pyfunction_with_module_and_py<'py>(
module: &Bound<'py, PyModule>,
_python: Python<'py>,
) -> PyResult<Bound<'py, PyString>> {
module.name()
}
#[pyfunction]
#[pyo3(pass_module)]
fn pyfunction_with_module_and_arg<'py>(
module: &Bound<'py, PyModule>,
string: String,
) -> PyResult<(Bound<'py, PyString>, String)> {
module.name().map(|s| (s, string))
}
#[pyfunction(signature = (string="foo"))]
#[pyo3(pass_module)]
fn pyfunction_with_module_and_default_arg<'py>(
module: &Bound<'py, PyModule>,
string: &str,
) -> PyResult<(Bound<'py, PyString>, String)> {
module.name().map(|s| (s, string.into()))
}
#[pyfunction(signature = (*args, **kwargs))]
#[pyo3(pass_module)]
fn pyfunction_with_module_and_args_kwargs<'py>(
module: &Bound<'py, PyModule>,
args: &Bound<'py, PyTuple>,
kwargs: Option<&Bound<'py, PyDict>>,
) -> PyResult<(Bound<'py, PyString>, usize, Option<usize>)> {
module
.name()
.map(|s| (s, args.len(), kwargs.map(|d| d.len())))
}
#[pymodule]
fn module_with_functions_with_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(pyfunction_with_module, m)?)?;
m.add_function(wrap_pyfunction!(pyfunction_with_module_owned, m)?)?;
m.add_function(wrap_pyfunction!(pyfunction_with_module_and_py, m)?)?;
m.add_function(wrap_pyfunction!(pyfunction_with_module_and_arg, m)?)?;
m.add_function(wrap_pyfunction!(pyfunction_with_module_and_default_arg, m)?)?;
m.add_function(wrap_pyfunction!(pyfunction_with_module_and_args_kwargs, m)?)?;
m.add_function(wrap_pyfunction!(pyfunction_with_module, m)?)?;
Ok(())
}
#[test]
fn test_module_functions_with_module() {
Python::with_gil(|py| {
let m = pyo3::wrap_pymodule!(module_with_functions_with_module)(py);
py_assert!(
py,
m,
"m.pyfunction_with_module() == 'module_with_functions_with_module'"
);
py_assert!(
py,
m,
"m.pyfunction_with_module_owned() == 'module_with_functions_with_module'"
);
py_assert!(
py,
m,
"m.pyfunction_with_module_and_py() == 'module_with_functions_with_module'"
);
py_assert!(
py,
m,
"m.pyfunction_with_module_and_default_arg() \
== ('module_with_functions_with_module', 'foo')"
);
py_assert!(
py,
m,
"m.pyfunction_with_module_and_args_kwargs(1, x=1, y=2) \
== ('module_with_functions_with_module', 1, 2)"
);
});
}
#[test]
fn test_module_doc_hidden() {
#[doc(hidden)]
#[allow(clippy::unnecessary_wraps)]
#[pymodule]
fn my_module(_m: &Bound<'_, PyModule>) -> PyResult<()> {
Ok(())
}
Python::with_gil(|py| {
let m = pyo3::wrap_pymodule!(my_module)(py);
py_assert!(py, m, "m.__doc__ == ''");
})
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.