Call a python variable that runs a function which returns a variable for the original python variable

37 views Asked by At

I'm trying to create a variable where when I call or use that variable, it runs a function to do stuff and return a certain variable. An example will make more sense:

def establish_client():
    a = None
    if True:
        a = 'A'
    return a


>>> print establish_client
'A'

It is possible to do this? Basically is there a way of running a method and returning something without using parenthesis?

2

There are 2 answers

0
fferri On

Note: the following is a hack, and there's probably more than a good reason to not do it.


You can achieve something on that line using a class and the __str__() method:

class foo:
    def __init__(self):
        pass
    def __str__(self):
        a = None
        if True:
            a = 'A'
        return a

Test:

>>> f=foo()
>>> print(f)
'A'
>>>

Beware: it works only with print and functions that explicitly treat arguments as strings.

For example, if you want to assign its string value to another variable, you have to use str(f) so you end up using parentheses.

1
textshell On

In the general case: No.

But there are some techniques that might come close.

Properties allow something like that for members in an object.

class Demo(object):
    @property
    def establish_client(self):
        a = None
        if True:
            a = 'A'
        return a

d = Demo()
print d.establish_client

But properties don't work for local or global variables.

Also you can use __str__ for to string conversion, but that only works when you only need this behavior when the variable is used in a way that converts it to a string. Which is usually not the case. See mescalinum answer for how to do that.