Home > Mobile >  Is it possible to make a scope that is only for the script?
Is it possible to make a scope that is only for the script?

Time:07-30

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'

CodePudding user response:

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.

CodePudding user response:

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
  • Related