Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add statement to class #1201

Open
yowoda opened this issue Aug 28, 2024 · 1 comment
Open

Add statement to class #1201

yowoda opened this issue Aug 28, 2024 · 1 comment

Comments

@yowoda
Copy link

yowoda commented Aug 28, 2024

I can't figure out how to add a statetement parsed using libcst.parse_statement to the body of a libcst.ClassDef node in leave_ClassDef. Is there any easy way to implement this?

@yowoda
Copy link
Author

yowoda commented Aug 28, 2024

def leave_ClassDef(self, original_node: cst.ClassDef, updated_node: cst.ClassDef) -> cst.ClassDef:
    __class_getitem__Node = cst.parse_statement(
        "__class_getitem__ = classmethod(types.GenericAlias)"
    )
    statements = original_node.body.body
    if isinstance(original_node.body, cst.SimpleStatementSuite):
        statements = [cst.SimpleStatementLine(statements)]

    return updated_node.with_changes(
        body=cst.IndentedBlock(
            body=(
                *statements,
                __class_getitem__Node
            )
        )
    )

Ok this seems to be working, however it would be great if there could be helper functions for this so you don't have to manually check whether the class only consists of smth like class A: pass or class A: ..., which automatically appends a statement to the class body

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

No branches or pull requests

1 participant