This case is no different from the others you've seen related to UnboundLocalError
. Since your inner-class is also called datetime
Python's bytecode compiler will mark the name datetime
as a local variable. Since you try to assign real_datetime = datetime
before the class declaration you get the error.
This might be clearer if you consider that
class datetime(datetime.datetime):
...
is an equivalent statement to:
datetime = type('datetime', (datetime.datetime), {...class members...})
As a workaround to this sort of thing, you could always use a different name from datetime
for the mock class. It probably doesn't matter what its name is (and if it really does matter you could still override that by assigning to its __name__
attribute after the class is created).
In Python 3 you would just declare nonlocal datetime
like you would any other non-local variable.