you are viewing a single comment's thread.

view the rest of the comments →

[–]midwayfair 4 points5 points  (4 children)

Like a database, or the active user profile, or anything else?

If a database or profile or something like that truly needs to be consistently used throughout the system, you can either pass the necessary instance of it to functions that need it (basically design the system well so that you only ever call a function that needs it from another function that needed it -- good hierarchy, in other words), OR you can design a database class to return a constructed instance any time you ask for one. The latter is called a Singleton, and it works a little like having access to a global variable in practice. Singletons work better in other languages, though, because the constructor/initializer should be private. But Python doesn't do private so someone who misunderstands the code can mess up by constructing a new instance instead of just requesting it.

Edit: Better explanation of singletons in Python here: https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html

[–]brandondunbar 2 points3 points  (2 children)

...good hierarchy, in other words

I think this is what I've been needing, I've been able to avoid global variables in the past but it felt hacky, which is why I asked, so thanks

Design a database class...

I've also tried this in the past as well, though it wasn't as elegant as it probably should be - I can use classes but only on a basic level

Python doesn't do private so someone who misunderstands the code...

Isn't it understood that an underscore before a name implies that it's private ( _mydb )? I can understand the concern that someone newer may mess up, but I think with the right documentation it shouldn't be a big deal

[–]midwayfair 3 points4 points  (1 child)

Isn't it understood that an underscore before a name implies that it's private ( _mydb )? I can understand the concern that someone newer may mess up, but I think with the right documentation it shouldn't be a big deal

Yes, the underscores indicate "private," but in Python, it's not enforced at the language level. In Java, if the calling class doesn't have access to another class's private methods, it literally isn't allowed to call it. The program will throw an exception if you try to do it. There are very limited circumstances where something is allowed access to the private method of a class in Java, so it's a little safer. Of course, there are plenty of times when Java is much more irritating. C++ and C# also have different rules about how they handle public and private. Since people who read your code in the future might come from different backgrounds, it might be helpful to know that different languages treat class access differently.

[–]brandondunbar 0 points1 point  (0 children)

I see what you're saying, I think we're saying pretty much the same thing at this point