Skip to content

Add type_hint_literal macro - #6398

Open
bschoenmaeckers wants to merge 1 commit into
PyO3:mainfrom
bschoenmaeckers:inspect-literal-macro
Open

Add type_hint_literal macro#6398
bschoenmaeckers wants to merge 1 commit into
PyO3:mainfrom
bschoenmaeckers:inspect-literal-macro

Conversation

@bschoenmaeckers

Copy link
Copy Markdown
Member

This adds a macro to make Literal type hints less verbose.

@bschoenmaeckers
bschoenmaeckers requested a review from Tpt September 9, 2026 12:41

@Tpt Tpt left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! I am a bit scared by this added complexity: do we have actual usescases where it will be useful?

@bschoenmaeckers

bschoenmaeckers commented Sep 9, 2026

Copy link
Copy Markdown
Member Author

Nice! I am a bit scared by this added complexity: do we have actual usescases where it will be useful?

My usecase is a local project that implements a FromPyObject for a rust enum. As it looks very verbose it moved me to create a macro for this.

pub enum Period {
    Daily,
    Weekly,
    Monthly,
    Quarterly,
    SemiAnnually,
    Yearly,
}

impl FromPyObject<'_, '_> for Period {
    type Error = PyErr;

    const INPUT_TYPE: PyStaticExpr = pyo3::type_hint_subscript!(
        pyo3::type_hint_identifier!("typing", "Literal"),
        PyStaticExpr::Constant {
            value: PyStaticConstant::Str("D")
        },
        PyStaticExpr::Constant {
            value: PyStaticConstant::Str("W")
        },
        PyStaticExpr::Constant {
            value: PyStaticConstant::Str("M")
        },
        PyStaticExpr::Constant {
            value: PyStaticConstant::Str("Q")
        },
        PyStaticExpr::Constant {
            value: PyStaticConstant::Str("S")
        },
        PyStaticExpr::Constant {
            value: PyStaticConstant::Str("Y")
        }
    );
}

This looks to my like a common pattern and other users may benefit from this.

@Tpt

Tpt commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

@bschoenmaeckers Make sense! Thank you!

Comment thread src/inspect.rs
#[test]
fn test_type_hint_literal_macro() {
const COLOR: PyStaticExpr = type_hint_identifier!("mypkg", "Color");
const T: PyStaticExpr = type_hint_literal!(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It hits the compiler recursion limit in macros

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting, I do not see this failure locally...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants