0

Let's consider the following file myfile.py.

def f_1():
    print("Run !")

def f_2():
    print("Run, run !")

class Test():
    def __new__(cls):
        print("In the class", dir())

print("After class", dir())
Test()

I would like to access to all the functions defined before my class within it. The inside dir is about the class and not the file as the output above shows.

After class ['Test', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'f_1', 'f_2']
In the class ['cls']

One solution would be to add a global constant previousnames = dir() just before the class but is there a better way to do that ?

2
  • What are you trying to accomplish? It's better to be explicit about this type of thing; just maintain (with a known name) a list or dictionary of the global functions that Test needs access to, and let Test iterate over the known list/dictionary. Commented Apr 26, 2015 at 17:15
  • I want to add methods to a class but I have no way to subclass it. See this post to know why. Commented Apr 26, 2015 at 17:16

1 Answer 1

1

As I said in my comment: be explicit, and don't try to do dynamic function discovery. dir is not intended for programmatic use anyway; it's a helper for use in the interactive shell.

def f_1():
    print("Run !")

def f_2():
    print("Run, run !")

for_Test = [f_1, f_2]

class Test():
    def __new__(cls):
        for f in for_Test:
            # Based on your linked question
            setattr(cls, f.name, f)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, that does the job. I will be more explicit in the future. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.