Reputation: 47
I want to create an alias to call a function without the parentheses. Something like:
>ls=os.getcwd()
>ls
>"/path1"
>os.chdir("/path2")
>ls
>"/path1" ( the wanted output would be "/path2" )
Indeed "ls" always have the same value, the value in the moment of the assingment.
Of course I can do:
>ls=os.getcwd
and then call with
>ls()
but I want is to call function without parentheses (of course when the function don't require an argument)
I tried
>def ListDir():
> print(os.getcwd())
>
>ls=ListDir()
But don't work. How I can do something this? it's possible? ( Only if is easy to do )
Upvotes: 2
Views: 2070
Reputation: 1122302
Python prefers you to be explicit; if you want to re-calculate an expression, you have to call it. But if you really want this to work in the Python interactive interpreter, you'd have to hack it.
You are only echoing a variable, not executing an expression. The variable is not going to change just because you asked the interactive interpreter to echo it.
That is, unless you hook into the echoing mechanism. You can do so with overriding the __repr__
method:
class EvaluatingName(object):
def __init__(self, callable):
self._callable = callable
def __call__(self):
return self._callable()
def __repr__(self):
return repr(self())
ls = EvaluatingName(os.getcwd)
Demo:
>>> import os
>>> class EvaluatingName(object):
... def __init__(self, callable):
... self._callable = callable
... def __call__(self):
... return self._callable()
... def __repr__(self):
... return repr(self())
...
>>> ls = EvaluatingName(os.getcwd)
>>> os.chdir('/')
>>> ls
'/'
>>> os.chdir('/tmp')
>>> ls
'/private/tmp'
This now works because each time an expression produces a value other than None
, that value is echoed, and echoing calls repr()
on the object.
Note that this will not work outside the interactive interpreter or printing. In other contexts (say, a script) you probably have to convert the object to a string each time. You can't use it as an argument to a function that expects a string, for example.
This will work:
os.path.join(ls(), 'foo.txt') # produce the value first
but this will not:
os.path.join(ls, 'foo.txt') # throws an AttributeError.
Upvotes: 5