Commit Graph

38 Commits

Author SHA1 Message Date
Scott Wolchok
ccb7129f54 Improve performance of enum_ operators by going back to specific implementation (#5887)
* Improve performance of enum_ operators by going back to specific implementation

test_enum needs a patch because ops are now overloaded and this affects their docstrings.

* outline call_impl to save on code size

This does cause more move constructions, as shown by the needed update to test_copy_move. Up to reviewers whether they want more code size or more moves.

* add function_ref.h to PYBIND11_HEADERS.

* Update test_copy_move tests with C++17 passing values just so we can see mostly-not-red tests

* Remove stray TODO

* fix clang-tidy

* fix clang-tidy again. add function_ref.h to test_files.py

* Add static assertion for function_ref lifetime safety in call_impl

Add a static_assert to document and enforce that function_ref is
trivially copyable, ensuring safe pass-by-value usage. This also
documents the lifetime safety guarantees: function_ref is created
from cap->f which lives in the capture object, and is only used
synchronously within call_impl without being stored beyond its scope.

* Add #undef cleanup for enum operator macros

Undefine all enum operator macros after their last use to prevent
macro pollution and follow the existing code pattern. This matches
the cleanup pattern used for the previous enum operator macros.

* Rename PYBIND11_THROW to PYBIND11_ENUM_OP_THROW_TYPE_ERROR

Rename the macro to be more specific and avoid potential clashes with
public macros. The new name clearly indicates it's scoped to enum
operations and describes its purpose (throwing a type error).

* Clarify comments in function_ref.h

Replace vague comments about 'extensions to <functional>' and 'functions'
with a clearer description that this is a header-only class template
similar to std::function but with non-owning semantics. This makes it
clear that it's template-only and requires no additional library linking.

---------

Co-authored-by: Ralf W. Grosse-Kunstleve <rgrossekunst@nvidia.com>
2026-02-16 23:00:21 -08:00
Ralf W. Grosse-Kunstleve
9f1187f97c Add typing.SupportsIndex to int/float/complex type hints (#5891)
* Add typing.SupportsIndex to int/float/complex type hints

This corrects a mistake where these types were supported but the type
hint was not updated to reflect that SupportsIndex objects are accepted.

To track the resulting test failures:

The output of

"$(cat PYROOT)"/bin/python3 $HOME/clone/pybind11_scons/run_tests.py $HOME/forked/pybind11 -v

is in

~/logs/pybind11_pr5879_scons_run_tests_v_log_2025-11-10+122217.txt

* Cursor auto-fixes (partial) plus pre-commit cleanup. 7 test failures left to do.

* Fix remaining test failures, partially done by cursor, partially manually.

* Cursor-generated commit: Added the Index() tests from PR 5879.

Summary:

  Changes Made

  1. **C++ Bindings** (`tests/test_builtin_casters.cpp`)

  • Added complex_convert and complex_noconvert functions needed for the tests

  2. **Python Tests** (`tests/test_builtin_casters.py`)

  `test_float_convert`:
  • Added Index class with __index__ returning -7
  • Added Int class with __int__ returning -5
  • Added test showing Index() works with convert mode: assert pytest.approx(convert(Index())) == -7.0
  • Added test showing Index() doesn't work with noconvert mode: requires_conversion(Index())
  • Added additional assertions for int literals and Int() class

  `test_complex_cast`:
  • Expanded the test to include convert and noconvert functionality
  • Added Index, Complex, Float, and Int classes
  • Added test showing Index() works with convert mode: assert convert(Index()) == 1 and assert isinstance(convert(Index()), complex)
  • Added test showing Index() doesn't work with noconvert mode: requires_conversion(Index())
  • Added type hint assertions matching the SupportsIndex additions

  These tests demonstrate that custom __index__ objects work with float and complex in convert mode, matching the typing.SupportsIndex type hint added in PR
  5891.

* Reflect behavior changes going back from PR 5879 to master. This diff will have to be reapplied under PR 5879.

* Add PyPy-specific __index__ handling for complex caster

Extract PyPy-specific __index__ backporting from PR 5879 to fix PyPy 3.10
test failures in PR 5891. This adds:

1. PYBIND11_INDEX_CHECK macro in detail/common.h:
   - Uses PyIndex_Check on CPython
   - Uses hasattr check on PyPy (workaround for PyPy 7.3.3 behavior)

2. PyPy-specific __index__ handling in complex.h:
   - Handles __index__ objects on PyPy 7.3.7's 3.8 which doesn't
     implement PyLong_*'s __index__ calls
   - Mirrors the logic used in numeric_caster for ints and floats

This backports __index__ handling for PyPy, matching the approach
used in PR 5879's expand-float-strict branch.
2025-11-10 20:26:50 -08:00
pre-commit-ci[bot]
a2951abbec chore(deps): update pre-commit hooks (#5605)
* chore(deps): update pre-commit hooks

updates:
- [github.com/pre-commit/mirrors-clang-format: v19.1.7 → v20.1.0](https://github.com/pre-commit/mirrors-clang-format/compare/v19.1.7...v20.1.0)
- [github.com/astral-sh/ruff-pre-commit: v0.9.9 → v0.11.4](https://github.com/astral-sh/ruff-pre-commit/compare/v0.9.9...v0.11.4)
- [github.com/PyCQA/pylint: v3.3.4 → v3.3.6](https://github.com/PyCQA/pylint/compare/v3.3.4...v3.3.6)
- [github.com/python-jsonschema/check-jsonschema: 0.31.2 → 0.32.1](https://github.com/python-jsonschema/check-jsonschema/compare/0.31.2...0.32.1)

* style: pre-commit fixes

* Update setup.py

* Update tests/test_enum.py

* Update configure.yml

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2025-04-10 18:31:28 -04:00
Henry Schreiner
8ef10a0ec9 ci: update to GraalPy 24.2 and mention in README (#5586)
* ci: update to GraalPy 24.2 and mention in README

Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>

* tests: update for GRAALPY 24.2 and better printout

Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>

* tests: use __graalpython__ for version number

Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>

* Update README.rst

---------

Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>
2025-03-31 22:50:55 -04:00
Ralf W. Grosse-Kunstleve
f365314ec0 Enable Conversions Between Native Python Enum Types and C++ Enums (#5555)
* Apply smart_holder-branch-based PR #5280 on top of master.

* Add pytest.skip("GraalPy does not raise UnicodeDecodeError")

* Add `parent_scope` as first argument to `py::native_enum` ctor.

* Replace `operator+=` API with `.finalize()` API. The error messages still need cleanup.

* Resolve clang-tidy performance-unnecessary-value-param errors

* Rename (effectively) native_enum_add_to_parent() -> finalize()

* Update error message: pybind11::native_enum<...>("Fake", ...): MISSING .finalize()

* Pass py::module_ by reference to resolve clang-tidy errors (this is entirely inconsequential otherwise for all practical purposes).

* test_native_enum_correct_use_failure -> test_native_enum_missing_finalize_failure

* Add test_native_enum_double_finalize(), test_native_enum_value_after_finalize()

* Clean up public/protected API.

* [ci skip] Update the Enumerations section in classes.rst

* Rename `py::native_enum_kind` → `py::enum_kind` as suggested by gh-henryiii:

https://github.com/pybind/pybind11/pull/5555#issuecomment-2711672335

* Experiment: StrEnum

enum.StrEnum does not map to C++ enum:

* https://chatgpt.com/share/67d5e965-ccb0-8008-95b7-0df2502309b3

```
============================= test session starts ==============================
platform linux -- Python 3.12.3, pytest-8.3.3, pluggy-1.5.0
C++ Info: 13.3.0 C++20 __pybind11_internals_v10000000_system_libstdcpp_gxx_abi_1xxx_use_cxx11_abi_1__ PYBIND11_SIMPLE_GIL_MANAGEMENT=False PYBIND11_NUMPY_1_ONLY=False
configfile: pytest.ini
plugins: parallel-0.1.1, xdist-3.6.1
collected 40 items / 39 deselected / 1 selected

test_native_enum.py F                                                    [100%]

=================================== FAILURES ===================================
________________________ test_native_enum_StrEnum_greek ________________________

    def test_native_enum_StrEnum_greek():
        assert not hasattr(m, "greek")
>       m.native_enum_StrEnum_greek(m)

test_native_enum.py:150:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/lib/python3.12/enum.py:764: in __call__
    return cls._create_(
        boundary   = None
        cls        = <enum 'StrEnum'>
        module     = None
        names      = [('Alpha', 10), ('Omega', 20)]
        qualname   = None
        start      = 1
        type       = None
        value      = 'greek'
        values     = ()
/usr/lib/python3.12/enum.py:917: in _create_
    return metacls.__new__(metacls, class_name, bases, classdict, boundary=boundary)
        _          = <class 'str'>
        bases      = (<enum 'StrEnum'>,)
        boundary   = None
        class_name = 'greek'
        classdict  = {'_generate_next_value_': <function StrEnum._generate_next_value_ at 0x701ec1711e40>, 'Alpha': 10, 'Omega': 20, '__module__': 'test_native_enum'}
        cls        = <enum 'StrEnum'>
        first_enum = <enum 'StrEnum'>
        item       = ('Omega', 20)
        member_name = 'Omega'
        member_value = 20
        metacls    = <class 'enum.EnumType'>
        module     = 'test_native_enum'
        names      = [('Alpha', 10), ('Omega', 20)]
        qualname   = None
        start      = 1
        type       = None
/usr/lib/python3.12/enum.py:606: in __new__
    raise exc.with_traceback(tb)
        __class__  = <class 'enum.EnumType'>
        __new__    = <function StrEnum.__new__ at 0x701ec1711da0>
        _gnv       = <staticmethod(<function StrEnum._generate_next_value_ at 0x701ec1711e40>)>
        _order_    = None
        _simple    = False
        bases      = (<enum 'StrEnum'>,)
        boundary   = None
        classdict  = {'Alpha': <enum._proto_member object at 0x701ebc74f9b0>, 'Omega': <enum._proto_member object at 0x701ebc74cce0>, '__module__': 'test_native_enum', '_all_bits_': 0, ...}
        cls        = 'greek'
        exc        = TypeError('10 is not a string')
        first_enum = <enum 'StrEnum'>
        ignore     = ['_ignore_']
        invalid_names = set()
        key        = '_ignore_'
        kwds       = {}
        member_names = {'Alpha': None, 'Omega': None}
        member_type = <class 'str'>
        metacls    = <class 'enum.EnumType'>
        name       = 'Omega'
        save_new   = False
        tb         = <traceback object at 0x701ebc7a6cc0>
        use_args   = True
        value      = 20
/usr/lib/python3.12/enum.py:596: in __new__
    enum_class = super().__new__(metacls, cls, bases, classdict, **kwds)
        __class__  = <class 'enum.EnumType'>
        __new__    = <function StrEnum.__new__ at 0x701ec1711da0>
        _gnv       = <staticmethod(<function StrEnum._generate_next_value_ at 0x701ec1711e40>)>
        _order_    = None
        _simple    = False
        bases      = (<enum 'StrEnum'>,)
        boundary   = None
        classdict  = {'Alpha': <enum._proto_member object at 0x701ebc74f9b0>, 'Omega': <enum._proto_member object at 0x701ebc74cce0>, '__module__': 'test_native_enum', '_all_bits_': 0, ...}
        cls        = 'greek'
        exc        = TypeError('10 is not a string')
        first_enum = <enum 'StrEnum'>
        ignore     = ['_ignore_']
        invalid_names = set()
        key        = '_ignore_'
        kwds       = {}
        member_names = {'Alpha': None, 'Omega': None}
        member_type = <class 'str'>
        metacls    = <class 'enum.EnumType'>
        name       = 'Omega'
        save_new   = False
        tb         = <traceback object at 0x701ebc7a6cc0>
        use_args   = True
        value      = 20
/usr/lib/python3.12/enum.py:271: in __set_name__
    enum_member = enum_class._new_member_(enum_class, *args)
        args       = (10,)
        enum_class = <enum 'greek'>
        member_name = 'Alpha'
        self       = <enum._proto_member object at 0x701ebc74f9b0>
        value      = 10
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

cls = <enum 'greek'>, values = (10,)

    def __new__(cls, *values):
        "values must already be of type `str`"
        if len(values) > 3:
            raise TypeError('too many arguments for str(): %r' % (values, ))
        if len(values) == 1:
            # it must be a string
            if not isinstance(values[0], str):
>               raise TypeError('%r is not a string' % (values[0], ))
E               TypeError: 10 is not a string

cls        = <enum 'greek'>
values     = (10,)

/usr/lib/python3.12/enum.py:1322: TypeError
=========================== short test summary info ============================
FAILED test_native_enum.py::test_native_enum_StrEnum_greek - TypeError: 10 is...
======================= 1 failed, 39 deselected in 0.07s =======================

ERROR: completed_process.returncode=1
```

* Remove StrEnum code.

* Make enum_kind::Enum the default kind.

* Catch redundant .export_values() calls.

* [ci skip] Add back original documentation for `py::enum_` under new advanced/deprecated.rst

* [ci skip] Add documentation for `py::enum_kind` and `py::detail::type_caster_enum_type_enabled`

* Rename `Type` to `EnumType` for readability.

* Eliminate py::enum_kind, use "enum.Enum", "enum.IntEnum" directly. This is still WIP.

* EXPERIMENTAL StrEnum code. To be removed.

* Remove experimental StrEnum code:

My judgement: Supporting StrEnum is maybe nice, but not very valuable. I don't think it is worth the extra C++ code.

A level of indirection would need to be managed, e.g.

    RED   ↔ Python "r" ↔ C++ 0
    Green ↔ Python "g" ↔ C++ 1

These mappings would need to be stored and processed.

* Add test with enum.IntFlag (no production code changes required).

* First import_or_getattr() implementation (dedicated tests are still missing).

* Fix import_or_getattr() implementation, add tests, fix clang-tidy errors.

* [ci skip] Update classes.rst: replace `py::enum_kind` with `native_type_name`

* For "constructor similar to that of enum.Enum" point to https://docs.python.org/3/howto/enum.html#functional-api, as suggested by gh-timohl (https://github.com/pybind/pybind11/pull/5555#discussion_r2009277507).

* Advertise Enum, IntEnum, Flag, IntFlags are compatible stdlib enum types in the documentation (as suggested by gh-timohl, https://github.com/pybind/pybind11/pull/5555#pullrequestreview-2708832587); add test for enum.Flag to ensure that is actually true.
2025-03-24 20:31:59 -07:00
Xuehai Pan
7f94f24d64 feat(typing): allow annotate methods with pos_only when only have the self argument (#5403)
* feat: allow annotate methods with `pos_only` when only have the `self` argument

* chore(typing): make arguments for auto-generated dunder methods positional-only

* docs: add more comments to improve readability

* style: fix nit suggestions

* Add test_self_only_pos_only() in tests/test_methods_and_attributes

* test: add docstring tests for generated dunder methods

* test: remove failed tests

* fix(test): run `gc.collect()` three times for refcount tests

---------

Co-authored-by: Ralf W. Grosse-Kunstleve <rgrossekunst@nvidia.com>
2024-11-11 15:35:28 -08:00
Michael Šimáček
c4a05f9344 Add support for GraalPy (#5380)
* Initial support for GraalPy

* Mark tests that currently fail on GraalPy with xfail

* Add graalpy to CI

* Limit test deps on graalpy to available binary wheels

* Skip cmake test installed_function on GraalPy

CMake won't find libpython on GraalPy, it either fails or silently picks
CPython's libpython.

* Factor out setting function docstrings into a macro

* Try to narrow down skipped tests
2024-10-07 14:12:04 -07:00
Ralf W. Grosse-Kunstleve
f1a2e03d19 feat: remove Python 3.6 support (#5177)
* Change Python version guard: PYTHON < 3.7 IS UNSUPPORTED.

* Replace or remove Python 3.6 jobs.

* Move appveyor to Python 3.8

* Change `[tool.pylint]` `master.py-version` from `3.6` to `3.8`

* Change `[tool.pylint]` `master.py-version` to `3.7`

* Remove `centos:7` job; Change almalinux:8 job to use Python 3.8

* Try 🐍 3.8 • ubuntu-20.04 • x64 without `-DCMAKE_CXX_FLAGS="-D_=1"`

* Update setup.cfg as suggested by @henryiii

* Try running `cmake --build . --target cpptest` on all platforms (`standard` job).

* Disable deadsnakes jobs entirely.

* Apply PR #5179: Add Python 3.10, 3.11, 3.12 to win32 job matrix.

* Add back `-DCMAKE_CXX_FLAGS="-D_=1"` but do not install boost in that case.

* PY_VERSION_HEX < 3.7 cleanup pass: include/pybind11

* WITH_THREAD cleanup pass: include/pybind11

* Undo incorrect change.

* Revert "Disable deadsnakes jobs entirely."

This reverts commit bbcd0087b2.

* WITH_THREAD cleanup pass: tests/

* Change Python version guard in pybind11/__init__.py: pybind11 does not support Python < 3.7.

* Misc cleanup pass

* chore: use future imports

Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>

* Update tests/test_numpy_array.py

* Update test_numpy_array.py

---------

Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>
Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
2024-06-22 00:55:00 -04:00
Henry Schreiner
c758b81f3b chore: move to ruff-format (#4912)
Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>
Co-authored-by: Ralf W. Grosse-Kunstleve <rwgk@google.com>
2023-11-07 23:42:54 -08:00
Sergei Izmailov
e705fb5f27 Fix enum's __str__ docstring (#4827)
* fix: Enum __str__ function name

* tests: Test enum.__str__.__doc__
2023-08-30 14:20:46 -07:00
Henry Schreiner
438034c5b8 chore: move to Ruff and add rules (#4483) 2023-02-22 06:18:55 -08:00
Ralf W. Grosse-Kunstleve
6493f496e3 Python 2 removal part 1: tests (C++ code is intentionally ~untouched) (#3688)
* `#error BYE_BYE_GOLDEN_SNAKE`

* Removing everything related to 2.7 from ci.yml

* Commenting-out Centos7

* Removing `PYTHON: 27` from .appveyor.yml

* "PY2" removal, mainly from tests. C++ code is not touched.

* Systematic removal of `u` prefix from `u"..."` and `u'...'` literals. Collateral cleanup of a couple minor other things.

* Cleaning up around case-insensitive hits for `[^a-z]py.*2` in tests/.

* Removing obsolete Python 2 mention in compiling.rst

* Proper `#error` for Python 2.

* Using PY_VERSION_HEX to guard `#error "PYTHON 2 IS NO LONGER SUPPORTED.`

* chore: bump pre-commit

* style: run pre-commit for pyupgrade 3+

* tests: use sys.version_info, not PY

* chore: more Python 2 removal

* Uncommenting Centos7 block (PR #3691 showed that it is working again).

* Update pre-commit hooks

* Fix pre-commit hook

* refactor: remove Python 2 from CMake

* refactor: remove Python 2 from setup code

* refactor: simplify, better static typing

* feat: fail with nice messages

* refactor: drop Python 2 C++ code

* docs: cleanup for Python 3

* revert: intree

revert: intree

* docs: minor touchup to py2 statement

Co-authored-by: Henry Schreiner <henryschreineriii@gmail.com>
Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
2022-02-10 18:28:08 -08:00
Aaron Gokaslan
f4c81e0877 maint: Add additional linter-related pre-commit hooks (#3337)
* Add additional pygrep pre-commit hooks

* Remove useless noqas with hook

* Fix all single rst backticks

* Simplify mypy pre-commit hook with upstream fixes

* Add back missing comment

* Add one last pygrep hook
2021-10-08 08:38:04 -04:00
Ralf W. Grosse-Kunstleve
49173e472f Minor follow-on to PR #1334 (Fix enum value's __int__ returning non-int when underlying type is bool or of char type) (#3232)
* Minor tweaks.

* Restoring tests/pybind11_tests.h version from master, removing just the comment and empty line that was added in PR #3087; those were made obsolete by the pragma cleanup that concluded with PR #3186.

* More-to-the-point test for Python 3.
2021-08-31 08:52:04 -07:00
Ye Zhihao
cb60ed49e4 Fix enum value's __int__ returning non-int when underlying type is bool or of char type (#1334)
* Use equivalent_integer for enum's Scalar decision

* Add test for char underlying enum

* Support translating bool type in enum's Scalar

* Add test for bool underlying enum

* Fix comment in test

* Switch from `PYBIND11_CPP20` macro to `PYBIND11_HAS_U8STRING`

* Refine tests

Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
2021-08-26 14:34:24 -07:00
Aaron Gokaslan
9df2f1ff13 maint(precommit): Apply isort (#3195)
* Apply isort

* Tweak isort config

* Add env.py as a known_first_party

* Add one missing known first party

* Make config compat with older isort versions

* Add another comment

* Revert pyproject setting
2021-08-13 12:37:05 -04:00
Eric Cousineau
2110d2d8ba enum: add missing Enum.value property (#2739)
* enum: Add Enum.value property

* simplify

* address review
2020-12-31 11:08:15 -05:00
Ralf W. Grosse-Kunstleve
cecdfadc58 minor cleanup: fixing or silencing flake8 errors (#2731)
* minor cleanup: fixing or silencing flake8 errors

* ci: lock CMake to non-Universal version

* Update .github/workflows/ci.yml

Co-authored-by: Henry Schreiner <HenrySchreinerIII@gmail.com>
2020-12-18 19:41:43 -05:00
Yannick Jadoul
c58758d049 fix: add reasonable argument names to enum_ methods (#2637)
* Add argument names to enum_ methods

* Add test_enum::test_docstring_signatures
2020-11-10 12:49:42 -05:00
Henry Schreiner
c50f90eca6 style: use Black everywhere (#2594)
* style: use Black everywhere

* style: minor touchup from review
2020-10-16 16:38:13 -04:00
David Vo
5e6ec49652 Add enum value to enum repr (#2126)
This changes enum reprs to look like `<Enum.name: value>` similarly to
the Python enum module.

This keeps the str of enums as `Enum.name`, like the Python enum module.
2020-09-20 01:12:19 +02:00
Henry Schreiner
d8c7ee00a6 ci: GHA basic format & pre-commit (#2309) 2020-07-20 13:35:21 -04:00
Wenzel Jakob
31680e6f9c Implicit conversion from enum to int for Python 3.8 (fix by @sizmailov) 2019-09-20 11:06:10 +02:00
Wenzel Jakob
21d0eb460f Fix Python 3.8 test regression 2019-09-20 09:38:30 +02:00
Sergei Izmailov
09f0829401 Avoid conversion to int_ rhs argument of enum eq/ne (#1912)
* fix: Avoid conversion to `int_` rhs argument of enum eq/ne

* test: compare unscoped enum with strings

* suppress comparison to None warning

* test unscoped enum arithmetic and comparision with unsupported type
2019-09-19 18:23:27 +02:00
Lori A. Burns
f6c4c1047a restores __invert__ to arithmetic-enabled enum, fixes #1907 (#1909) 2019-09-04 22:16:21 +02:00
Tarcísio Fischer
54eb8193e5 Fix scoped enums comparison for equal/not equal cases (#1339) (#1571) 2018-10-24 11:18:58 +02:00
Wenzel Jakob
f4245181ae enum_: move most functionality to a non-template implementation
This commit addresses an inefficiency in how enums are created in
pybind11. Most of the enum_<> implementation is completely generic --
however, being a template class, it ended up instantiating vast amounts
of essentially identical code in larger projects with many enums.

This commit introduces a generic non-templated helper class that is
compatible with any kind of enumeration. enum_ then becomes a thin
wrapper around this new class.

The new enum_<> API is designed to be 100% compatible with the old one.
2018-09-11 22:08:26 +02:00
Krzysztof Fornalczyk
5c8746ff13 check for already existing enum value added; added test (#1453)
* check for already existing enum value added; added test

* added enum value name to exception message

* test for defining enum with multiple identical names moved to test_enum.cpp/py
2018-09-11 10:59:56 +02:00
Boris Staletic
289e5d9cc2 Implement an enum_ property "name"
The property returns the enum_ value as a string.
For example:

>>> import module
>>> module.enum.VALUE
enum.VALUE
>>> str(module.enum.VALUE)
'enum.VALUE'
>>> module.enum.VALUE.name
'VALUE'

This is actually the equivalent of Boost.Python "name" property.
2018-04-07 19:11:35 -03:00
Wenzel Jakob
6d19036cb2 support docstrings in enum::value() (#1160) 2017-11-16 22:24:36 +01:00
Jason Rhinelander
391c75447d Update all remaining tests to new test styles
This udpates all the remaining tests to the new test suite code and
comment styles started in #898.  For the most part, the test coverage
here is unchanged, with a few minor exceptions as noted below.

- test_constants_and_functions: this adds more overload tests with
  overloads with different number of arguments for more comprehensive
  overload_cast testing.  The test style conversion broke the overload
  tests under MSVC 2015, prompting the additional tests while looking
  for a workaround.

- test_eigen: this dropped the unused functions `get_cm_corners` and
  `get_cm_corners_const`--these same tests were duplicates of the same
  things provided (and used) via ReturnTester methods.

- test_opaque_types: this test had a hidden dependence on ExampleMandA
  which is now fixed by using the global UserType which suffices for the
  relevant test.

- test_methods_and_attributes: this required some additions to UserType
  to make it usable as a replacement for the test's previous SimpleType:
  UserType gained a value mutator, and the `value` property is not
  mutable (it was previously readonly).  Some overload tests were also
  added to better test overload_cast (as described above).

- test_numpy_array: removed the untemplated mutate_data/mutate_data_t:
  the templated versions with an empty parameter pack expand to the same
  thing.

- test_stl: this was already mostly in the new style; this just tweaks
  things a bit, localizing a class, and adding some missing
  `// test_whatever` comments.

- test_virtual_functions: like `test_stl`, this was mostly in the new
  test style already, but needed some `// test_whatever` comments.
  This commit also moves the inherited virtual example code to the end
  of the file, after the main set of tests (since it is less important
  than the other tests, and rather length); it also got renamed to
  `test_inherited_virtuals` (from `test_inheriting_repeat`) because it
  tests both inherited virtual approaches, not just the repeat approach.
2017-08-05 18:46:22 -04:00
Wenzel Jakob
7653a115bd pytest target: add USE_TERMINAL flag
The added flag enables non-buffered console output when using Ninja
2017-04-29 16:35:28 +02:00
Wenzel Jakob
e6fd2cd5ab enum_: fix implicit conversion on Python 2.7
Enumerations on Python 2.7 were not always implicitly converted to
integers (depending on the target size). This patch adds a __long__
conversion function (only enabled on 2.7) which fixes this issue.

The attached test case fails without this patch.
2017-04-29 16:35:28 +02:00
Matthieu Bec
af936e1987 Expose enum_ entries as "__members__" read-only property. Getters get a copy. 2017-03-03 08:45:50 -08:00
Dean Moldovan
bad1740213 Add checks to maintain a consistent Python code style and prevent bugs (#515)
A flake8 configuration is included in setup.cfg and the checks are
executed automatically on Travis:

* Ensures a consistent PEP8 code style
* Does basic linting to prevent possible bugs
2016-11-20 21:21:54 +01:00
Pim Schellart
90d27805b9 Extended enum support (#503)
* Allow enums to be ordered
* Support binary operators
2016-11-16 17:28:11 +01:00
Dean Moldovan
a9a37b4e31 Move enum tests into a new file
There are more enum tests than 'constants and functions'.
2016-08-19 13:19:38 +02:00