0

I'd like to declare a variable (string, in this case) as such:

class = "this is my string"

In Python (3.6.3), and I get an error:

class = "This is my string"
      ^
SyntaxError: invalid syntax

It obviously doesn't like the fact that I'm using an equal sign (=) after class.

Let's say I really need to have a variable with the name class, and I can't change it to myClass or whatsoever, what would be the correct way of doing something as such?

1
  • 3
    just don't do that Commented Nov 8, 2017 at 13:33

4 Answers 4

5

Thankfully Python doesn't allow you to do this, class is a keyword that can't be used as an identifier. One alternative also mentioned in PEP 8 is using a trailing underscore:

class_ = ...

but you really should avoid such names since they mostly serve to confuse. You should always strive for more descriptive ones.

If class is the only option, the other (somewhat) viable approach would be to use a dictionary:

>>> names = {'class': 'something'}
>>> names['class']
'something'
Sign up to request clarification or add additional context in comments.

3 Comments

Got it! Thought perhaps there's a library or something that could potentially do this, hence I asked. I'm quite new to Python! Nevertheless, thanks heaps :)
@Sina Most languages don't allow you to use reserved keywords as variable names. This has nothing to do with libraries or Python.
@deceze,"most languages", you said. Exactly :)
4

You cannot do that, as it explicitly stated in the Python documentation:

enter image description here

link to the documentation

Comments

1

It is not possible, however it is some kind of a tradition in Python to append class _ to get a new identifier

Use like this:

class_ = "This is my string"

You can read Official Documentation

Comments

0

You can't declare reserved words as variables.

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.