How do you implement “#ifdef” in python?

前端 未结 8 2078
广开言路
广开言路 2020-12-02 17:04

Programming in C I used to have code sections only used for debugging purposes (logging commands and the like). Those statements could be completely disabled fo

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 17:36

    If you are using #ifdef to check for variables that may have been defined in the scope above the current file, you can use exceptions. For example, I have scripts that I want to run differently from within ipython vs outside ipython (show plots vs save plots, for example). So I add

         ipy = False
         try:
            ipy = __IPYTHON__
         except NameError:
            pass
    

    This leaves me with a variable ipy, which tells me whether or not __IPYTHON__ was declared in a scope above my current script. This is the closest parallel I know of for an #ifdef function in Python.

    For ipython, this is a great solution. You could use similar constructions in other contexts, in which a calling script sets variable values and the inner scripts check accordingly. Whether or not this makes sense, of course, would depend on your specific use case.

提交回复
热议问题