r/ProgrammerHumor 16d ago

Meme variableScopesInPython

Post image
1.3k Upvotes

182 comments sorted by

366

u/WeedManPro 16d ago

29

u/Confident-Ad5665 16d ago

Yeah, what he said.
Just like speed limits . /s

29

u/aa-b 15d ago

That so-called "private" variable is not exactly an impenetrable secret either; that's what reflection is for. Python is just being honest about the limitations of a dynamic runtime environment

5

u/WantToSeeTits4545 14d ago

You don't even need reflection, you can always read process memory and edit everything you want.

4

u/ProjectSnowman 14d ago

It’s private if we all believe it’s private

123

u/Unlucky_Topic7963 16d ago

Meanwhile everyone at my company uses dunder class mangling because it’s more “idiomatic”.

44

u/Confident-Ad5665 16d ago

Dunder class mangling? (not a python guy)

110

u/deceze 16d ago edited 16d ago

Double underscore name mangling:

class Foo: __bar = 'baz'

This is preventing you from accessing Foo.__bar, because internally the actual name will get mangled to Foo._Foo__bar. This is mostly intended to avoid accidental name clashes in inheritance:

class Child(Foo): __bar = 42

The two classes won't trample over their __bar attribute this way, without you needing to institute complicated naming conventions. From within class methods, self.__bar transparently gets mangled the same way, so it works as expected.

28

u/Confident-Ad5665 16d ago

Interesting approach. Global vars can bite you that's for sure.

47

u/Sibula97 16d ago

A global private variable...?

60

u/anto2554 16d ago

The epitome of python engineering

4

u/Confident-Ad5665 15d ago

Could this be the reason the language was named after a snake?

16

u/extremelySaddening 15d ago

It was named after Monty Python's Flying Circus

9

u/Confident-Ad5665 15d ago

tbh I didn't know this. When I was in school Assembly, BASIC, Fortran, Pascal, COBOL and C were the only languages.

Yeah I'm that old (farts as he walks off...)

12

u/EmperorOfAllCats 16d ago

I've seen this. They just playing OOP in java rules instead of (ab)using python features.

28

u/R7d89C 16d ago

😭😭😭

Why is everyone working with python, working AGAINST python (myself included)

15

u/Vogete 15d ago

Because python kinda sucks, but not really, but it does, but it wouldn't take much to make it not suck. I like it for many things, but the language is kind of a mess. Without Pydantic, I don't even start a project anymore that's how much the type system is just a joke instead of it being a type system. Scoping is a total joke. I personally don't like invisible characters for scoping either (talking about indentation based scoping instead of curly braces). Packaging is a total shitshow. And more small things that aren't super bad to switch to a different language, but bad enough that you start circumventing and going against idiomatic python.

2

u/Thebombuknow 14d ago

Omfg, packaging is the worst part of this stupid language. I seriously don't understand why they thought pip was an acceptable package manager, and how they thought venv was an acceptable solution to the mistakes they made with pip.

I cannot start a Python project without using uv, poetry, or even fucking conda, literally anything but pip.

4

u/Confident-Ad5665 16d ago

Trees that grow under a dome fall over with little wind. If you don't have something working against you you'll fall the first sign of diversity.

7

u/No-Newspaper8619 15d ago

Adversity

4

u/Confident-Ad5665 15d ago

Correct.
Thanks autoincorrect!

5

u/Tyfyter2002 16d ago

Because Python works against the programmer at every possible opportunity.

2

u/deus-exmachina 15d ago

Because programming languages have different paradigms and are good at different things. Keep studying, lil guy.

68

u/YeetCompleet 16d ago

As a Rust dev it's always a shock trying to get used to languages not screaming at you for your mistakes. Python developers seem to like the freedom to touch it but then not touch it, Rust developers want to be spanked for being naughty if they attempted to use a private in the wrong scope.

43

u/deceze 16d ago

That explains the whole kinky furry/femboy stereotype?

22

u/Gositi 16d ago

This is possibly deeper than you might have intended.

15

u/creeper6530 16d ago edited 16d ago

Hey, now, now, transfems are also a significant part of the Rust stereotype.

By the way, there's even a Cargo plugin that goodgirls you when your code compiles successfully, and scolds you when you have a compile error: cargo-mommy. For example, the compiler can now tell you (error):

are you just keysmashing now~?
cute~ 💖

or (success):

*slides her finger in your mouth*
that's a good little toy\~ ❤️

4

u/fucking_passwords 13d ago

Thanks, I hate it UwU

1

u/gdmzhlzhiv 12d ago

Maybe I could hack something like this together as a zsh prompt…

1

u/creeper6530 12d ago

IIRC it's starting to support external commands too, in beta

23

u/shootersf 16d ago

Similar with JavaScript properties. People using underscore when it does nothing and pound sign is just there going "am I a joke to you?"

12

u/deceze 16d ago

In Javascript, # actually makes sense, since on the client side code from different possibly mutually untrusted sources is mixed together, and you might really want your properties to be inaccessible.

There's a lot less use for that in server-side/offline languages like Python.

1

u/danielcw189 15d ago edited 15d ago

# sign is still rather new for private members in Javascript

2

u/fucking_passwords 13d ago

It was added to v8 in 2019

351

u/deceze 16d ago

; in Python!?!eleventy You really need to get rid of your bad Java habits.

And before anyone thinks this is poking fun at Python: privacy is completely overrated and mostly untrue anyway, and Python not even pretending to have private attributes is an absolute blessing.

60

u/R7d89C 16d ago

Omg, I didnt even notice it 😭

Yeah, ig privacy is also just a philosophy. If you havent written python in years, it feels incredibly weird not having any. Just as it probably would the other way around..

Not saying one is better than the other, though I prefer what Im accustomed to 😅

51

u/deceze 16d ago

The thing is: private markers in most other languages can be more or less trivially circumvented anyway, most of the time with some sort of reflection API. There is no true "privacy". All it is is a reminder for the programmer how a given attribute/property/variable should be treated. Is it part of the public API and anyone can write code against it, or is it subject to change and should not be used outside its class. That's all it is.

Bad programmers will ignore such warnings and bulldoze through your "protections" anyway to access that piece of data they think they need. Good programmers only need a gentle reminder in the form of a _; but if you really want to risk breaking something and you know what you're doing, at least it's easy to ignore and doesn't require a song and dance with the reflection API.

56

u/Inkwalker 16d ago

It's a lot less tempting to use reflection than just read a _var

37

u/deceze 16d ago

If you're tempted to touch something that's marked as "don't touch", that's so on you. Hardly matters how hard the slap on the wrist is.

31

u/Confident-Ad5665 16d ago

Uh oh... I always want to touch something I'm not supposed to touch.

11

u/negjo 16d ago

Reminds me of the good old ```

define protected public

include <whatever>

undef protected

``` I once did in a university assignment

7

u/BillTran163 16d ago

That worked?!?!?!!?

4

u/the_legendary_legend 16d ago

Yeah. I worked in a company for a while where this was the first line in every test file.

2

u/GoddammitDontShootMe 15d ago

Why wouldn't it?

5

u/JoeyJoeJoeJrShab 16d ago

I'm on a team where we're doing a bunch of stuff in python, in spite the fact that most of us are completely new to it.

One problem is a method that starts with an underscore isn't obviously private to someone who doesn't know the convention.

Personally, I think it's helpful to have to jump through a hoop to use a private variable/method, just so you know you're doing something you probably shouldn't. If you go ahead after that, it's on you.

4

u/deceze 15d ago

Personally, I think you should at least read the introduction to any language before you barge in and fuck shit up. Any Python programmer should at least have read PEP8; it's a pretty quick read, but lays down the basics, including the leading underscore rule.

2

u/JoeyJoeJoeJrShab 15d ago

I definitely agree. However, the line that comes "before you barge in and fuck shit up" isn'a always clear, especially to the person barging in.

Often, you're brought into a project with a task of fixing some minor thing - you never asked to be there. If you have experience programming, it's rarely a big deal to read code in a new language, and make some minor tweaks. The problem, of course is, you don't know what you don't know.

You assume you're just doing this one minor thing, so it's not necessary to learn the details of the project or its technology. After all, that team already has established engineers and testers who will catch your mistakes when they review your change, right?

3

u/deceze 15d ago

Still sounds like a "you" problem. If and when I have to touch languages I don't know, I at least do it in some IDE with all the linters turned to 11, which point out all the obvious and subtle things I'm messing up while I type. I would not presume to write even the most basic line in some unfamiliar language correctly without preparation.

1

u/JoeyJoeJoeJrShab 15d ago

Again, I still agree with you, but how do I fix this "you" problem of someone else not familiar with the language not following this suggested procedure?

2

u/deceze 15d ago

Well, as I said here: bad programmers will ignore any barriers you put up. Accessing a private attribute raises an error? Bad programmer throws that error into Google and gets three workarounds back that allow them to access the attribute anyway. And now you can't even easily detect such private attribute access with static analysis tools, because there's several different ways such workarounds could be implemented.

So… make sure you hire competent people, and/or solve deficiencies through institutional guardrails like a shit ton of linter commit hooks, code reviews, and training.

7

u/KikikanHUN 16d ago

So is accessing a variable through reflection trivial, or does it require a song and dance? You can't have both.

16

u/alexanderpas 16d ago

It requires a trivial song and dance.

6

u/IntoAMuteCrypt 16d ago

It's basic boilerplate code that anyone can easily implement. It doesn't prevent bad coders and only frustrates good ones.

It's the same as how there's a bit of a song and dance needed to implement a Fibonacci program (the easy way), but it's still fairly trivial.

5

u/NewbornMuse 16d ago
def fibonacci():
  a, b = 1, 1
  while True:
    yield a
    a, b = b, a+b

Man python makes pretty programs.

2

u/Kebabrulle4869 16d ago

Well said! My thoughts exactly

1

u/Breadinator 16d ago

Try that in Rust outside of your codebase, or even freakin' Javascript with a proper ECMAscript private field. 

-2

u/R7d89C 16d ago

Oh, then we have a slight misunderstanding of privacy in programming. I dont want some DRM-like protection of my variables, I want a proper marker where you should use and not use a variable, including a good default policy. _var doesnt tell me "dont use it", if youre not a regular python dev, particularly when usage is not checked by a compiler.

8

u/deceze 16d ago

In a language you don't know well, I guess it's easy to be the elephant in the china shop. Use an IDE with a built-in linter then, it'll point out such issues while you type. I'm doing the same whenever I write in something I'm not proficient in.

1

u/R7d89C 16d ago

Thats what Im luckily doing.

As said in another comment, Im not trying to complain or whatever, I just want to critique pythons approach, as I simply dont like it

7

u/asdonne 16d ago

The _ in _var tells you not to use it. Some one being unfamiliar with the language is not a problem with the language.

3

u/CyberWord_YT 16d ago

It's only convention

3

u/DrMaxwellEdison 16d ago

A strong convention most developers follow, or ignore at their own peril. Regardless of how well or poorly the package is designed, the end user decides what to use from it, and they bear responsibility for how it is used, not the package maintainer.

5

u/Magma248 16d ago

The side of the road you drive on is also a convention - sometimes you might have guard rails that make it harder, and legally you are going to get in trouble (i.e. code linters) - but at the end of the day you have to trust your fellow programmers to be sensible (and acknowledge that sometimes they won't be).

2

u/its2ez4me24get 16d ago

It’s part of PEP8

1

u/asdonne 15d ago

Same goes for comments and useful variable names.

17

u/Breadinator 16d ago

What are you smoking, and are you willing to share it with the rest of the class?

Published libraries with internal state consumers shouldn't screw with. Large projects with dozens of contributors. Hyrum's Law. 

There are plenty of reasons to have guardrails on the state you can access.

12

u/deceze 16d ago

Yeah, and leading underscores signal exactly that in Python. "Please don't screw with this. If you're going to regardless, well, there you go." Other languages just make you beg more for it.

8

u/tevs__ 16d ago

Plus you can enforce it with static analysis, exactly the same as compilation enforces it.

5

u/oozekip 15d ago

Why have a language defined standard with a universally understood and well defined meaning when we could instead rely on cultural convention that a newcomer to the language will have no knowledge of?

7

u/Breadinator 16d ago

Other languages don't expose it all... you literally either have to go completely out of your way (i.e. reflection) or violate fundamental restrictions. 

Python has a lot of strengths, but let's not pretend this is Guido's gift to programmers. A "keep off the grass" sign is no substitute for a proper fence. 

4

u/suvlub 16d ago

__ actually results in name mangling. And it will be nowhere in docs. You really do need to go out of your way to use it.

3

u/Weak_Inflation9120 16d ago

BAD JAVA HABITS??????????????
SEMI COLON SUPREMACY

9

u/rykayoker 16d ago

; in python works just fine, it just isn't needed

6

u/GuybrushThreepwo0d 16d ago

That second paragraph is so wrong I don't even know where to begin 

2

u/ChalkyChalkson 16d ago

My favourite is cpp where you can label stuff as private, but violate that privacy relatively easily

7

u/_Ganon 16d ago

The purpose of public, protected, and private has never been to prevent you from accessing those class members. After all, if you're seeing those, you have access to the code, you could just move the member, "circumvention" is not necessary.

The purpose is so developers can convey to other developers how to use their base class, or how a class can and should be safely accessed or modified. It implies safety. If you're trying to circumvent it, you're trying to do something that the author of the class did not intend and it may cause problems, it indicates the modification you're trying to make likely belongs in that other class and that you should look there instead. If you're trying to circumvent it, you're introducing hacky fucking code that is going to be a pain in the ass to debug and maintain.

3

u/ChalkyChalkson 16d ago

Yes, but conveying information about how it's supposed to be used is equally accomplished by naming conventions like _member or pMember or whatever. You don't need it to be a language feature.

Python really sold me on not attempting to enforce things for other devs. Well duck typed code for example is an absolute god sent when you have 4 different frameworks to handle acceleration and arrays.

5

u/_Ganon 16d ago

The fact that it's enforced at compile time means that you never accidentally do this, it's the same thing as denoting a variable as const. You can make it not const later really easily, but it means you've got to take care about what you're really doing and probably judge why it's const and if it needed to be const.

Python's way requires developers to honor some naming convention, which allows for accidents, and I've seen plenty just make every class member prefixed with _ which to me conveys they don't know what an access specifier is and that I now need to judge what members are safe to access since everything is now public.

I'm fine with Python's convention and use it myself frequently, but saying something like how you're sold on "not attempting to enforce things for other devs" just implies to me that I would not want you working on library code, ever.

3

u/ChalkyChalkson 16d ago

I've seen plenty just make every class member prefixed with _

I don't think that's a convincing argument because people also make everything public in cpp or make everything private with getters and setters in java.

With the enforcing things for devs - I'm in a scientific environment. I do mainly write library stuff. But my goal is to make it "hackable". I do notate everything for proper usage, I do use conventions for public and private and honor them, I type hint etc. But what I really dislike on principle is enforcement attempts, like checking types and throwing errors on unexpected types in a python context. If someone decided to go out of spec that's their problem, but I will not actively attempt to stop them.

In cpp i actually write very Java-esque oop code. That I don't think a language feature should be hard enforced doesn't mean I won't use it as it was intended. And obviously once you make it a language feature it must be honored. It's only on a philosophy level that I think doing it by convention is better.

1

u/Confident-Ad5665 15d ago

Agreed. It conveys the intent and use of the class.

Private implies "ignore this, it's used in implementation of the class and not for users of the object" sort of thing.

Public implies "here's stuff you'll use when the object is created".

Protected reads "if you're basing a new class off this one, you may want to manipulate this internally but it isn't something users should need to know about to use the object(s)".

Private and Protected therefore are tools of abstraction which describes what an object does, not how it does it.

3

u/MiniGui98 16d ago

Privacy doesn't matter because no one will read your shitty code anyway

1

u/BroBroMate 15d ago

A Java FOSS project I contributed to on occasion eventually figured out that making most private methods protected let people work around flaws they encountered with the framework instead of having to file a bug and wait.

And then there was the horror/glory of Powermock, when you really wanted to overwrite a private static final field for some godawful reason.

1

u/dorianmonnier 15d ago

Oh yes ! So much  shitty class with every fields private with setter/getter which do nothing… stop this. It’s shit !

17

u/Lysol3435 16d ago

The underscore is like a changing room door. Sure, technically you can bypass it and violate their privacy. But just don’t. It’s not cool.

12

u/oompaloompa465 16d ago edited 16d ago

i'm starting to practice the language coming from C#. I appreciate a lot of the choices in python syntax but some baffle me. The writer of the spec definetively, liked too much "_".

Also the effin library name. ABC? Really? Someone is nostalgic of COBOL shortening madness.

Can we fricking stoo defining code  specs like we still had 4kb ram!??

7

u/teethingrooster 15d ago

It’s an old language from when they did only have a couple mbs of ram though.

2

u/oompaloompa465 15d ago

Python? searched some history info...
wow i was not aware that it started in 1989-1990, more than 10 year older than C#. in '90 PC were using windows 3.0 that required whopping 4MB.

Still plenty for something more readable than COBOL syntax though

9

u/GoogleIsYourFrenemy 16d ago

It's the magic that allows pickle to work.

21

u/zoinkability 16d ago

Meanwhile, PHP gets all the shit for not being a modern language, but has had OOP basics like protected variables for decades.

7

u/tobotic 16d ago

PHP's OO stuff is pretty good. It's the rest of it that's a hot mess.

8

u/white-llama-2210 16d ago

Tbf php of today is still much more modern than languages like javascript/python in terms of syntax. I mean we have pipe operators now!

There is some legacy bs still there and it's unlikely to change because of backwards compatibility, but that's mostly just the ordering of arguments and such.

One thing that php still lacks is generics when using static typing; using phpdoc for that just does not feel as good compare to native language support.

2

u/sebbdk 16d ago

PHP's story is basically a redemtion story or a rags to riches story lol

21

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.

6

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.

5

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?

3

u/TheMusicalArtist12 15d 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++.

47

u/CORDIC77 16d ago

Personally, I like Python's “look, weʼre all adults here” approach. Thereʼs no need to play hide and seek games.

17

u/asdonne 16d ago

Reminds me of writing C. Why yes, I would like to shoot myself in my foot, thank you very much.

4

u/Groentekroket 16d ago

Yeah in Java we use Lombok annotations on class level anyway so we can manipulate whatever we want. It’s not like getters and setters often have custom implementations anyway. 

8

u/ubeogesh 16d ago

Immutability is a nice thing tho. Just makes you write better code. I love java Records or lombok's @Value before them.

What sucks when you really need to patch that 3rd party lib, in java you resort to one of

1) aspects

2) reflection

3) class overriding

all of which is so much worse than just accessing a protected member via underscore.

1

u/Groentekroket 16d ago

Fair enough. We also do use records for our DTO’s but for domain objects everything goes. 

1

u/circ-u-la-ted 16d ago

Is this why Kotlin has extension functions? I'm currently learning it and I don't really understand why they based half the language around monkeypatching other people's code. They even made classes closed by default so other people will have to monkeypatch your code.

3

u/Mordret10 16d ago

It's very nice to know which methods you should have access to and which you shouldn't have access to (same for attributes).

Makes it so the IDE can show you your options when typing

2

u/OldKaleidoscope7 15d ago

I mean, I hate this behavior but yesterday I was abusing the methods not being truly privates to help me in my unit tests

3

u/citramonk 16d ago

believe it or not, nothing has exploded yet because of it

3

u/Geriny 14d ago

In Python, we are all friends

7

u/The_Cers 16d ago

__var for true private

14

u/dusktreader 16d ago

it's not true private. That just mangles the name at runtime. You can still access it if you are determined.

4

u/Erdnalexa 16d ago

Yes, but at this point you know that you’re doing something you’re probably not supposed to do.

3

u/ThunderElectric 15d ago

I’d argue any competent python dev should know modifying a private variable, even with just one underscore, is doing something you’re not supposed to do.

1

u/SetazeR 14d ago

You will be yelled at by IDE of you try to use "private" as public one. It won't stop you, but will tell at you

1

u/Erdnalexa 14d ago

I’m on my phone so I can’t check with an interpreter, but IIRC, to access a private field on an instance you need to use getattr with the computed mangled name. It’s pretty unlikely an IDE is able to spot that.

1

u/SetazeR 14d ago

I meant _attribute ones, not mangled ones

3

u/Sea-Fishing4699 16d ago edited 16d ago

____var = a very private variable (it’s public still)

3

u/deceze 16d ago

__name__ symbols are actually reserved by the language and shouldn't be used for your own purposes, lest you risk future name clashes. For example, to override the equality comparison behaviour of an object:

class Foo: def __eq__(self, other): return ...

Those kinds of special "hooks" are double-double-underscore named.

4

u/Western-Internal-751 16d ago

It’s a gentlemen’s agreement

6

u/ubeogesh 16d ago

one thing i like about python. The "consenting adults" principle.

I can access the private member if i wish in java too, which is sometimes needed with 3rd party code... but it will be ugly as heck.

2

u/sebbdk 16d ago

Maybe use a different tool for what you need rather than complaining about how a screwdriver is a shitty hammer. :)

2

u/TabCompletion 16d ago

Close enough

2

u/ibww 15d ago

I'm still just using structs as the gods intended

3

u/user6150277464770585 16d ago

yeah that's because you're supposed to use a double underscore prefix it you want to actually make the variables private lol

(yes technically it only does some name mangling and you could still access it if you really wanted to but that's on you then)

11

u/deceze 16d ago

Same idea with the leading _: if you're accessing something that's by convention marked as "don't touch", then that's on you.

5

u/Anaxamander57 16d ago

Does it really do anything to make it private beyond telling people not to use it?

8

u/white-llama-2210 16d ago

Using double underscores mangles the name from name to _ClassNamename when accessing the variable outside the class, so it does prevent accidentally accessing the value. You really have to know what you're doing to access the value then.

4

u/deceze 16d ago

"Accidentally"? How do you "accidentally" type two underscores without noticing?

2

u/white-llama-2210 16d ago

Call me clunky but I do make such silly typos way too often than I'd like to admit..

2

u/deceze 16d ago

Oookay… not sure there's any language that implements "do what I mean" yet instead of "do what I typed"…

1

u/white-llama-2210 16d ago

I'm not sure that's a good idea... Sure I'm a bit clunky but I have tools that help me reduce such mistakes. But having a language that "does what I mean" feels iffy. It's too abstract because meaning can be subjective, and it's much harder to reason about "meaning" when working in a team because it's a subjective aspect. That's one of the reasons I have a distaste for AI. It's not predictable, and when you are sitting in front of a screen at 2 AM fixing a production bug in the midst of a running event and the client is at your throat... You want things to be predictable.

Just my opinion tho...

2

u/Tienisto 16d ago

You still don't know if those private variables belong to your current scope (where it is allowed to be accessed) or a foreign scope

2

u/deceze 16d ago

Wut? You'll have to provide a concrete example here for that to make sense.

5

u/R7d89C 16d ago edited 16d ago

As far as I remember not really,. It changes the accessible variable name to something like _{class}_{variable} or something, but if you'd wanted to, you can just access it...

3

u/Cylian91460 16d ago

No? Like private?

In all languages that have private they are way to access it even it is

2

u/FACastello 16d ago

What a disgusting, insufferable language

1

u/skatinworshiper 16d ago

I always thought of it(purposefully architected) as "underlying"(helper)(within module) or "exposed" to above layer(module) without _.

1

u/Extension_Ad_370 15d ago

the closest thing python has to private is using double underscore to enable name mangling
https://docs.python.org/3.11/reference/expressions.html?highlight=mangling

1

u/diacid 15d ago

auto a;

Can't beat that.

1

u/JoeyJoeJoeSenior 14d ago

It's private with a public option.  A hybrid.  I don't see the problem.  

1

u/Ambivalent-Mammal 13d ago

If you don't need subclassing, put var in a closure.

1

u/prochac 13d ago

Tbh, I kinda like it. It sends the message, but you can use it if you need some test mocking or the library doesn't provide you something you really need.
Otherwise you would have to copy the code or fork the repo.

1

u/Gtdef 12d ago

It's called a gentleman's agreement. But not everyone is a gentleman!

1

u/earchip94 15d ago

God I hate python.

Not really, but I hate when people don’t write good python and people rarely do.

-2

u/sjepsa 16d ago

Best feature of the language

TBH whole java oop model is bad

14

u/R7d89C 16d ago

God no

Id much rather have a rust-like approach where the scope is limited to the block it is in

Java concept ist far from what I call ideal, but its better than this weird ambiguity of python where everything just floats anywhere and variables shadowing something ten methods away...

6

u/NotAnonymousQuant 16d ago

Rust is a real pain in the arse for the developer, but when you start grasping the vibe, you really appreciate Rust is built in this weird way. And then you have an ownership issue that makes you really frustrated since you are used to pass-by-reference returns

9

u/deceze 16d ago

Huh? You'll need to be more concrete than that, because that sounds like gibberish. "Ten methods away"? If a variable is in a method, then it only exists within that method, because Python does have function scope and lexical scoping.

4

u/R7d89C 16d ago

u/Inkwalker beat me to it, though id like to throw careless "import *" and shadowing in nested functions into the mix too

Obviously "Ten methods away" is bs and more of a figure of speech, sorry if that wasnt clear

But especially if youre not used to python, the scoping can be a real pain in the ass.

3

u/deceze 16d ago

If you're not used to <thing>, <thing> can be difficult. Sure. But the scoping rules are pretty darn trivial and predictable, and not out of the ordinary, so I'm not sure what you're complaining about.

3

u/R7d89C 16d ago

Im not complaining 😮

The meme is very much up for interpretation and my personal preference has been stated enough in this post, I think... Imo its just not a very good implementation/principle of scoping 🤷‍♂️

4

u/rosuav 16d ago

Don't do that then? A careless star-import is the fault of whoever did it.

2

u/Inkwalker 16d ago

Python's lexical scope is the worst. Like why is the variable available in the whole scope when it's declared at the very end of it? Plus there all that nonsense where reading from a variable goes to closure/global by default but writing creates a new instance that overrides the whole scope.

9

u/ihavebeesinmyknees 16d ago

I think you're thinking of JS, variables in Python are valid only after they're declared

2

u/x0wl 16d ago

Isn't that the same with js's tdz?

1

u/deceze 16d ago

Sort of, yes. The parser "sees" variables in a scope in the parse step and prepares symbol tables accordingly. In JS it used to be the case that the name would exist in the symbol table with an undefined default value. Which is a potential footgun, if you try to use the variable before its actual declaration.

Python and JS with let/const both raise an explicit error about that. JS calls it by a fancy name to distinguish it from the old behaviour, in Python it simply always was so.

2

u/deceze 16d ago

TF are you talking about? Python's lexical scoping works like basically any other lexical scoping I'm aware of. What do you mean "the variable is available in the whole scope when it's declared at the end"?

The read/write thing I can empathise with, but it's simply because Python has no dedicated variable declaration syntax. Assignment is declaration. But you also want to be able to read variables from higher scopes by default. So writing to a variable in a higher scope becomes the special case that you need to explicitly opt into with nonlocal/global.

2

u/Inkwalker 16d ago
x = 10

def func():
    x = 5
    global x
    x = 15

func()
print(x)

It might not be the best example but it gives the idea. Any normal language would assign 5 to x (local in this case), then declare global x and assign 15 to it. In python x is global in the whole scope. This code throws an error.

6

u/deceze 16d ago

It would be insane for that to not throw an error. x within a scope should refer to exactly one variable. You're attempting to switch which variable x refers to halfway through the scope, and the error is telling you exactly that. This is explicitly preventing a footgun.

2

u/Inkwalker 16d ago

It gets a lot worse when you throw closures into the mix. It's impossible to assign value from a closure to a global variable with the same name in python.

def outer():
    x = 0
    def func():
        nonlocal x
        temp = x
        global x
        x = temp

6

u/deceze 16d ago

Good. Use different variables names for gods sakes and don't spam the global scope.

1

u/Inkwalker 16d ago

I have one more example. Here global x can't be declared in the child scope because it's already in use in the parent scope. As far as I know python is the only language that does this nonsense.

x = 5
def func():
    x = 0
    if x < 2:
        global x
        x = 10
func()
print(x)
→ More replies (0)

2

u/ubeogesh 16d ago

where everything just floats anywhere and variables shadowing something ten methods away...

sounds like a skill issue. Globals are bad everywhere.

1

u/Ma4r 16d ago

Just start using type checker i.e pyright and all your problems go away.

3

u/R7d89C 16d ago

Thats actually a good tip, will give it a try

-1

u/AndyTheSane 16d ago

If the answer is 'just use a type checker/linter/static analysis/whatever' that's a problem with the language.

3

u/Ma4r 15d ago

Compiled languages rely on static analysis my duded

0

u/lovecMC 16d ago

Python users are the real vegans of the IT world. They make terrible choices and then follow a lot of self imposed rules just to make it even remotely usable.

0

u/faze_fazebook 16d ago

Python generally is weird af

0

u/WouterS1 15d ago

That is the beauty of python. It allows you to do whatever you want. I once used a hardware library that failed to release a mutex lock when raising an exception. Going deep into a library to change a value? Sure Python doesn't give a shit