I have two python files main.py and conftest.py. I want to access a variable of a method of the class Test declared in main.py from a function declared in conftest.py.
I have tried a bit, but I know it's wrong as I get a syntax error in the first place. Is there any way to do this?
main.py
class Test():
def test_setup(self):
#make new directory for downloads
new_dir = r"D:\Selenium\Insights\timestamp}".format(timestamp=datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
# print(new_dir)
if not os.path.exists(new_dir):
os.makedirs(new_dir)
saved_dir=new_dir
conftest.py
from main import Test
def newfunc():
dir=Test.test_setup()
print(dir.saved_dir)
In the execution of your function
newfunc()the first instructiondir=Test.test_setup()raise the following error:This error referred to an attempt to execute a method of a class by attribute reference but it requests an argument which is in general an instance of that class.
To solve this, and other errors present in your code, and build an answer to your question I think that it is enough to do following steps:
save_diras an attribute of the classTestTestclass.In your code
saved_diris a local variable of the methodtest_setupso it is not visible outside of that method.I show you the 2 possible correct files:
File main.py
Pay attention: don't use directly the previous code because in
main.pyI have adjusted the value ofnew_diraccording to my environment (see/home/frank/Selenium/Insights/timestamp/instead of yourD:\Selenium\Insights\timestamp).File conftest.py:
If you want to access to the attribute
saved_dirdirectly without the use of methodget_saved_dir()(not very object oriented) the fileconftest.pybecomes:Accessing the attributes of a class by reference
This is a useful link (it is included in the tutorial of official Python documentation) about the access to a variable or a method of a class.
Previous link explains how to access to an attribute of a class by reference. If we adapt this concept to this post we can access the method
test_setupof the classTest, by the following syntax:If we print on the standard output the value of
fwe obtain:and this means that
fis a valid attribute reference to a function object. In particular I referred to the following sentence of the link: