First of all, sorry for the wording of the title, I can’t think of anything better but I’m open to suggestions.
I want to refactor some constants so they share namespace in a Python project. Something like this:
class MyNamespace():
""" Does NOT need to be a class, this is just an example. """
AVOID_MAGIC_NUMBER: int = 10
SOME_TEXT_OUTPUT_MESSAGE: str = 'something'
FREQUENTLY_USED_INIT_ARG: str = 'magic initialization argument'
THIS_IS_A_WELL_KNOWN_FILENAME: Path = Path('some_hardcoded_filename.txt')
BASE_FILENAME: PATH = THIS_IS_A_WELL_KNOWN_FILENAME.stem
HERE_IS_AN_OBJECT = DefinedElsewhere(FREQUENTLY_USED_INIT_ARG)
The fact that they are not real constants is not an issue. My needs:
- A namespace, so the variable names do not clash with imported symbols, locals, etc.
- Some of the attributes need to refer to previously defined attributes, sometimes.
- If some attribute stops being used in the code, the IDE should detect it and mark the variable as unused. This is probably the most important point.
- Optionally, it allows me to use type annotations, but I can live without this.
So far I’m using class
because it fulfills 1
and 2
, but I’ve also tried @dataclass
, NamedTuple
, etc. All of them work perfect for 1
and 2
. My problem is with 3
.
No matter the linter, type checker, etc. I use, unused class attributes are not deteced as such, for obvious reasons.
Is there any way I can have a namespace, with attributes which can reference other attributes within the namespace (so, no SimpleNamespace
), and which IDEs will detect unused attributes? Frankly, I’m out of ideas.
My IDE of choice is Visual Studio Code, but I assume that any solution working for some IDE will work for mine, too, since most of them use pylint
, Pyright
, Ruff
, etc.
Thanks in advance!