Reputation: 775
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
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
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
Reputation: 2604
You cannot do that, as it explicitly stated in the Python documentation:
Upvotes: 4