Sina
Sina

Reputation: 775

Declaring a variable in python with the name 'class'

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?

Upvotes: 0

Views: 86

Answers (4)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160667

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'

Upvotes: 5

iamsankalp89
iamsankalp89

Reputation: 4749

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

Upvotes: 1

karthik reddy
karthik reddy

Reputation: 479

You can't declare reserved words as variables.

Upvotes: 0

asakryukin
asakryukin

Reputation: 2604

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

enter image description here

link to the documentation

Upvotes: 4

Related Questions