-1

I have a function in a file example1.py which looks like:

def A():
    global var
    ....
    def B():
    .....
        return x
    #calculations using var,function B
    return var

def C(var):
....
    return something

I want to import all functions into other file example2.py using

from example1 import *

I see function A is working fine in example2.py but function C is not returning the expected value. Whats wrong in my import?

Jayanth
  • 329
  • 2
  • 5
  • 17
  • 2
    Please show `example2.py` contents. – Sachin Jun 13 '17 at 09:22
  • I would suggest that passing the results of functions around using globals is not the best way to work. Each function should take a number of arguments and return a result like you seem to have done using `return var` – scotty3785 Jun 13 '17 at 09:42
  • Related [question](https://stackoverflow.com/q/4020419/1435475). – guidot Jun 13 '17 at 10:05

1 Answers1

1

You generally should avoid using globals to pass the results of functions between modules.

Consider the following example

file1.py

def add(num1,num2):
    var = num1 + num2
    return var

main.py

from file1 import add

result = add(5,6)
print(result)

The addition function inside file1.py is imported by main.py. main.py then uses that function and passes two arguments to it (5 and 6). add does the calculation and returns the result where it is then stored in result for further use in main.py.

This is a basic coding skill in any language and your question suggests that you should go through a number of python tutorials and fully understand them. Many other stack overflow users would not be so helpful as I have just been and expect you to know the basics of a language before asking questions.

scotty3785
  • 6,763
  • 1
  • 25
  • 35