Python 3 print without parenthesis

PythonPrinting

Python Problem Overview


The print used to be a statement in Python 2, but now it became a function that requires parenthesis in Python 3.

Is there anyway to suppress these parenthesis in Python 3? Maybe by re-defining the print function?

So, instead of

print ("Hello stack over flowers")

I could type:

print "Hello stack over flowers"

Python Solutions


Solution 1 - Python

Although you need a pair of parentheses to print in Python 3, you no longer need a space after print, because it's a function. So that's 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')
hello

It'll make your code less readable, but you'll save those few characters every time you print something.

Solution 2 - Python

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

However, print without parentheses might be useful in the interactive shell. It's 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 you're 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 won't even need to type the slash:

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

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

Solution 3 - Python

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

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.

Solution 4 - Python

No. That will always be a syntax error in Python 3. Consider using 2to3 to translate your code to Python 3

Solution 5 - Python

The AHK script is a great idea. Just for those interested I needed to change it a little bit to work for me:

SetTitleMatchMode,2         ;;; allows for a partial search 
#IfWinActive, .py           ;;; scope limiter to only python files
:b*:print ::print(){Left}   ;;; I forget what b* does
#IfWinActive                ;;; remove the scope limitation

Solution 6 - Python

I finally figured out the regex to change these all in old Python2 example scripts. Otherwise use 2to3.py.

Try it out on Regexr.com, doesn't work in NP++(?):

find:     (?<=print)( ')(.*)(')
replace: ('$2')

for variables:

(?<=print)( )(.*)(\n)
('$2')\n

for label and variable:

(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n

Solution 7 - Python

You can't, because the only way you could do it without parentheses is having it be a keyword, like in Python 2. You can't manually define a keyword, so no.

Solution 8 - Python

In Python 3, print is a function, whereas it used to be a statement in previous versions. As @holdenweb suggested, use 2to3 to translate your code.

Solution 9 - Python

You can use operator oveloading:

class Print:
    def __lt__(self, thing):
    print(thing)

p = Print()

p < 'hello'   #  ->  hello 

Or if you like use << like in c++ iostreams.

Solution 10 - Python

I have configured vim to auto-add the parens around my debug def calls when I write the file. I use a simple watcher that auto-runs my updates when the timestamp changes. And I defined CTRL+p to delete them all. The only caveat is that I have to have them alone on a line, which I pretty much always do. I thought about trying to save and restore my previous search-highlight. And I did find a solution on Stack. But it looked a little too deep for now. Now I can finally get back to debugging Ruby-style with a quick p<space><obj>.

function! PyAddParensToDebugs()
  execute "normal! mZ"
  execute "%s/^\\(\\s*\\)\\(p\\|pe\\|pm\\|pp\\|e\\|ppe\\)\\( \\(.*\\)\\)\\{-}$/\\1\\2(\\4)/"
  execute "normal! `Z"
endfunction

autocmd BufWrite *.py silent! call PyAddParensToDebugs()

map <c-p> :g/^\\s*\\(p\\\|pe\\\|pm\\\|pp\\\|e\\\|ppe\\)\\( \\\|\(\\)/d<cr>

I use these Python defs to do my debug printing.

def e():
    exit()
def pp(obj):
    pprint.PrettyPrinter(indent=4).pprint(obj)
def ppe(obj):
    pprint.PrettyPrinter(indent=4).pprint(obj)
    exit()
def p(obj):
    print(repr(obj))
def pe(obj):
    print(repr(obj))
    exit()
def pm():
    print("xxx")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLauraView Question on Stackoverflow
Solution 1 - PythonTigerhawkT3View Answer on Stackoverflow
Solution 2 - PythonmichauView Answer on Stackoverflow
Solution 3 - PythonHarry BinswangerView Answer on Stackoverflow
Solution 4 - PythonholdenwebView Answer on Stackoverflow
Solution 5 - PythonTokyoMikeView Answer on Stackoverflow
Solution 6 - PythonalchemyView Answer on Stackoverflow
Solution 7 - Pythonuser3917838View Answer on Stackoverflow
Solution 8 - PythonSPKB24View Answer on Stackoverflow
Solution 9 - PythonnadapezView Answer on Stackoverflow
Solution 10 - PythonMyles PratherView Answer on Stackoverflow