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.

asked Aug 1, 2023 at 23:57
2
  • Try changing the order where Python method get_data is defined before the Stata program. Commented Aug 2, 2023 at 1:32
  • @Parfait I tried that, but I got the same result. Commented Aug 2, 2023 at 1:44

1 Answer 1

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.

answered Aug 2, 2023 at 1:47
Sign up to request clarification or add additional context in comments.

3 Comments

For future readers, please provide fuller code that shows how you reference the external file.
Even in the Stata docs you link, examples use separate ado files. Only methods are defined without actual calls.
@Parfait I missed that when I asked my question. Can you elaborate on why separate files are important?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.