0

I am working on a task to transform existing SAS CODE to Python.

I am facing some challenges in converting existing SAS MACRO to its Python Equivalent.

I am working on the assumption that SAS MACRO equivalent will be PYTHON FUNCTION and SAS MACRO VARIABLE equivalent will be PYTHON STRING Variable that can be used in Python Code while its value is passed in Python Function (if required).

SAS MACRO Variable has 2 Usecases:

USECASE 1: It can be used in SAS Program body e.g. Filter Condition:

e.g.

%let COUNTRY = 'UK';
 
DATA REVENUE_UK;

set REVENUE_ALL;

where CTRY = &COUNTRY.;

run;

USECASE 2: It can be used in DATA STEP in SAS Program while creating dataset:

%let COUNTRY = 'UK';

DATA PROFIT_&COUNTRY.;

set PROFIT;

run;

If we have to write similar logic in Python:

USECASE 1: Use of variable in Python CODE e.g. Filter Condition:

COUNTRY = 'UK'

REVENUE_UK = REVENUE_ALL.loc[REVENUE_ALL['CTRY'] == COUNTRY,:]

USECASE 2: Use Variable while creating Dataframe:

COUNTRY = 'UK'

'PROFIT_'+CTRY = PROFIT.copy()

Now Second Usecase is not working.

As per my understanding we cannot use STRING Variable while in a Dataframe name.

Other options include, initially creating a dictionary and pre-defining all Variable as KEY and associated dataframes as value and then use that dictionary to assign dataframe name.

But it is not user friendly and needs frequent update in Dictionary at initial stage.

Is there a better way so that we can create Python dataframes and name them as per the string passed in Function?

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
  • You can use `exec()`. As explained in [convert-string-to-variable-name-in-python](https://stackoverflow.com/questions/19122345/convert-string-to-variable-name-in-python) – Anant Kumar Aug 06 '20 at 06:31

1 Answers1

0

Defining variables in this way in Python is not recommended - it's just not the 'Pythonic' way of doing things.

That being said, you can use globals() to achieve what you're looking for, as in the following example:

# my_var_3 is not defined at this point: 
print(my_var_3)
---------------------------------------------------------------------------
NameError                               
...
NameError: name 'my_var_3' is not defined

# Now use 'globals'
var_name = "my_var" + "_3"
globals()[var_name] = "Sample value"

print(my_var_3)
==> Sample value
Roy2012
  • 11,755
  • 2
  • 22
  • 35