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

Original question:

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

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

Here is what I am trying to figure out:

Is there a way to avoid code duplication in Python? In one part of the program that I am 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 have this code embedded in a line that will later be output to a python file that will be launched by itself:

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

How can I create a “macro” that avoids this duplication?

+3
source share
7 answers

Answering a 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.

, first.py python , second.py, second.py.

+2

, Python , C. - , Python; , Pythonic , .

+3

python pypp, . python. Python -, . python, pypp.

. , C, :

import sys
OBJWITHSIZE = lambda x: sys.getsizeof(x) / sys.getsizeof(x[0])
aList = [1, 2, 4, 5]
size = OBJWITHSIZE(aList)
print str(size)

, python, python, - .

- :

import sys
def getSize(x):
   return sys.getsizeof(x) / sys.getsizeof(x[0])

OBJWITHSIZE = getSize
aList = [1, 2, 4, 5]
size = OBJWITHSIZE(aList)
print str(size)

.

, python, :

aList = [1, 2, 4, 5]
size = len(aList)
print str(size)
+2

. Python , #define C.

+2

, python, eval. eval Python. - , ( ), . comp.lang.python, .

'C', .

C .

  • C, C . Duh.

  • #include, import.

  • #define, . , const int foo = 1; #define foo 1. , , . , . . .

  • FOO (x, y)... code...; , .

"CPP" Python , . , . " Perl" (HOP), Python, , , .

C Pre, Python, , #define , , C ++.

lisp , ... .

+2

, , Metapython:

http://code.google.com/p/metapython/wiki/Tutorial

For instance, the following MetaPython code:

$for i in range(3):
    print $i

will expand to the following Python code:

print 0
print 1
print 2

Python, , , . ( , , , ...), C.

0

"""
from firstFile import replaceProgramFilesPath
"""
0
source

Source: https://habr.com/ru/post/1747441/


All Articles