How to determine if a variable exists in another python file

I have two python files. From python file # 1, I want to check if a specific global variable exists, defined in python file # 2.

What is the best way to do this?

+3
source share
3 answers
try:
    from file import varName
except ImportError:
    print 'var not found'

Alternatively, you can do this (if you have already imported the file):

import file
# ...
try:
    v = file.varName
except AttributeError:
    print 'var not found'

This will only work if var is global. If you use variables with scope, you will need to use introspection.

+3
source

You can directly check if a module file2(which is a module object) has an attribute with the correct name:

import file2
if hasattr(file2, 'varName'):
    # varName is defined in file2…

, try… except… ( , ).

+3

Using the built-in function, getattr()you can also specify a default value, for example:

import file2

myVar = getattr(file2, attribute, False)

See documentation

+2
source

Source: https://habr.com/ru/post/1758085/


All Articles