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 ?

projetmbc
  • 1,332
  • 11
  • 26
  • 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. – chepner Apr 26 '15 at 17:15
  • I want to add methods to a class but I have no way to subclass it. See [this post](http://stackoverflow.com/a/29880095/4589608) to know why. – projetmbc Apr 26 '15 at 17:16

1 Answers1

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)
chepner
  • 497,756
  • 71
  • 530
  • 681