Passing a Local to a Python program from Stata

71 views Asked by At

I am trying to write a Stata program that passes a local to a Python function. It is based on this example, where this approach works.

Here is a toy example demonstrating the problem:

python clear
capture program drop get_data
program get_data
     version 17
     args InputText
     python: get_data()
end

python:

from sfi import Macro

def get_data():
     inputtext = Macro.getLocal('InputText')
     print(inputtext)
     
end

local InputText "YYY"
python: get_data()

get_data "XXX"

The first works, the second does not:

. local InputText "YYY"

. python: get_data()
YYY

. 
. get_data "XXX"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'get_data' is not defined
r(7102);

I would like to get a fix with an explanation.

1

There are 1 answers

3
dimitriy On

Putting this code into a file called get_data.ado seems to do the trick:

python clear
capture program drop get_data
program get_data
     version 17
     args InputText
     python: get_data()
end

python:

from sfi import Macro

def get_data():
     inputtext = Macro.getLocal('InputText')
     print(inputtext)

end

Here is the result:

. get_data "XXX"
XXX

I would still love to understand why it has to go into a separate file.