0

I have the following structure in my project:

    myProject
    |- classes
       |- myclass.py
    |- main.py

But myclass.py doesn't see variables defined at main.py

main.py:

import pandas as pd
from classes.myclass import myclass
outputPath = '/some/path/'
classInst = myClass()

myclass.py:

import pandas as pd

class myClass:
    def __init__(self):
        global outputPath
        self.outputPath = outputPath
        dataFrame = pd.DataFrame(columns=['col1', 'col2'])

Is it possible to define global variables in outputPath in main.py only and use in that in all classes?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
VictorDDT
  • 583
  • 9
  • 26
  • 1
    You can access `outputPath` from `myclass.py` via `import main; print(main.outputPath)`. – Maximilian Peters Jan 27 '19 at 22:13
  • 1
    Any reason not to pass output_path as a parameter at class init? `classInst = myClass(output_path='/some/path/')`? – Jérôme Jan 27 '19 at 22:14
  • 2
    If you want to avoid circular import issues (main import classes, classes import main), you may add a third file imported where needed. E.g. params.py, containing that `output_path` declaration. – Jérôme Jan 27 '19 at 22:16
  • @Jérôme: There are many such parameters I would like to have them as a config somewhere and not to send them to each class instance. – VictorDDT Jan 27 '19 at 22:22
  • Please stick to a *single* question per post. `import` in Python is a form of *binding*, you are adding names for objects you need in that module. If you need access to Pandas in `myclass` then you must import *something* that gives you access to the Pandas module. There is little point in making your code harder to follow by trying to avoid using `import pandas`. – Martijn Pieters Jan 27 '19 at 22:38

0 Answers0