Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python using variables from another file

Tags:

python

I'm new and trying to make a simple random sentence generator- How can I pull a random item out of a list that is stored in another .py document? I'm using

random.choice(verb_list)  

to pull from the list. How do I tell python that verb_list is in another document?

Also it would be helpful to know what the principle behind the solution is called. I imagine it's something like 'file referencing' 'file bridging' etc..

like image 204
Benjamin James Avatar asked Jan 28 '13 23:01

Benjamin James


People also ask

How do I use a variable in another file?

In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting.

Can global variable be access from another file Python?

It is impossible to globalise a variable inside a function in a separate file.

How do you access a list from another file in Python?

You have a list named list in file1.py and you want to import list to file2.py and from this list, you want to get random words. and as @Olvin said in comments, do not use list as a variable name because it is python function to create list eg l = list() .


1 Answers

You can import the variables from the file:

vardata.py

verb_list = [x, y, z] other_list = [1, 2, 3] something_else = False 

mainfile.py

from vardata import verb_list, other_list import random  print random.choice(verb_list)  

you can also do:

from vardata import * 

to import everything from that file. Be careful with this though. You don't want to have name collisions.

Alternatively, you can just import the file and access the variables though its namespace:

import vardata print vardata.something_else 
like image 187
Kartik Avatar answered Oct 01 '22 18:10

Kartik