talkpython / 100daysofweb-with-python-course

Demo code and resources for our 100 Days of Web in Python Course
https://training.talkpython.fm/courses/explore_100days_web/100-days-of-web-in-python
630 stars 390 forks source link

Question: double forward underscores #30

Closed vyahello closed 4 years ago

vyahello commented 4 years ago

Hey guys, I'm pretty excited about your course and job you have done to make it, that's really thorough work.

But sometimes I'm getting a bit confused when seeing double underscores in functions/variables names in various 100DaysOfWeb chapters. I know that those are used as super-private objects or relative, but can you guys explain me as experts, what is reason to not use a single forward underscore as conventional privacy in python but use double underscores? For instance, please take a look at a code snippet below (chapter 33-36). Can't we use just self._result name instead of self.__result here to mark that it should be a private one?

class switch:
    __no_result = uuid.uuid4()

    def __init__(self, value):
        self._found = False
        self.__result = switch.__no_result

Do you think it's worth to mention that somewhere in a course? thx

mikeckennedy commented 4 years ago

Hi, the reason we don't cover this deeply in the course is we are just reusing that python-switch library from github. So we didn't discuss the internals.

But the reason for __thing and why this is better than a convention of just _thing is that the runtime makes it truly hidden, not just devs thinking to themselves it should be hidden. For example:

print(switch.__no_result)

will result in the error:

AttributeError: type object 'switch' has no attribute '__no_result'

That is much stronger just some convention that you might or might not know that you should not touch that. You can do whatever you want with switch._no_result from Python. That's the idea. :)

cc @hobojoe1848 @bbelderbos