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 *
Related
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.
The error says that the there is no module named as "gtts.gTTS", and got this error many times while importing other modules. So can you brief me what is the logic behind importing modules? Can't we import class using "." operator?
What is the problem; I can't understand!
#what is the difference between these two codes
import gtts.gTTS
from gtts import gTTS
Unlike Java, where you do something like import module.submodule.blah.blah.MyClass, in Python, you can only directly import modules. If you want to only import a certain class, function, or other named value from a module, you need to use the from ... import ... syntax.
In all likelihood, gtts is a module, and gTTS is a class within that module. Therefore, import gtts.gTTS makes no sense, since gTTS isn't a module (that's what the error says), you must use from gtts import gTTS
For example, import os.path works fine, since path is a submodule of os, but if I wanted to use the exists function in path, I would need to use from os.path import exists or import os.path; os.path.exists(...). I get a ModuleNotFoundError if I erroneously try import os.path.exsts.
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
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.
I have around 2000 lines of code in a python script. I decided to cleanup the code and moved all the helpers in a helpers.py file and all the configs and imports in a config.py file
Here my main file:
from config import *
from helpers import *
from modules import *
And in my config file I've writted
import threading as th
And then in modules I am extending a thread class
class A(th.Thread):
...
I get an error that th is not defined.And when I import config in my modules class, it works fine. I don't have a clear picture on how imports work here.
Also, is there any best practice to do it?
Python's from module import * isn't the same as require/include that you may see in other languages like PHP.
The star import works by executing/loading the module first, then merging the module's namespace to the current namespace. This means that module have to import its own dependencies itself. You can do that by adding from config import * in module, or better to do import threading as th in module as well.
Read import threading as th as th = __import__("threading"): it's an assignment first and foremost. Thus, you have to do the import in every file where you're using the variable.
PS: import * is best avoided.