3

I am refactoring a small codebase from Python 2 to 3 (3.4 specifically), and one of the ways I can make the codebase better and more maintainable is by solving all the little PEP based complaints that Pycharm displays.

One of the problems is the usage of variables that could potentially be empty/uninitialized. An example:

if condition1:
    variable1 = parse_something(a_parameter)
elif condition2:
    variable1 = parse_something(another_parameter)

local_call(variable1)

The right thing to do would be to declare the variable before all usages. Therefor, I would like to annotate the variable type along with the declaration. This is what I do:

variable1 = None  # type: ArgumentParser
if condition1:
    variable1 = 5
elif condition2:
    variable1 = 10

local_call(variable1)

Annotating the type of course gives me more code completion options further down the line. However, the PEP scan complains about the following: Expected type 'ArgumentParser', got 'None' instead. Which is true. The solution seems to be to annotate the variable as optional, from typing:

from typing import Optional

variable1 = None  # type: Optional[ArgumentParser]
if condition1:
    variable1 = 5
elif condition2:
    variable1 = 10

local_call(variable1)

However, that package doesn't seem to be available everywhere where the software should run. And, thinking about it some more, I ask myself: Why would I need to annotate the variable as Optional? Isn't that basically the standard behaviour of all variables?

So, my predicament is this: I do not get why I need an optional, separately installable package, to annotate that a variable is able to be set to None, when I perceive this as the default for all variables in Python anyway? Can I get around that any other way?

Note 1: I know that Python 3.4 is no longer supported. On the systems the software needs to be run, there is no other version available, as the platforms are running on LTS Linux releases.

S.B
  • 13,077
  • 10
  • 22
  • 49
0xCAFEBABE
  • 5,576
  • 5
  • 34
  • 59
  • 1
    This is not helping your case directly, but in a new variable annotation has been introduced in python 3.6 which address this specific problem. See https://www.python.org/dev/peps/pep-0526/ and in particular the example `captain: str # Note: no initial value!` – alfajet Nov 14 '19 at 12:18

0 Answers0