0

Please see the code below, when running I get a not defined name error for path_to and file_name variable. I guess Python can't access those variable when creating the class instance, what's the logic behind it and how do I fix it?

Thanks!

import os
from dataclasses import dataclass
import pandas as pd


def main():
    df = TransactionData(file_name="transactions.xlsx", path_to="./sources")


@dataclass
class TransactionData:
    file_name: str
    path_to: str
    data: pd.DataFrame = pd.read_excel(os.path.join(path_to, file_name))


if __name__ == "__main__":
    main
Asrakh
  • 61
  • 1
  • 7
  • "when running I get a not defined name error for path_to and file_name variable." please, if you are getting an error, **post the full error message including the stack trace.**, not a vague description of the error. The python runtime goes to great lengths to provide you *tons* of useful debugging information, **why would you just omit that**? – juanpa.arrivillaga Nov 18 '22 at 20:47
  • In any case, there is **no `path_to` variable defined anywhere in the scope of the class body where you try to use it**. Note, *this code doesn't actually create a `TransactionData` instance, since you don't actually call `main`*. The error happens when the class definition statement is being executed. – juanpa.arrivillaga Nov 18 '22 at 20:48
  • So you could write a `__post_init__` if you use the `dataclass` code generator, or just don't use the `dataclass` code generator and use a regular class definition. – juanpa.arrivillaga Nov 18 '22 at 20:49
  • the problem is in the definition of the data attribute of TransactionData. you have set it in the `__postinit__` method as it is calculated from the other attributes. – nigh_anxiety Nov 18 '22 at 20:50

0 Answers0