How to Execute Python Code Within a Class By Importing It Specifically

Advertisements

How can I import a specific class and execute the code within by importing it?

Let’s say that I have x.py:

class classY:
    print('Executed class Y!')

class classZ:
    print('Executed class Z!')

I want the statement print('Executed function Y!') to execute when I import ONLY that module from another file.

For example, when I execute the command from x import classY, I would want the output in the console to be:

>>>from x import classY
Executed class Y!
>>>

Currently, executing the same command with the same conditions results in both strings being printed.

How can I achieve this?

>Solution :

You could potentially do it using module level __getattr__ (see PEP-562). It would require either renaming your classes or placing them inside a namespace or a separate module to ensure __getattr__ is called.

x.py

class Namespace:

    class A:
        ...


    class B:
        ...


def __getattr__(name):
    cls = getattr(Namespace, name)
    if cls is not None:
        print(f"Imported class {cls.__name__}")
        return cls
    raise AttributeError(f"{name} invalid")
>>> from x import A
Imported class A 

Technically all the code within a class is executed when it’s defined, but you can potentially put code inside functions and have it executed as part of the getattr function. Alternatively, you could save the class definitions as strings, and use exec to evaluate the strings in the getattr function.


class_C = """
class C:
    print("Creating class C")
"""


def __getattr__(name):
    CLASS_DEFS = {"C": class_C}

    if name in CLASS_DEFS:
        exec(CLASS_DEFS[name], globals())
        return globals()[name]
    
    raise AttributeError(f"{name} invalid")
>>> from x import C
Creating class C 

Leave a ReplyCancel reply