1

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.

dimitriy
  • 9,077
  • 2
  • 25
  • 50

1 Answers1

0

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.

dimitriy
  • 9,077
  • 2
  • 25
  • 50
  • For future readers, please provide fuller code that shows how you reference the external file. – Parfait Aug 02 '23 at 01:53
  • Even in the Stata docs you link, examples use separate ado files. Only methods are defined without actual calls. – Parfait Aug 02 '23 at 01:58
  • @Parfait I missed that when I asked my question. Can you elaborate on why separate files are important? – dimitriy Aug 02 '23 at 03:03