0

file1

from file3 import helper_func # a function
from file3 import fixed_var # a constant (type string)

def new_func(id):
    url = fixed_var + f'_and_{id}'
    output = helper_func(url)
    return output

file2 attempt1

from file1 import new_func 

new_func('words')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

file2 attempt2

from file3 import helper_func # a function
from file3 import fixed_var # a constant
from file1 import new_func 

new_func('words')
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

The error is thrown both times for the line url = f'{fixed_var}_{id}'. fixed_var is None in both attempt1 and attempt2. Presumably, even if i were to get past this line, the next line would throw an error along the lines of cannot find function helper_func.

How can I import new_func from file1 into file2 and use?

Thanks.

Canovice
  • 9,012
  • 22
  • 93
  • 211
  • 1
    I wonder if there is a reason not to have this variable as a function parameter? – Marat Nov 10 '21 at 16:22
  • 1
    If the value of `fixed_var` is determined after a certain function call in `file3` this may happen. The value of `fixed_var` will be `None` until some value is given to it. Also please make sure you have an empty file named `__init__.py` in the directory where all these files are located. – unityJarvis Nov 10 '21 at 16:31
  • Are you sure you've shown us all of file1? f`{fixed_var}_{id}` does not call `+`. You're sure that there's not some other definition of `new_func` later in that file. The error message you're showing makes no sense. – Frank Yellin Nov 10 '21 at 16:48
  • @FrankYellin the original code was `url = fixed_var + f'_{id}'` – Canovice Nov 10 '21 at 21:33
  • It seems `new_func` did find `fixed_var`, and its value was `None`. So there is no reason it shouldn't also find `helper_fun`. The error you're getting clearly indicates that `fixed_var` does have a value, just not the one you're expecting. – Frank Yellin Nov 10 '21 at 21:35
  • Correct, `fixed_var` is a basic constant string variable being loaded, so it definitely shouldn't be None. – Canovice Nov 10 '21 at 21:43
  • @unityJarvis what does the `__init__.py` file do here that would help with the issue? – Canovice Nov 10 '21 at 22:18
  • @FrankYellin I've updated the example code above to accurately reflect the error message. I'm still not sure how to make it so that the value of `fixed_var` is not equal to **None** – Canovice Nov 10 '21 at 22:20
  • @Canovice - Although Python works without an `__init__.py` file you should still include one. It specifies that the directory should be treated as a package, so, therefore, include it (even if it is empty). - Read more from this answer - https://stackoverflow.com/a/50307979/12950723 – unityJarvis Nov 11 '21 at 03:02

0 Answers0