简体   繁体   中英

Python prefix postfix infix, no parentheses

I came to Python from Mathematica. Are there prefix, postfix, and infix operators without parentheses like in Mathematica in Python?

eg In Mathematica

Print@@string
string~Join~string
data//Sum

I find I'm constantly using print to test functions and having to wrap the entire thing with parentheses seems cumbersome and cleanup is slow. Is there a way to have [i for i in data]//Print in Python3?

Python does not have any postfix operators, though you could sort of mimic them using the magic r-dunder methods and infix operators if you try really hard.

For example,

class PrintType:
    def __rfloordiv__(self, other):
        print(other)

Print = PrintType()

[1, 2, 3]//Print

You might still require parentheses to get the precedence right though.

Python does have an operator precedence table in the documentation. Thus, operations with higher precedence will apply first and do not require explicit parenthesis, eg 10 + 2 * 3 is the same as 10 + (2 * 3) in Python.

You could even generalize this to arbitrary 1-argument functions,

class Slash2:
    def __init__(self, fn):
        self.fn = fn

    def __rfloordiv__(self, other):
        return self.fn(other)

Print = Slash2(print)
Sum = Slash2(sum)

[1, 2, 3]//Sum//Print
# prints "6"
[1, 2, 3]//Slash2(sum)//Slash2(print)  # Same thing.

If you're used to Mathematica, I would recommend using Jupyter notebooks for your Python experiments, as the paradigm of cells will be familiar to you.

Jupyter's Python kernel, IPython , does have % magics that extend the native Python syntax somewhat. IPython includes an %autocall option to invoke functions without the parentheses. This can cause ambiguity in some cases and so is disabled by default.

You can also start a line with / for a similar effect (it only works in IPython--see also , and ; for auto call with auto quotes).

As in the IPython repl, the value of the last statement in a Jupyter cell will be displayed as output automatically--you don't have to call print on it. And for some data types, like Pandas data frames, it's better if you don't. It is also possible to configure it to display the output of multiple statements from the same cell.

The first cell you should try executing in Jupyter is

?

Just a question mark. This will bring up the online help explaining IPython's features.

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