Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Preprocessor commands escape if condition

    Dear Statalist community,

    In the code below, both #review and #delimit are executed although the if condition is not fulfilled.

    Code:
    clear all
    sysuse auto.dta, clear
    
    local delimchange 0
    
    if `delimchange' == 1 {
        #review
        #delimit ;
    }
    
    tab price
    tab weight
    Is this intended behavior? I know that both #review and #delimit are preprocessor commands, but I couldn't find much information in the documentation.

    The issue initially came up when I integrated Python code into my do-file, using # to start a comment.

    Code:
    clear all
    
    qui python query
    if `r(initialized)' != 1 {
        python search
        set python_exec  "C:my/dummy/path/python.exe"    // set path
    }
     
    local py 0
    
    if `py' == 1 {
    python:
    # Here comes a simple print command
    print("Hello world")
    end
    }
    I am using Stata 18 (update level: 26 Feb 2025) on Windows 11.

  • #2
    I think the first part of your question regarding pre-processor commands is a of a diversion from what I suspect you are really interested in, which is how to conditionally execute your python block.

    As it happens, when you have a code block, in this case your -if- command, you cannot have nested language blocks (e.g., -python {- or -python:-) like you could in open code outside of such a block. To execute Python-specific commands like that, you must use the -python:- prefix for every single Python command. In your case, this would become:

    Code:
    if `py' == 1 {
        python: # Here comes a simple print command
        python: print("Hello world")
    }
    The same is true if, instead of Python, you wanted to execute Mata statements. Some helpful related discussions from the past can be found here.

    Comment


    • #3
      I'm not sure about your comment on nested language blocks inside code blocks. The following works just fine for me:
      Code:
      local py 1
      
      if `py' == 1 {
      python:
      print("1st line")
      print("2nd line")
      print("3rd line")
      end
      }
      My question was more generally about preprocessing commands and why they are considered by Stata even when they are tucked away in an unfulfilled if condition. The Python case was just the first time I had encountered this behavior.

      Comment


      • #4
        I'm speculating here, but when executing code from the do-file editor, or an ado, I think each line of the file is first preprocessed before being processed as actual code. The preprocessor must see lines beginning with "#" as a preprocessor directive and tries to execute those immediately, rather than treating them like regular Stata commands that follow the same logical flow implied by the program.

        Comment

        Working...
        X