This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python: Circular (or cyclic) imports
I'm new to Python, and I'm having an issue, but I'm not exactly sure if this is my issue. I have two files, user.py and comments.py. In user.py, I do
from comments import Comment
and in comments.py I do
from user import User
My user loads fine, but when I load the URL that leads to comments, I get a server error. Commenting out the from comments import Comment fixes the problem. Am I doing something wrong?
Yes, you have a circular import, and those cause many many problems. If you think about what is actually happening when you import, it is analogous to saying, "copy the code from file x in to this file," but if you copy from x to y then back from y to x, you've created an infinite loop where it's difficult to impossible for the interpreter to figure out which module is supposed to supersede or load which in which situations. However, if your program is architected properly, you should not have any. What reason do you have for having this circular import? Chances are you don't actually need it at all if we look at the problem a little more carefully.
This kind of circular import does not work. Importing a module means essentially executing the statements in it. The import statements are executed in the moment they are encountered, so in at least one of the modules the other module has not yet been initialised, so the import will fail.
A circular dependency is considered an antipattern. There are situations where they somehow occur naturally, but in general they are a sign of a bad design.
You can probably make this work by moving one of the import statements to the end of the module or to function level, but I'd recommend against these "fixes".
Related
This is a novice question.
Consider the below code block :
try:
import os
except ImportError as error:
print " Unable to import buildin module os"
raise error
Do we need to add exception block while importing python built-in modules(like above? What would cause to fail importing a built in module?
Can someone point at python documentation explaining this theory?
Short answer, no.
Longer answer: it doesn't help your program much to catch exceptions that you can't do anything about. Some file is missing -- you can report it, maybe ask the user again, or perhaps it is known that this sometimes happens and you can give a clear error message explaining why. Some API call fails -- maybe it can be retried, or someone needs to receive a message that a service is down.
But something as basic as this... First, it never happens (I've never seen import os fail in twenty years). Second, if that fails, there's nothing your program can usefully do (if this fails, chances are print also fails). And also, the library documentation doesn't say that this is something that can happen.
You have to rely on the basic system working. Only catch exceptions when it is known that they could be raised and you have a way to deal with them.
There are a couple of reasons that the code in the question is pretty much pointless.
First of all, it does not add any new information. The error is just reraised. The printout adds no new information that isn't already in the error and stack trace.
Second, as #RemcoGerlich's answer points out, you are asking specifically about builtin modules. It would make sense to react to the absence of an optional module by either finding a replacement or turning off program features, but there's nothing much you can do in response to your platform being broken.
Failure of builtin imports is never addressed in the documentation explicitly to the best of my knowledge. Builtin module imports can fail for any of the reasons a normal import can fail. Builtins are a collection of Python files and C-extensions (in CPython at least). Modifying, replacing, deleting any of these files can lead to anything from import failures to the interpreter not starting up at all. Setting the wrong file permissions can have a similar effect.
I tried searching around but didn't seem to find an answer to my problem, so I'm sorry if I missed something and it actually has been answered before.
So basically I have main.py and another file called check.py (both in same directory)
In my main.py I have:
from check import checkfunction
I have a small function inside main.py that I MUST call inside check.py, but I can't seem to get this import working on my check.py:
from main import mainfunction
How can I get the mainfunction to work inside check.py?
Thanks!
You've got a design with a circular dependency which is usually a bad thing as your two python modules are tightly coupled.
Consider refactoring your code. But if you must stick with your design please see the following SO question for more info on how circular imports work in Python and the various gotchas to look out for.
Several options:
Move the common function to a module imported by both other modules.
Merge both modules into one.
Pass the function from main to the code that needs to call it.
Monkey patch the function into the check module after importing it.
Refactor the whole thing so that you don't have circular dependencies.
If you actually explained why you have this design, someone could possibly propose a better way.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python import coding style
When I write some code that requires an import, and the import is only introduced by the bit of code I'm currently writing, should I:
Stick the import at the top of the file where it is made clear that to make this module work it needs these imports, yet the import is detached from the usage and should the need be removed later the module may still import stuff it doesn't ever actually use, or
Keep the import with the code that uses it immediately thereafter so it is obvious what the import is used to do and whence it can be safely removed, but risk importing the same libs multiple times and make it hard to work out what libs are required to make the module work.
Best practice?
Put the import at the top? Or put it where it gets used?
Import_Statement_Overhead from the Python wiki states:
"import statements can be executed just about anywhere. It's often
useful to place them inside functions to restrict their visibility
and/or reduce initial startup time. Although Python's interpreter is
optimized to not import the same module multiple times, repeatedly
executing an import statement can seriously affect performance in some
circumstances."
I follow general stylistic conventions and put all of my import statements at the top of the program. PEP 8 states re imports:
"Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants."
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Should Python import statements always be at the top of a module?
I recently answered a SO question and provided this routine as a solution:
def set_fontsize(fig,fontsize):
import matplotlib
"""
For each text object of a figure fig, set the font size to fontsize
"""
if not isinstance(fig,matplotlib.figure.Figure):
raise Exception("fig is not a matplotlib.figure.Figure")
for textobj in fig.findobj(match=matplotlib.text.Text):
textobj.set_fontsize(fontsize)
I imported matplotlib into the definition of set_fontsize(fig,fontsize) because it's not guaranteed that someone using this routine would import matplotlib at a more-global scope (better terminology?). Especially since many of the matplotlib examples invoke routines using this import: import matplotlib.pyplot as plt.
Are there instances where my import of matplotlib would cause a conflict?
Are there any efficiency costs?
Is there a preferable/more-common alternative to test if fig is an instance of matplotlib.figure.Figure; an alternative that does not require importing the module?
there's nothing wrong with importing inside functions and classes - it's a useful way of handling mutually recursive imports (where two files each imports the other), for example.
however, there is something wrong with checking the type of an argument. idiomatic python would not check the type of fig. instead, just let misuse fail wherever it fails. this is because you are breaking "duck typing" - people cannot call your routine with objects that "work like" fig, even if they want to (an obvious example is testing mocks; another example is someone writing a replacement for matplotlib that has the same API, but looks or works better).
so, for the code you have there, it is not necessary to have the import at all. just use fig.
more generally, imports are cached when first used, so you typically don't need to worry much about efficiency (i'm not saying it's perfect, but it's the kind of thing you need to profile before worrying about).
There's nothing particularly wrong with importing inside the function - although you should do it after the docstring, otherwise Python won't see the docstring - but your reasoning doesn't make any sense.
If you import at module level, and someone imports your function, the function has access to all the things in its module, including imports. Users of your function don't need to import anything specifically.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Perl's AUTOLOAD in Python (getattr on a module)
I'm coming from a PHP background and attempting to learn Python, and I want to be sure to do things the "Python way" instead of how i've developed before.
My question comes from the fact in PHP5 you can set up your code so if you attempt to call a class that doesn't exist in the namespace, a function will run first that will load the class in and allow you to continue on as if it were already loaded. the advantages to this is classes weren't loaded unless they were called, and you didn't have to worry about loading classes before using them.
In python, there's alot of emphasis on the import statement, is it bad practice to attempt an auto importing trick with python, to alleviate the need for an import statement? I've found this module that offers auto importing, however I dont know if that's the best way of doing it, or if auto importing of modules is something that is recommended, thoughts?
Imports serve at least two other important purposes besides making the modules or contents of the modules available:
They serve as a sort of declaration of intent -- "this module uses services from this other module" or "this module uses services belonging to a certain class" -- e.g. if you are doing a security review for socket-handling code, you can begin by only looking at modules that import socket (or other networking-related modules)
Imports serve as a proxy for the complexity of a module. If you find yourself with dozens of lines of imports, it may be time to reconsider your separation of concerns within the module, or within your application as a whole. This is also a good reason to avoid "from foo import *"-type imports.
In Python, people usually avoid auto imports, just because it is not worth the effort. You may slightly remove startup costs, but otherwise, there is no (or should be no) significant effect. If you have modules that are expensive to import and do a lot of stuff that doesn't need to be done, rather rewrite the module than delay importing it.
That said, there is nothing inherently wrong with auto imports. Because of the proxy nature, there may be some pitfalls (e.g. when looking at a thing that has not been imported yet). Several auto importing libraries are floating around.
If you are learning Python and want to do things the Python way, then just import the modules. It's very unusual to find autoimports in Python code.
You could auto-import the modules, but the most I have ever needed to import was about 10, and that is after I tacked features on top of the original program. You won't be importing a lot, and the names are very easy to remember.