-1

I have developed a python framework that is being used by others. In order to print any data to the output, the developer should use a Log class (Log.print(...)) and should not use the print() method directly. Is there any ways to force this rule throughout the code? For example, by throwing an error when a developer uses the print method directly like this:

Error: print method cannot be called directly. Please use Log.print().

Suppressing print (as discussed here) is not a good idea as the developer might get confused.

ManiAm
  • 1,759
  • 5
  • 24
  • 43
  • 2
    Sounds like you're worrying about something that's not your problem. Ensure Log.print() is well documented. – AbrahamCoding Mar 26 '20 at 08:25
  • 1
    If you want to _force_ developpers to do things in a gievn way, then Python is obviously not the right language (ADA might have been a better choice). Python's philosophy is that "we are all consenting adults". Since Python doesn't even try to prevent you from changing an object's class at runtime, I fail to see how you could prevent anyone to write to stdout. IOW: just document as clearly as possible _why_ your framework's users should use `Log.print()` instead of `print()` and that's all. – bruno desthuilliers Mar 26 '20 at 08:40
  • 1
    Also note that Python as a full logging package in it's stdlib... – bruno desthuilliers Mar 26 '20 at 08:41

1 Answers1

1

Actullay, below two line code are the same:

sys.stdout.write('hello'+'\n')
print('hello')

so, you can redirect sys.stdout to a class which raise a exception at calling print.

import sys

class BlockPrint():
    call_print_exception = Exception('Error: print method cannot be called directly. Please use Log.print().')
    def write(self, str):
        raise self.call_print_exception

bp = BlockPrint()
sys.stdout=bp

print('aaa')

Output:

Traceback (most recent call last):
  File "p.py", line 12, in <module>
    print('aaa')
  File "p.py", line 7, in write
    raise self.call_print_exception
Exception: Error: print method cannot be called directly. Please use Log.print().
gamesun
  • 227
  • 1
  • 10