How to make a module function visible only inside the module?

Discussion in 'Python' started by beginner, Aug 19, 2007.

  1. beginner

    beginner Guest

    Hi Everyone,

    Is there any equivalent version of C's static function in Python. I
    know I can make a class function private by starting a function name
    with two underscores, but it does not work with module functions.

    For exmaple, __func1 is still visible outside the module.
    """my module""

    def __func1():
    print "Hello"
    import mymodule


    beginner, Aug 19, 2007
    1. Advertisements

  2. The trick for the name mangling does not work at module level. Anyway,
    if you read the PEP 8 [1] you can correctly write your code following a
    well known coding standard. A function like this:

    def _f():

    is meant to be private, you can also state it in the function's
    docstring to be more clear, if you want, but it's not necessary
    Yes, and _f() will also be. There's no such thing as enforcing
    encapsulation in Python, even the "__method()" trick can be easily
    bypassed if you have to.

    1 - <>

    Lawrence Oluyede, Aug 19, 2007
    1. Advertisements

  3. beginner

    beginner Guest

    Thanks a lot. I was using two underscores, __module_method() as my
    static method convention, and then I had some problems calling them
    from inside class methods.
    beginner, Aug 19, 2007
  4. *Please* do yourself and other people that sometime may have to read
    your code a favor and write code at least loosely oriented to
    PEP 8.

    BTW, Python has no "static methods" at module level. And I suppose
    what you call "class methods" actually aren't.


    Bjoern Schliessmann, Aug 19, 2007
  5. beginner

    beginner Guest

    I just started learning the language. I wasn't aware of the PEP.
    beginner, Aug 19, 2007
  6. The convention is to use a single leading underscore _f to indicate
    private things.
    When you see something like:

    from some_module import _function

    you know you are messing with internal stuff.

    There is another form of import:

    from some_module import *

    that will import all public names defined in some_module, into the
    current namespace. By default, the public names are all names not
    beginning with "_" - but you can customize it defining __all__ which
    must be the list of public names. (Note that this form of import is
    strongly discouraged).
    For more info, see the Reference Manual: <
    Gabriel Genellina, Aug 19, 2007
  7. Mh, two postings before Lawrence already mentioned it.

    I suggest looking through the BeginnersGuide.


    Bjoern Schliessmann, Aug 19, 2007
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.