printing – Python 3 print without parenthesis

printing – Python 3 print without parenthesis

Although you need a pair of parentheses to print in Python 3, you no longer need a space after print, because its a function. So thats only a single extra character.

If you still find typing a single pair of parentheses to be unnecessarily time-consuming, you can do p = print and save a few characters that way. Because you can bind new references to functions but not to keywords, you can only do this print shortcut in Python 3.

Python 2:

>>> p = print
  File <stdin>, line 1
    p = print
SyntaxError: invalid syntax

Python 3:

>>> p = print
>>> p(hello)

Itll make your code less readable, but youll save those few characters every time you print something.

Using print without parentheses in Python 3 code is not a good idea. Nor is creating aliases, etc. If thats a deal breaker, use Python 2.

However, print without parentheses might be useful in the interactive shell. Its not really a matter of reducing the number of characters, but rather avoiding the need to press Shift twice every time you want to print something while youre debugging. IPython lets you call functions without using parentheses if you start the line with a slash:

Python 3.6.6 (default, Jun 28 2018, 05:43:53)
Type copyright, credits or license for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type ? for help.

In [1]: var = Hello world

In [2]: /print var
Hello world

And if you turn on autocall, you wont even need to type the slash:

In [3]: %autocall
Automatic calling is: Smart

In [4]: print var
------> print(var)
Hello world

printing – Python 3 print without parenthesis

Use Autohotkey to make a macro. AHK is free and dead simple to install.

You could assign the macro to, say, alt-p:

!p::send print(){Left}

That will make alt-p put out print() and move your cursor to inside the parens.

Or, even better, to directly solve your problem, you define an autoreplace and limit its scope to when the open file has the .py extension:

#IfWinActive .py            ;;; scope limiter
:b*:print ::print(){Left}   ;;; I forget what b* does. The rest should be clear 
#IfWinActive                ;;; remove the scope limitation

This is a guaranteed, painless, transparent solution.

Leave a Reply

Your email address will not be published. Required fields are marked *