2

I want to create wrapper over print function or any logging function so that if internally I need to change logging/print strategy it should work without changing in all module.For ex:

print "Hello this is test A:%d B:%d C:%d",a,b,c

instead of this it should look like:

MyPrint "Hello this is test A:%d B:%d C:%d",a,b,c 

which will give me same output.

This gives me flexiblity of changing definition of MyPrint without affecting print in whole code.

In C++ this can be acheived through macro but not sure how we can achieve in python.

llllllllll
  • 16,169
  • 4
  • 31
  • 54
AnonymousDev
  • 247
  • 3
  • 15

2 Answers2

3

Doing something like this should do:

def my_print(message, *args):
    print(message % args)

Then you could call it like this:

my_print("Hello this is test A:%d B:%d C:%d", 1, 2, 3)

# Output: Hello this is test A:1 B:2 C:3
Omar Einea
  • 2,478
  • 7
  • 23
  • 35
2

Looks like you should be using logging with a custom format

eg. as this answer shows

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • no this is not what I was looking for, lets say I am using this logger, with some syntax say logging.error("Content") but in future if I need to change logger then I have to change all the logging.error() lines , so to overcome this if I have my logger("Content ") than I wont need to change code I need to change logger() handling logic. – AnonymousDev Feb 10 '18 at 11:43
  • @AnonymousDev I don't get how this doesn't solve your problem? Your example was a bit unclear to me – jamylak Feb 10 '18 at 12:05
  • lets say I am using logger of x package but in future I need to change to logger of some y package , so I need to create a wrapper that will handle logging and since in code will be using my wrapper apis so there wont be change if I need to change logger of x to y package. Refer to ans that might clear your doubt. – AnonymousDev Feb 10 '18 at 12:14
  • @AnonymousDev Everyone just uses the python `logging` module. If they were to use another logging module, theyd just use that from the start. Nobody really switches between them – jamylak Feb 10 '18 at 13:58