tags:

views:

78

answers:

2

In a simple program I made, I wanted to get a list from another project and access the elements from it. Since I'm new to python, I don't really have any idea what to do. In my project, I checked the box for the project name I wanted to reference and... I don't know what to do. A few google searched did me no good, so I'm hoping someone here can tell/link me how to set this up.

+2  A: 

Use import. Then you can access the "module" (project) and everything in it like an object./

# a.py
some_list = [1,2,3,4]

# b.py
import a
print a.some_list

If you run b.py, it will print [1,2,3,4]

Unknown
Simple enough, thanks! Also, let's say the .py file I wanted to reference was not in the same directory, would I just include the directory after the import? Like, import c:\python_backup\lists
Justen
Justen, it gets more complicated than that. If you want to import a specific directory you need to use the __import__ function. If the directory is a subdirectory of the main file, then you must have an __init__.py file in the subdirectory. Any more explanation about this is too much to fit into this box.
Unknown
alright, I can probably find the rest out when I need to now that I have a direction, thanks again.
Justen
@Unknown: Wrong. __import__ has nothing to do with importing from a specific directory.
nosklo
oh yeah imp.load_source is for specific directories while __import__ lets you change the name and global local scope.
Unknown
+1  A: 

Generally if you have some code in project1.py and then want to use it from a different file in the same directory, you can import project1 as a module:

import project1

data = project1.my_data_function()

This works just the same way as you would import any module form the standard library.

sth