[SOLVED] Defining private module functions in python


According to http://www.faqs.org/docs/diveintopython/fileinfo_private.html:

Like most languages, Python has the
concept of private elements:

  • Private
    functions, which can’t be called from
    outside their module

However, if I define two files:



import a
print a.__num

when i run b.py it prints out 1 without giving any exception. Is diveintopython wrong, or did I misunderstand something? And is there some way to do define a module’s function as private?


In Python, “privacy” depends on “consenting adults'” levels of agreement – you can’t force it (any more than you can in real life;-). A single leading underscore means you’re not supposed to access it “from the outside” — two leading underscores (w/o trailing underscores) carry the message even more forcefully… but, in the end, it still depends on social convention and consensus: Python’s introspection is forceful enough that you can’t handcuff every other programmer in the world to respect your wishes.

((Btw, though it’s a closely held secret, much the same holds for C++: with most compilers, a simple #define private public line before #includeing your .h file is all it takes for wily coders to make hash of your “privacy”…!-))

Answered By – Alex Martelli

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *