Share your repls and programming experiences

← Back to all posts
Private Variables in Python!

#Private Variables in Python...

Disclaimer - This is a "bug" and might be removed at anytime

First of all, you might ask, "What is a private variable"? Well... A private variable is a variable that cannot be accessed by any import statement etc.

How it works

This "bug" works on the fact that in python, there are a few attrs that are in each module they are: '__annotations', '__builtins', '__doc', '__loader', '__name', '__package', '__spec'. If you notice them, they all start with a \__. Next in python, there are 2 types of import statements, the py import module or from module import attr (this "bug" only works with the second). In from module import * it import everything right? Wrong (kind of) it imports everything except variable that start with \__ because otherwise, it would override the __name attr in the current file (I think you can see where I am going with this)... So to create private variable, we just need to make the variable start with a \__ and HOORAY! We have private variables!


Some code would be nice :)