0

The following code

class base:
    var: int

doesn't seem to work with python2.7 and gives this error:

    var: int
       ^
SyntaxError: invalid syntax

It seems I need python3.6 or later to use attribute annotations. I am wondering how I can achieve similar functionality for python2.7?

1 Answers1

3

I think what you are actually trying to do is typing hint in python, which is only available after python3.5 (https://docs.python.org/3/library/typing.html), so it's not possible in python2.7.

You probably should just use comments for this.

TYZ
  • 8,466
  • 5
  • 29
  • 60
  • I see, so this question https://stackoverflow.com/questions/75416237/does-annotating-instance-attributes-in-a-base-class-result-in-functional-changes is related to the current question because I'm trying to figure out if I even need to use the annotations. I'm not familiar enough with Python to know whether it is standard to include the variables or not in an abstract base class when it won't be initialized until the derived classes. If it's not needed to include, then the current question is no longer relevant – structuralengin Feb 13 '23 at 14:03
  • @structuralengin I would say it's not really a standard since the `typing` isn't going to enforce the type of the variable, rather just as a hint (thus the name `typing hint`), you will be able to do something like `a: str = 5` to confuse others and not get any error. The whole purpose of introducing `typing hint` in python is to provide more information on the variables when the kind of declaration in other languages is not possible, it has not thing to do at runtime. – TYZ Feb 13 '23 at 14:20
  • Sorry I mean is it standard to introduce those attributes in the base class in this case? I don't actually care about the type annotations itself. My purpose with using the annotations was really to just "introduce" those variables in the base class. – structuralengin Feb 13 '23 at 14:28
  • 1
    @structuralengin To define those variables or not in base class depends on your overall design of the base class and how it will be used. If you always need to define those in your class that's inheriting the base class, then why not initializing them in your base class, etc.? It's more like a software design preferences etc and what makes sense and what don't. – TYZ Feb 13 '23 at 15:13