Somatic
Somatic

Reputation: 193

How can I turn one of the arguments of a function into a string?

I have this code, with the desired output "The value is Bar and the name is b."

class myClass:
    def __init__(self, value):
        self.value = value

b = myClass("Bar")

def foo(var):
    true_name = str(var)
    print("The value is %s and the name is %s" % (var.value, true_name))

foo(b)

However, this prints The value is Bar and the name is <__main__.myClass object at 0x000000187E979550>, which is less useful to me.

Now, I know the problems with trying to get the true name of a variable in Python. However, I don't need to do any fancy introspection; I just want to convert the actual letters typed between the parentheses of foo( ) and print that.

To me, this sounds like a simple thing that would be useful in debugging and examining my code, so I can tell exactly what object did a thing. Am I making a fundamental error in my assumptions, and this is a terrible idea?

Upvotes: 0

Views: 38

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49318

The easiest way to do this is by simply passing the desired "true name" in along with the actual reference:

def foo(var):
    var, true_name = var
    print("The value is %s and the name is %s" % (var.value, true_name))

foo((b, 'b'))

Of course, this does not guarantee that true_name matches the passed reference name, but it's a much shorter and clearer way of not guaranteeing it than possibly-fragile hacks that may or may not work.

If you just want something more readable than <__main__.myClass object at 0x000000187E979550>, you should define a __str__ method in your class and then simply print the instance. You won't even need a separate foo function anymore. You can also define a __repr__ method for the precise representation (which is the string that you would enter into the interpreter to produce an equivalent object):

class myClass:
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return 'myClass with a value of {}'.format(self.value)
    def __repr__(self):
        return "myClass({})".format(repr(self.value))

Result:

>>> b = myClass("Bar")
>>> print(b)
myClass with a value of Bar
>>> b
myClass('Bar')

Upvotes: 1

Related Questions