0

The basic idea of this is to have a variable that can only be used in the same script it is defined/declared scope. So even if you import the script to another file you still can't access that variable. Basically a local scope but for the script file. Sorry if i'm bad at explaining.

Because normaly you can just do this:

Script a (the script with the variable)

scriptvar = 21
def somefunction():
  return "banana"

Script b (the script that should not be able to access the variable)

import script_a
print(script_a.somefunction())
print(script_a.scriptvar)

Script b should return

>> banana
>> AttributeError: module 'script_a' has no attribute 'scriptvar'
  • 2
    Does this answer your question? [Defining private module functions in python](https://stackoverflow.com/questions/1547145/defining-private-module-functions-in-python) – Axe319 Jul 29 '22 at 13:20
  • 2
    There's no way to do that. The usual convention is to start variable names with an underscore to indicate that they are internal details that shouldn't be accessed - but nothing actually enforces that. – jasonharper Jul 29 '22 at 13:20

2 Answers2

0

You can't do this but there is a convention that if you add a underscore to the name you indicate that it is a internal variable.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 01 '22 at 08:49
0

I think, that there is no elegant way to get this. There is a __all__ directive to specify what will be imported via from module_name import * but it will not work with

import module_name
module_name.scriptvar

There is a workaround: you can initialise all the necessary objects inside function and export only useful ones. Simple example

# lib.py
import sys

__all__ = ['x', 'y']

def __init(module):
    def x():
        return 2

    z = 2

    def y():
        return z

    module.x = x
    module.y = y
    del module.__init


__init(sys.modules[__name__])
# script.py
import lib

print(lib.x())

try:
    lib.__init()
except AttributeError:
    print('As expected')

from lib import *
print(x())
print(y())
try:
    print(z)
except NameError:
    print('As expected')

Running python3 script.py gives

2
As expected
2
2
As expected
pavelgein
  • 43
  • 4