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

Each Answer to this Q is separated by one/two green lines.

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?

C = MyReallyBigClassNameWhichIHateToType

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

from modulename import ReallyLongNameWhichIHateToType as FriendlyName

You can simply do:

ShortName = MyReallyBigClassNameWhichIHateToType

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

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

Otherwise whateverName = VeryLongClassName should do the trick.

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'


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .