I’m building a library where one of the modules need to write a file at an “unknown” location. to put it more concretely, I have some layout like this:
src
│ base.py
└───dir1
│ │
| └───A1
| | |
| | └───A1.py
| |
│ └───A2
| |
| └───A2.py
│
└───dir2
│ B.py
both A1 and A2 are implementations of the Abstract class A that is located in the base.py file.
B holds an instance of either A1 or A2 but it doesn’t know which because he only sees it as the super class A using polymorphism.
B made some calculations on the object and wants to save the data under the correct folder depending on the instance, so if the object is A1 it will write the file to the A1 directory and if its A2 it will write it to the A2 directory.
I’m trying to avoid solutions that requires changes to the subclasses A1 and A2 because that would mean more work for the user if he wanted to add another module A3(which is a big part of the project) by setting his own path that may also be outside of the library’s root folder.
Unfortunately, python doesn’t set a ‘_file_’ variable for objects automatically, so the simple
from src.dir1.A1.A1 import A1
a1 = A1()
print(a1.__file__)
doesn’t work and returns AttributeError: 'A1' object has no attribute '__file__'
I can set the ‘_file_’ attribute in the class manually but it feels wrong and also doesn’t solve the problem:
if I set it in the super class I don’t get the directory of the instance object, just the super class which is not where I need to write the file.
if I set it in the subclasses for example:
class A1(A):
__file__ = os.path.abspath(os.path.dirname(__file__))
I get the correct path but it wont automatically work for A2 or A3 created by the user.
I’m looking for any general solution that wont require the “user” to do anything for this to work.