Can you import another script/module from a variable? - python

Do you always have to "hard-code" imports or could you techically import for example another script whose name is inside an variable? The desired behaviour is:
var_my_script_name = "my_script"
import var_my_script_name

You sure can! just use the module importlib:
import importlib
name_of_my_module_or_script="my_script"
my_module_object = importlib.import_module("my_script")
# Can also import built-in or third-party modules
np = importlib.import_module("numpy")

Related

Why does python import module imports when importing *

Let's say I have a file where I'm importing some packages:
# myfile.py
import os
import re
import pathlib
def func(x, y):
print(x, y)
If I go into another file and enter
from myfile import *
Not only does it import func, but it also imports os, re, and pathlib,
but I DO NOT want those modules to be imported when I do import *.
Why is it importing the other packages I'm importing and how do you avoid this?
The reason
Because import imports every name in the namespace. If something has a name inside the module, then it's valid to be exported.
How to avoid
First of all, you should almost never be using import *. It's almost always clearer code to either import the specific methods/variables you're trying to use (from module import func), or to import the whole module and access methods/variables via dot notation (import module; ...; module.func()).
That said, if you must use import * from module, there are a few ways to prevent certain names from being exported from module:
Names starting with _ will not be imported by import * from .... They can still be imported directly (i.e. from module import _name), but not automatically. This means you can rename your imports so that they don't get exported, e.g. import os as _os. However, this also means that your entire code in that module has to refer to the _os instead of os, so you may have to modify lots of code.
If a module contains the name __all__: List[str], then import * will export only the names contained in that list. In your example, add the line __all__ = ['func'] to your myfile.py, and then import * will only import func. See also this answer.
from myfile import func
Here is the fix :)
When you import *, you import everything from. Which includes what yu imported in the file your source.
It has actually been discussed on Medium, but for simplification, I will answer it myself.
from <module/package> import * is a way to import all the names we can get in that specific module/package. Usually, everyone doesn't actually use import * for this reason, and rather sticked with import <module>.
Python's import essentially just runs the file you point it to import (it's not quite that but close enough). So if you import a module it will also import all the things the module imports. If you want to import only specific functions within the module, try:
from myfile import func
...which would import only myfile.func() instead of the other things as well.

How to properly import scatter_matrix() function from pandas?

It does not see the scatter_matrix, says "not found":
import pandas.plotting
scatter_matrix(df[['col1', 'col2']])
I tried this:
import pandas.plotting.scatter_matrix
ImportError: No module named 'pandas.plotting.scatter_matrix'
actually when I hit tab after "plotting." the popup hint for import is showing some functions to import but no scatter_matrix
But doing this works and plots:
pandas.plotting.scatter_matrix(df[['col1', 'col2']])
Why do i Need the whole path to use scatter_matrix? How to import the scatter_matrix?
Simply change it from
import pandas.plotting.scatter_matrix
to
from pandas.plotting import scatter_matrix
When you're importing you import a file, if you want to import specific function you must specify from what file you want to import it (:
Edit:
There are generally two types of import syntax. When you use the first one, you import the resource directly, like this:
import abc
abc can be a package or a module.
When you use the second syntax, you import the resource from another package or module. Here’s an example:
from abc import xyz
xyz can be a module, subpackage, or object, such as a class or function.
reference- https://realpython.com/absolute-vs-relative-python-imports/

Import set of builtin functions from a python file to another python file

I have set of inbuilt functions in 'pythonfile1.py' located at '/Users/testuser/Documents', the file contains
import os
import sys
import time
Now i want to import 'pythonfile1.py' to 'pythonfile2.py', which is located at '/Users/testuser/Documents/execute'
I have tried with my following code and it didn't work:
import sys
sys.path[0:0] = '/Users/testuser/Documents'
import pythonfile1.py
print os.getcwd()
I want it to print the current working directory
Your question is a bit unclear. Basically, there are two things 'wrong'.
First, your import statement is broken:
import pythonfile1.py
This specifies a file name, not a module name - modules don't contain dots and extensions. This is important because dots indicate sub-modules of packages. Your statement is trying to import module py from package pythonfile1. Change it to
import pythonfile1
Second, there's no need to fetch builtins from another module. You can just import them again.
# pythonfile1
import os
print 'pythonfile1', os.getcwd() # assuming py2 syntax
# pythonfile2
import os
print 'pythonfile2', os.getcwd()
If you really want to use os from pythonfile1, you can do so:
# pythonfile2
import os
import pythonfile1
print 'pythonfile2', os.getcwd()
print 'pythonfile1->2', pythonfile1.os.getcwd()
Note that os and pythonfile1.os in pythonfile2 are the exact same module.
if you want to import stuff from another file, you should use python modules.
If you will create file named init.py then the execute folder becomes a module.
After that you can use
from .pythonfile1 import function_name
or you can use
from .pythonfile1 import *
which imports all, but better solution is name everything you want to use explicitly
you can find more about modules in documentation

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.
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.

Importing imports within a function - Python 2.6

I have two files, SysDump.py and libApi.py in the same folder.
In SysDump I do:
from libApi._SysDump import *
In libApi I have:
def _SysDump():
import cPickle as _cPickle
import math as _math
from zipfile import ZipFile as _ZipFile
import re as _re
However I get the error:
from libApi._SysDump import *
ImportError: No module named _SysDump
I use VS2012+PTVS to step through the code and the execution trace goes to def _SysDump() in libApi as I steop through but does not enter it. Question is how do I make this work in Python 2.6 only please?
from libApi._SysDump import *
When writing this, Python looks for a package libApi and a module in it called _SysDump. A package is equivalent to a folder and a module is a single file. From your explanations, this is not the situation you have in your case. You have a module libApi with a function _SysDump. So if anything, you could do this:
from libApi import _SysDump
So you would get a reference to the _SysDump function. Note that running that function will not give you references to all the modules you are trying to import. Inside the function, the modules will be imported and assigned to local variables. After the function ends, those references are gone.
If you want to have some module take care of all your imports, you could make a file that performs those imports and import everything from that module:
# imports.py
import cPickle as _cPickle
import math as _math
from zipfile import ZipFile as _ZipFile
import re as _re
And then:
from imports import *

Categories