Search code examples
pythonpeewee

How to use a variable name of reserved words in Python


I've encountered a problem when I'm using peewee in python to fetch a column's data named 'class'. But 'class' is a reserved word, when I run the code it always stopped with 'SyntaxError: invalid syntax'.

Here is the code I'm using which works if I do not include the Class.class column.

query = (
    Student.select(
        Student.id,
        Student.name,
        Student.school_id,
        School.name,
        Student.class_id,
        Class.class,
        Class.grade,
    )
    .join(Class, join_type=pw.JOIN.INNER, on=(Class.id == Student.class_id))
    .join(School, join_type=pw.JOIN.INNER, on=(School.id == Student.school_id))
    .where(Student.id == id)
)

And the definition of Class.class which also causes the same error:

class = CharField(max_length=45)

It should give me a query without error. So my question is how do I use the variables of reserved name in python. Thanks!


Solution

  • In general, you can use getattr to access names that are reserved keywords; for the class attribute:

    query = (
        Student.select(
            Student.id,
            Student.name,
            Student.school_id,
            School.name,
            Student.class_id,
            getattr(Class, 'class'),  # equivalent to `Class.class` (if that were allowed)
            Class.grade,
        )
        .join(Class, join_type=pw.JOIN.INNER, on=(Class.id == Student.class_id))
        .join(School, join_type=pw.JOIN.INNER, on=(School.id == Student.school_id))
        .where(Student.id == id)
    )
    

    However, you probably want to rename the attribute in your Peewee table definition to something that's not a reserved word and use column_name='class' to have it still refer to a class attribute in the physical table:

    klass = CharField(max_length=45, column_name='class')
    # or maybe, if you prefer:
    class_ = CharField(max_length=45, column_name='class')