pythonfunctionimportmodulerestrictions

How can I restrict which functions are callable from an imported module? Can I make a function private? (Python)


For example, in file A.py I have functions: a (), b () and c (). I import A.py to B.py, but I want to restrict the functions a () and b (). so that from B.py I will be able to call only c (). How can I do that? Are there public, privates functions?


Solution

  • You could make you A.py a python package with following structure:

    B.py  
    A/
    |-- __init__.py
    `-- A.py
    

    __init__.py:

    from .A import c
    

    A.py ( example ):

    def a():
        return 'a'
    
    def b():
        return 'b'
    
    def c():
        print(a(), b(), 'c')
    

    B.py (example):

    import A
    A.c()  # a b c
    A.a()  # AttributeError: 'module' object has no attribute 'a'
    A.b()  # not executed because of exception above