I am trying to import all the objects from a subfolder into a class in python 3.8, and am strugguling to find a way to do so. I don't want to manually have to import all the objects, as there are far too many files to list:
class Foo:
from bar import {
one,
two,
three,
# ...
}
And when I use the star symbol to import all functions and classes (e.g. from bar import *
) I get the following error:
SyntaxError: import * only allowed at module level
Also, I would not like to put everything under a sub-scope (e.g. import bar.package
and put all the files in the package
subpackage of bar
), because the functions in bar
rely on being passed self
when run and would mean would have to change all references of self
to self.package
I am only creating another folder with all the methods in the class so that there is not a single extremely long file.
So I guess I have three questions: Why is importing all in a class not allowed, how can I get around this, and is there a better way to split multiple methods up into different files?
EDIT: I've seen this post, and is what I currently have, but only instead of importing everything manually I want to use the *
instead.
EDIT 2: Perhaps creating the submethods of a class as a package and importing it as self would work (e.g. import bar.package as self
), but this may override the default self. For example say I have the two files foo.py
and bar.py
:
# foo.py
def print_bar(self):
print("bar")
# bar.py
class Test:
import foo as self
def __init__(self):
print("hi")
self.one = 1
def print_one(self):
print(self.one)
if __name__ == "__main__":
test_class = Test()
test_class.print_one()
test_class.self.print_bar(test_class)
Notice the ugly call in bar.py
that runs test_class.self.print_bar(test_class)
. In this case, python does not automatically pass the class as a method. If I get rid of the test_class
argument passed in the function it does not run and gives a TypeError
. I want to avoid passing self
to the method at all costs.