1

Im using flask with sqlalchemy.

I have a Model that is defined as such:

class Employee(db.Model):
    id = Column(Integer)
    class = Column(Text) #Can I do this? I need a field named 'class'.

If not, then how can I define variables in python that are the same as keywords?

2
  • 5
    You cannot do this, because class is a reserved word. You can name it class_ if you want, that's what , e.g.,beautifulSoup does. Commented Apr 4, 2017 at 6:21
  • klass is an alternative. Commented Apr 4, 2017 at 11:30

3 Answers 3

2

Saying

class_ = Column('class', Text)

will give you an orm field known as "class_" corresponding to a column in your database named "class". It sounds like this may be what you are trying to do.

It may or may not be the best thing to do. You may be better off doing something like

clas = Column(Text)

and intentionally spelling it "funny", just to keep things simpler in the long run. SQLAlchemy is really happiest when the orm names are the same as the column names.

(Does this address your question?)

Sign up to request clarification or add additional context in comments.

1 Comment

(porque downvotar?)
1

You can't define a variable with then name class, as class is a reserved keyword.

https://docs.python.org/2.5/ref/keywords.html

2.3.1 Keywords

The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:

and del from not while as elif
global or with assert else if pass
yield break except import print class
exec in raise continue finally is
return def for lambda try

If not then how can I define variables in python that are the same as keywords?

As suggested in the comments you can append a character (e.g. _) after the word, and that will compile fine.

Comments

-1

'class' is a protected word in Python, pretty much meaning that you can't overwrite it. If you want to have something similar to 'class', as a variable, then I suggest using 'Class' or 'class_(class name/topic)' to overcome your issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.