I have a module blah.time where I do some sanity checks and wrapper functions around normal time and date operations:
import time
def sleep(n):
time.sleep(n)
When I call sleep, it just throws a maximum recursion error. I'm guessing the namespace is wrong, so I tried using import time as _time, but I still get the same error.
How do I reference the system time module from within my own module in order to prevent this namespace conflict?
Add from __future__ import absolute_import as the first line in your file.
This will force all imports to be absolute rather then relative. So import time will import the standard module, to import a local module you'd use from . import foobar
I would read http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports and then use from __future__ import absolute_import.
HTH
What's happening is that your time module is shadowing the system time module. The easiest way around the problem is to rename your module to something besides time.
Related
The Issue:
I want to use a module that has been imported from within a different module with it's function.
What I want to achieve:
main.py
import differentFile
print (differentFile.functionName.os.getcwd())
differentFile.py
def functionName():
import os
What I have tried:
Pretty much the above, but it doesn't work as functionName as no function os.
I have managed to achieve the above without using the function, but I need to use the function.
There is no reason to do this, you can simply import os in main
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.
When we import a module, say os, aren't we importing everything in it?
Then what's the use of from moduleName import (delimiter) should be added to the file in order for us to use its constants? and bunch of other things.
Can any one explain the exactly what from moduleName does when we actually have already loaded the module using import?
When you just do import sys for example, you do input everything in it. When you do a from sys import exit you import that specific module to be used without its first module name. Basically, if you use the from sys import exit statment you can just call:
exit()
Instead of:
sys.exit()
It's just a way to save less time writing the full sys.exit() statement. If you use it to load constants, you just allow yourself to write shorter statements to write something. If you have questions just ask!
Suppose I want to use os.path.abspath. I can import os, and type os.path.abspath every time I want to use it. Or I can write from os.path import abspath, and now I just need to type abspath.
The utility of something like:
import os
from os.path import abspath
Is that I can still reference other objects defined in os, like os.path.splitext, but if I use abspath frequently, I only need to type abspath.
Beginner question. I am trying to import a python script "feedparser.py" into another python script "ps5.py". Both scripts reside in the same folder "MIT_OCW" on my desktop. When I try to import "feedparser.py" into "ps5.py" I get an import error ("ImportError: No module named feedparser"). What steps should I take to diagnose the error (I am new to programming)? Thanks.
This is code from ps5.py
import feedparser
import string
import time
These are the paths of feedparser.py and ps5.py
~/Desktop/MIT_OCW/problem set 5/ps5.py
~/Desktop/MIT_OCW/problem set 5/feedparser.py
Originally when I ran the code I got back the "ImportError: No module named feedparser". However, I just tried running it again (without having changed anything) and it worked. I am happy it works but frustrated that I don't know why it didn't work in the first place. Anyway, thanks for your help.
The name of the module is the filename without the extension. So to import feedparser.py, you would use:
import feedparser
To use something from feedparser, say a function f, you would call it from your module like:
feedparser.f()
Actually, I agree with munk and Rushy Panchalon this. You should do the following:
import feedparser as feed
(or any other name)
You wouldn't need to import string or time unless needed for your code.
I agree with #munk, the file extension is not needed when you import a module.
import feedparser
or
import feedparser as f
from feedparser import * #not recommended at all
from feedparser import func1, func2 #where func1 and func2 are functions in your module
Anything will work for Python3 at least.
No need to add the file extension.
import feedparser
Or if you are going to refer the functions/classes in the file very frequently and you arenkt going to redefine the functions/classes in the file:
from feedparser import *
Using the second method will allow you to acces the objects defined in the feedparser file without having to add ‘feedparser.’ before the object name. If that doesn’t work try this(replace text in the curly brackets with the appropriate words):
from {name of the directory in which the feedparser file is located}.feedparser import *
Thank You! Hope that works!
I've done what I shouldn't have done and written 4 modules (6 hours or so) without running any tests along the way.
I have a method inside of /mydir/__init__.py called get_hash(), and a class inside of /mydir/utils.py called SpamClass.
/mydir/utils.py imports get_hash() from /mydir/__init__.
/mydir/__init__.py imports SpamClass from /mydir/utils.py.
Both the class and the method work fine on their own but for some reason if I try to import /mydir/, I get an import error saying "Cannot import name get_hash" from /mydir/__init__.py.
The only stack trace is the line saying that __init__.py imported SpamClass. The next line is where the error occurs in in SpamClass when trying to import get_hash. Why is this?
This is a pretty easy problem to encounter. What's happening is this that the interpreter evaluates your __init__.py file line-by line. When you have the following code:
import mydir.utils
def get_hash(): return 1
The interpreter will suspend processing __init__.py at the point of import mydir.utils until it has fully executed 'mydir/utils.py' So when utils.py attempts to import get_hash(), it isn't defined because the interpreter hasn't gotten to it's definition yet.
To add to what the others have said, another good approach to avoiding circular import problems is to avoid from module import stuff.
If you just do standard import module at the top of each script, and write module.stuff in your functions, then by the time those functions run, the import will have finished and the module members will all be available.
You then also don't have to worry about situations where some modules can update/change one of their members (or have it monkey-patched by a naughty third party). If you'd imported from the module, you'd still have your old, out-of-date copy of the member.
Personally, I only use from-import for simple, dependency-free members that I'm likely to refer to a lot: in particular, symbolic constants.
In absence of more information, I would say you have a circular import that you aren't working around. The simplest, most obvious fix is to not put anything in mydir/__init__.py that you want to use from any module inside mydir. So, move your get_hash function to another module inside the mydir package, and import that module where you need it.