Python: Dynamically access variable from another file [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I want to access the python variable from config file dynamically like below.
config file:
total_var_count = 4
var1=1
var2=2
var3=3
var4=4
main_file.py
import config as cf
for variable_no in range(1,int(cf.total_var_count)+1):
print(cf.var+str(variable_no))
another method I have tried:
new_var ='var'+str(1)
print(cf.new_var) # which is also not working.
I have tried the above methods to access but its not working. Could someone tell me how I can access the variable from config file dynamically?

You can use getattr() for this:
main_file.py
import config as cf
new_var = 'var' + str(1)
print(getattr(cf, new_var))
The attribute is here the variable of the imported module.

Related

different python files sharing the same variables [duplicate]

This question already has answers here:
Using global variables between files?
(9 answers)
Closed 2 years ago.
I would like to know please, how can I define variables in a python file and share these variables with their values with multiple python files?
To do this, you can create a new module specifically for storing all the global variables your application might need. For this you can create a function that will initialize any of these globals with a default value, you only need to call this function once from your main class, then you can import the globals file from any other class and use those globals as needed.
You can create a python module
Create a py file inside that module define variables and import that module in the required places.

Is there a way to grab a variable inside a function inside a class from an imported file? [duplicate]

This question already has answers here:
How do I set and access attributes of a class? [duplicate]
(5 answers)
Closed 3 years ago.
Total noob here. There are two python files in this example. The first is cloned from github, the second is my own. The first is called city_data.py. Mine is called analyze.py. Within the city_data.py code there is a class with a prompt with many defined functions within the class. In my analyze.py file I want to run a specific function within the class. I got the function to run (table output) but when I try to recall variables from the file it just says "NameError: name 'pop_dens' is not defined". Is there a way to recall the variable pop_dens from my file while running the function on the imported file?
city_data.py
class city_stats():
prompt = '> '
def table_output(self, arg):
pop_dens = SingleTable(volume,'city')
...
print(table)
...
analyze.py
from city_data import city_data
analyze = city_stats()
density_output = analyze.table_output("Chicago")
print(pop_dens)
run analyze.py
table outputs successfully
"NameError: name 'pop_dens' is not defined"
When you want to access variable from another class use form class_name.class_variable.
in your case
...
print(analyze.pop_dens)
...

Am i making a mistake using global variables like this? [duplicate]

This question already has answers here:
How do I use global variables in python functions? [duplicate]
(7 answers)
Closed 5 years ago.
Im trying to use global variables in order to declare them at the start of my code just like you would in C# however when ever i edit them in a function and i try call it in another function it throws an error saying that the variable is not declared?
This is where i declare the variables:
from tkinter import *
import os
global Name
global Wmain
global directory
global Username
global Password
global Code
This is where i change the the directory variable:
def NameGet():
Name = NameEntry.get()
directory = ('C:\\Users\\Bradley\\Desktop\\Log In system\\Members\\' + Name + '.txt')
CheckFile(Name)
This is where i am getting the error:
def SignUpFinished():
with open(directory, W) as F:
F.write(Username)
F.write(Password)
F.write(Code)
F.close()
Now i feel im either making a really novice mistake or something isnt working right with my code. any ideas?
In order to use global variable you need to explicitly set it inside a method.
For example:
a=4
def func():
global a
print(a)
func()

dynamic execute a function by a string like 'module.function' [duplicate]

This question already has answers here:
Python function pointer
(8 answers)
Closed 9 years ago.
if I have a string like 'module.function', How can I execute function just by one step?
likesomefunction('os.error','args')
You can dynamically get the modules using sys.modules and then you can use getattr to get the attributes from the module, like this
import sys
func = "os.error"
module, function = func.split(".", 1)
getattr(sys.modules[module], function)()
sys.modules can give only the modules which are already loaded. So, if you want to load a module dynamically you can use __import__ function like this
For example,
module, function = "math.factorial".split(".", 1)
print getattr(__import__(module), function)(5)
Output
120
All you need to do is
from module import function
and you'll be able to call
function(x, y, z)
in your code.

Assigning values to variables in separate scripts with Python and Pygame [duplicate]

This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 8 years ago.
I need to create a variable in a different script from the main one in my game I am working on, with Python and Pygame.
For example:
def test():
a = 10
def testing():
return a
Then I run code like this:
import (script name)
script name.test()
script name.testing()
And after this, it gives an error. How can I fix this problem?
'a' in testing() is not a global variable and hence it's not recognised from previous function test(). If you really want to use 'a' from test() then you can probably define 'a' as Global Variable.

Categories

Resources