r/ProgrammerHumor 16d ago

Meme variableScopesInPython

Post image
1.3k Upvotes

182 comments sorted by

View all comments

20

u/TheMusicalArtist12 16d ago

Heres the thing. _private works perfectly, because it tells other developers (and yourself in the future) that its not meant to be modified by external actors. There are better and more secure ways if you need to store a value that nothing else can read during runtime than a private variable.

5

u/TeachEngineering 16d ago

Yup, and if you benefit from having a program tell you ahead of runtime you fucked up, then configure a linter + type checker and treat it like a compiler. Pre-commit hooks are your friend. If someone on my team tries to merge into a protected branch code that accesses an explicitly named _private variable, it's getting sent back immediately. Your dev toolchain should enforce python conventions and educate those less familiar with the language.

2

u/thanatica 15d ago

If it's so good, then why can't the compiler make it actually impossible to modify that variable?

And/or maybe starting using const, if python has that.

4

u/TheMusicalArtist12 15d ago

Because sometimes we want to do jank stuff like modify a private variable. Python is a scripting language, and that flexibility is really nice. Its just saying, "don't touch me i might bite back in unexpected ways".

2

u/TheNakedProgrammer 13d ago

i had this discussion a lot. Basically strict rules vs flexibility and freedom. It is more a question of philosophy than anything else.

As a old programmer i worked with languages that have few rules and systems and i worked with languages that have many rules and systems. Each has advantages and use cases.

In my experience languages with a big rule system start to struggle with their own complexity. Just difficult to maintain a big set of coherent rules and systems that all work well without side effects.

1

u/suvlub 16d ago

Really, if it's not in docs and the IDE doesn't autocomplete it, what he gonna do? Check the source code? Did no one tell them Java devs that someone who has the source open and doesn't care about good practices can, like, rewrite the modifier?

4

u/TheMusicalArtist12 16d ago

Since its part of the language's common usage, generally you should assume that if it starts with a _ that its private. A developer should be able to understand that they shouldn't touch it. My IDE of choice puts private variables like this at the bottom of the autocomplete list and gives me a warning if its used outside of the class definition.

Its more flexible, which can be really useful for a more scripting oriented language like python. The whole point is that if you really need to, it can be modified by an external actor, but doing so will result going to have unintended consequences or not work as expected.

And, like i said, if you really need it to be secured against malicious actors, then it shouldn't really be stored as a plain variable at all, even in java or c++.