Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to convert code to a string and vice versa in Python?

Tags:

python

macros

The original question was:

Is there a way to declare macros in Python as they are declared in C:

#define OBJWITHSIZE(_x) (sizeof _x)/(sizeof _x[0])

Here's what I'm trying to find out:

Is there a way to avoid code duplication in Python? In one part of a program I'm writing, I have a function:

def replaceProgramFilesPath(filenameBr):
  def getProgramFilesPath():
    import os
    return os.environ.get("PROGRAMFILES") + chr(92)
  return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() )

In another part, I've got this code embedded in a string that will later be
output to a python file that will itself be run:

"""
def replaceProgramFilesPath(filenameBr):
  def getProgramFilesPath():
    import os
    return os.environ.get("PROGRAMFILES") + chr(92)
  return filenameBr.replace("<ProgramFilesPath>",getProgramFilesPath() )
"""

How can I build a "macro" that will avoid this duplication?


2 Answers

Answering the new question.

In your first python file (called, for example, first.py):

import os

def replaceProgramFilesPath(filenameBr):
  new_path = os.environ.get("PROGRAMFILES") + chr(92)
  return filenameBr.replace("<ProgramFilesPath>", new_path)

In the second python file (called, for example, second.py):

from first import replaceProgramFilesPath
# now replaceProgramFilesPath can be used in this script.

Note that first.py will need to be in python's search path for modules or the same directory as second.py for you to be able to do the import in second.py.

like image 183
Gary Kerr Avatar answered Sep 17 '25 02:09

Gary Kerr


No, Python does not support preprocessor macros like C. Your example isn't something you would need to do in Python though; you might consider providing a relevant example so people can suggest a Pythonic way to express what you need.

like image 31
Greg Hewgill Avatar answered Sep 17 '25 02:09

Greg Hewgill