maciek2791 maciek2791 - 4 months ago 7
Python Question

Execute function with variable from imported file

I'm trying to execute function with value from other file as variable.

one file (let's assume text.py) containing:

VAR="abc"


In main file:

variable1 -> that variable contain value "VAR"
import text


Execute function:

example_function(connect=text.variable1)


Why I cannot do it this way?

EDIT:

real code:

variable = "VAR_23_23"
import text
from functionfile import number_function
from functionfile import find_number
number_to_substr=find_number(variable,"_",1)
source_var=variable[:number_to_substr]
number_function(connect=text.source_var)


Edit 2.

text.py contain:

VAR="abc"


main.my contain:

import text

variable = "VAR_23_23"
from functionfile import number_function
from functionfile import find_number

number_to_substr=find_number(variable,"_",1) -> the result is "4"
source_var=variable[:number_to_substr] -> the result is "VAR"
number_function(connect=text.source_var) -> now trying to execute function with that variable name but as result I expect value from TEXT.py file.


For now instead of 'abc' value I got 'VAR' value.`

Answer

You cannot do text.variable1 because variable1 resides in your main file.

You can either use the value from the imported file:

import text
example_function(connect=text.VAR)

Or use the value in variable1:

example_function(connect=variable1)

If what you're trying to do is as I've posted in my comment then this is what you should change in order to make it work:

First, edit the text.py file so that instead of containing an instantiation of a variable named VAR, it contains an instantiation of a dictionary containing a "VAR" key:

d = {'VAR': "abc"}

Now, in order to access the value of 'VAR' in the main file, do text.d[source_var]. That is,

number_function(connect=text.d[source_var])

This is assuming that the source_var variable contains the string "VAR".