how to include external code in Python similar as %include in SAS?

Question:

I am trying to define a variable list var_list which includes hundreds of variables. So I want to do something similar as SAS to put this definition in an external code instead of the main code. Is there anyway to do that?

For example save the following code in another file called def_var.py

var_list= ['date_of_birth_year_month'
                             ,'zip5'
                             ,'zip4'
                             ,'state_province'
                             ,'city'
                             ,'zip5_ip'
                             ,'zip4_ip'
                             ,'create_user'
                             ,'create_dt'
                             ,'update_user'
                             ,'update_dt'
                             ,'resp_ST'
                             ,'resp_HomeTheater'
                             ,'resp_Headphone']
Asked By: Gavin

||

Answers:

Take a look at the import statement.

You can save your variables in def_var.py as:

var_list= ['date_of_birth_year_month'
,'zip5'
,'zip4'
,'state_province'
,'city'
,'zip5_ip'
,'zip4_ip'
,'create_user'
,'create_dt'
,'update_user'
,'update_dt'
,'resp_ST'
,'resp_HomeTheater'
,'resp_Headphone']

And import it in your main.py:

from def_var import var_list
# now you can work with your list
print(var_list[1])

Output:

zip5
Answered By: Nils

For more sophisticated uses of sas, programmers will often have various macros/sas programs in different directories, each of which is specific to a certain type of workflow. In these cases SAS %include will typically include the full path to whatever code is of interest.

%include "myfilepath/some_directory_of_macros/some_sas_macro.sas"

In python one specifies this in two steps

Step1:

Make sure that the directory with code base of interest is in the python search path.

Details:

import sys
sys.path
sys.path.append("myfilepath")
sys.path # checking to see if it was added to list

STEP2

Now you can import the code/function of interest. The import will look sequentially through all the paths in sys.path, and stop once it finds a directory named some_directory_of_macros in one of the directories listed in sys.path.

import some_directory_of_macros

# SomePythonModule.py should be in some_directory_of_macros
from some_directory_of_macros.SomePythonModule  

CAUTION, If some_directory_of_macros exists in more than one of the directories listed in sys.path, python will load the 1st one it finds

–> the sequence of paths in sys.path matters.

–> You can modify the order as you would normally do with any Python list if need be.

Answered By: quetal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.