1

Is there a way to import a module inside a function, then use it outside that function? I'm assuming the issue is that the import name is local and not global. I don't know how to fix it.
sample code:

def func1():
    import modshare
    modshare.ken=2
    print("func1")

    func2()

def func2():
    print("func2")
    # Error here modshare undefined 
    modshare.ken = 2

func1()
ywbaek
  • 2,971
  • 3
  • 9
  • 28
Ted pottel
  • 6,869
  • 21
  • 75
  • 134
  • 1
    Importing within functions is not a great practice, is there any reason you don't want to import it globally in the beginning of the file? – Michael Hawkins Jun 22 '20 at 21:33

2 Answers2

1

Yes, though whether it's a good idea, and what method is best, depends on what you're trying to do. More details would be needed for that.

1. Pass as argument

Modules are objects, so you can pass them around.

def func1():
    import sys
    func2(sys)

def func2(module):
    print(module)

func1()  # -> <module 'sys' (built-in)>

2. Global

Module names are variables, so you could use a global declaration, though globals are generally a bad idea, so avoid this if you can.

def func1():
    global sys
    import sys
    func2()

def func2():
    print(sys)

func1()  # -> <module 'sys' (built-in)>
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

If I think I'm following what you are asking, then maybe this will work. First off, let me start by saying that importing within functions is not a good practice and should be avoided when you can. It makes things messy to maintain. Try returning the modified object (assuming the import is a class or something) from the first function when passing it to the next function (essentially making a copy of it):

def func1():
    import modshare as result
    result.ken = 2
    print("func1")
    return result

def func2():
    func2_result = func1()
    func2_result.ken = 5
    print("func2")

func2()
Michael Hawkins
  • 2,793
  • 1
  • 19
  • 33