简体   繁体   中英

How to completely ban print keyword in python 2.7?

I am introducing the loggers into my project and I would like to ban the print statement usage in it. My intent is to force any future developers to use the loggers and to make sure I replaced all print invocations in project.

So far I managed to restrict print('foo') and print 'foo' like invocations with:

from __future__ import print_function

def print(*args, **kwargs):
    raise SyntaxError("Don't use print! Use logger instead.")

But it is still possible to use print without arguments with intent of adding newline but it won't do anything.

Is it possible to do it without interpreter modifications?

EDIT: I wasn't clear enough I guess from the comments. I just wanted to know if I can prevent the print function for being aliased

print("foo") # raises exception
print "foo" # doesn't work either
print # doesn't raise any exception, but I want it to
foo = print # this shouldn't work either like the one above, but it does

No, you can't prevent print statements from being used in code that doesn't use from __future__ import print_function . print statements are not hooked, they are compiled directly to a set of opcodes and the implementation of those opcodes just write directly to stdout or other file object (when using the >> notation).

You could go the drastic route of requiring a custom codec , but that's no better than requiring that from __future__ import print_function is used.

By the same token, if all code does use from __future__ import print_function , while you can assign a new print function to the __builtin__ module , you can't prevent someone from building their own version (named print or something else) that writes to sys.stdout , or from executing reload(__builtin__) . Python is highly dynamic and flexible, I'd not try to lock this down.

The normal path to enforce coding standards is to use a linter, code review and tests. You can install hooks on most version control systems that prevent code from being checked in that doesn't pass a linter, and both pylint and flake8 support custom plugins. You can run a test that configures the logging module to direct all output to a file then raise an exception if anything is written to stdout , etc.

This is the path that Facebook uses (and it is not alone in this approach), where Python code must pass the Facebook flake8 configuration, which includes the flake8-bugbear extension , and code is autoformatted using Black to make it easy for developers to meet those requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM