3

I am trying to return a version number, with a way to implement exceptions.

Since the exceptions can be for any of my classes I am trying to get the classname from the object.

Problem is, I get a tuple instead of a string:

def version_control(*args):
    version = 1.0
    print args
    #Exception example:
    print str(args.__class__.__name__)
    if 'User' == args.__class__.__name__:
        version = 12.3

    return version

How can I change the str(args.__class__.__name__) in such a way that it return the name of the class as string?

1
  • 1
    No, you are not getting a tuple from args.__class__.__name__; something else is wrong. And why not use if isinstance(args, User): instead? Commented Jan 4, 2014 at 13:56

2 Answers 2

5

I get a tuple instead of a string

No, you get the string "tuple" instead of some other string, because args is a tuple of arguments.

When you call version_control(obj, 1, 2), args == (obj, 1, 2). You want to be looking at args[0], which in this example is obj

Sign up to request clarification or add additional context in comments.

5 Comments

Excuse me first time working with args, i guess i can solv this easier with kwargs then?
@HansdeJong: why would keyword arguments solve the problem? Your function is being called with positional arguments; just index the args tuple. How many different ways is this function being called?
i want to be able to put any of my objects (from most of my classes) in this and only give an exception version when an object is passed that is in the exception list pastebin.com/NGDHTN68 this seems to work fine
Sure, but since you didn't show us how the function is being called, we cannot help you with what arguments are being passed in either.
My excuses for that, still pretty new to django, python and stackoverflow. Next time i try to be more precise
3

To get the class name as a string:

f = Foo()
f.__class__.__name__ # => 'Foo'

However, consider using isinstance() instead:

isinstance(f, Foo) # => True

This is more readable and covers a majority of use cases, and should be preferred when using a conditional.

2 Comments

Adding this answer here to provide a condensed tl;dr that directly addresses the question title, for users who googled 'python get classname from object' or something similar.
Credit to the comment on the question by Martijn Peters, which contains this information as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.