Karthick
Karthick

Reputation: 47

Import sys not getting imported when given inside a function [Python]

generic_import.py

def var_import():
  import sys
  import glob

main.py

from generic_import import *
var_import()

whenever I run the main file, I get

NameError: name 'sys' is not defined

However when import sys is outside the function,the code is executed without any error.

generic_import.py

import sys
def var_import():
   import glob

What's the reason behind this ? I want to import it inside the fucnction.

Upvotes: 0

Views: 1487

Answers (1)

MSeifert
MSeifert

Reputation: 152667

The reason for this is the Scope of the Imports.

You are importing the libraries inside a function so the scope of these is var_import and as soon as the function terminates the scope is discarded. You would need to return the imported libraries and then save them inside the scope you want to use them.

But I would recommend just import libraries as needed without any generic_import functionality.

If you are worried about namespace conflicts: You can always use aliases like import sys as python_builtin_sys but I wouldn't recommend this either.


Since you asked about how to get the modules outside the function scope I'll provide a short example code.

def var_import():
    import sys
    import glob
    return sys, glob

and you can get them into your wanted scope by using something along the lines of:

from generic_import import var_import  # Do not use "import *"
sys, glob = var_import()

or something more advanced if you don't know the number of loaded modules.

Upvotes: 2

Related Questions