0

I would like to implement a function, say "foo", so that it can take the input argument as follows:

foo "test", or foo << "test", ..., i.e. without parentheses involved instead of calling foo("test") explicitly just like when we calls the built-in function, "print".

Anyone knows the solution/hint?

Thanks.

Naite Ju
  • 1
  • 2
  • 1
    Why do you want to do this? Normally you shouldn't be trying to find ways to make code look less idiomatic. If you have a really good reason, you should probably be looking at a macro processor like [MacroPy](https://github.com/lihaoyi/macropy). – abarnert Aug 22 '13 at 02:47

1 Answers1

3

In Python2, print isn't a function, it's a statement, so it can break the usual rules.

However you can write a class with the __lshift__ and __rshift__ methods

class X(object):

    def __lshift__(self, n):
        print "<< "*n

    def __rshift__(self, n):
        print ">> "*n

It's possible to make those methods do pretty much whatever you like

>>> X() << 5
<< << << << << 
>>> X() >> 10
>> >> >> >> >> >> >> >> >> >> 

So you can simulate your calling idea like this

class X(object):

    def __call__(self, *args, **kw):
        print "called with ", args, kw

    def __lshift__(self, n):
        return self(n)

Not that it's a good idea, but sometimes good ideas arise from playing with things like this

John La Rooy
  • 295,403
  • 53
  • 369
  • 502