How do you alias a python class to have another name without using inheritance?

Question:

If I have a python class, how can I alias that class-name into another class-name and retain all it’s methods and class members and instance members? Is this possible without using inheritance?

e.g. I have a class like:

class MyReallyBigClassNameWhichIHateToType:
    def __init__(self):
         <blah>
    [...]

I’m creating an interactive console session where I don’t want my users’ fingers to fall off while instantiating the class in the interactive sessions, so I want to alias that really long class name to something tiny like ‘C’. Is there an easy way to do this without inheritance?

Asked By: Ross Rogers

||

Answers:

Refactor the name, no reason it should have a name that long.

Otherwise whateverName = VeryLongClassName should do the trick.

Answered By: Yuval Adam
C = MyReallyBigClassNameWhichIHateToType
Answered By: SilentGhost

You can simply do:

ShortName = MyReallyBigClassNameWhichIHateToType

A class in Python is just an object like any other, and can have more than one name.

Answered By: dF.

Also, if you’re importing the name from another module…

from modulename import ReallyLongNameWhichIHateToType as FriendlyName
Answered By: James Emerton

Simple name assignment approach works but has one disadvantage that might be important in some cases: the alias name will be the same as the name of the “base” class because of the __name__ property.

class C(object):
    pass

D = C

print(C.__name__)  # 'C'
print(D.__name__)  # 'C' again

For example, if you create custom exception and then another one that assigning the first one you will get the name of this “parent” exception every time no matter which one of them you raise and this should probably confuse a user:

class CustomBaseException(Exception):

    def __init__(self, operation):
        super(CustomBaseException, self).__init__()
        self.operation = operation

    def __str__(self):
        return f"Invalid operation '{self.operation}'"


OperationException = CustomBaseException

raise OperationException('readd')

output:

Traceback (most recent call last):
  File "<input>", line 12, in <module>
CustomBaseException: Invalid operation 'readd'

So a solution would be to actually subclass the class:

class CustomBaseException(Exception):

    def __init__(self, operation):
        super(CustomBaseException, self).__init__()
        self.operation = operation

    def __str__(self):
        return f"Invalid operation '{self.operation}'"


class OperationException(CustomBaseException):
    pass


raise OperationException('delite')

output:

Traceback (most recent call last):
  File "<input>", line 14, in <module>
OperationException: Invalid operation 'delite'
Answered By: Hello Human
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.