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.
asked Aug 1, 2023 at 23:57
dimitriy
9,4602 gold badges28 silver badges56 bronze badges
1 Answer 1
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.
answered Aug 2, 2023 at 1:47
dimitriy
9,4602 gold badges28 silver badges56 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Parfait
For future readers, please provide fuller code that shows how you reference the external file.
Parfait
Even in the Stata docs you link, examples use separate ado files. Only methods are defined without actual calls.
dimitriy
@Parfait I missed that when I asked my question. Can you elaborate on why separate files are important?
lang-py
get_datais defined before the Stata program.