I keep noticing blocks of code starting with import string, import re or import sys.
I know that you must import a module before you can use it. Is the import based on the object?
The import is based on what module you want to access the names of.
Python has modules that give the code more functionalities. import re gives access to the re module which gives RegEx support. If you type help() at the Python interpreter and then type modules, it will return a list of all the modules.
import sys
Will have the effect of adding a sys variable to your local namespace (usually at the module level). Because sys is a module with it's own attributes, then you can say sys.something(), and Python will be able to reference the local name sys, and then the attribute something, and then call it ().
from os.path import join
This will look inside the os package, inside the path subpackage, and create a local reference to the join function in your namespace. That way, you can simply refer to it as:
join('a', 'b')
Suggest you look at a couple of tutorials that cover importing.
Related
I have a small application that I would like to split into modules so that my code is better structured and readable. The drawback to this has been that for every module that I import using:
import module
I then have to use module.object for any object that I want to access from that module.
In this case I don't want to pollute the global namespace, I want to fill it with the proper module names so that I don't have to use
from module import *
in order to call an object without the module prepend.
Is there a means to do this that isn't consider to be poor use of from import or import?
Two reasonable options are to import with a shorter name to prepend. E.g.
import module as m
m.foo()
Or explicitly import names that you plan to use:
from module import (foo,bar)
foo()
You should avoid using an asterisk in your imports always. So to answer your question, I would say no, there isn't a better way than just:
import module
module.method()
OR
import really_long_module_name as mm
mm.method()
Take a look here at the pep8 guide "Imports" section:
https://www.python.org/dev/peps/pep-0008/#imports
Wildcard imports ( from import * ) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).
Specific is safer than globbing and I try to only import what I need if I can help it. When I'm learning a new module I'll import the whole thing and then once it's in a good state I go back and refactor by specifically importing the methods I need:
from module import method
method()
I would have to say that you should use the module's name. It's a better way of usage, and makes your code free of namespace confusions and also very understandable.
To make your code more beautiful, you could use the as import:
import random as r
# OR
from random import randint as rint
One solution that I think is not very beautiful, but works, that comes to mind, in case you don't want to pollute the global namespace, you can try to use the import statements, for example, inside functions.
For example:
>>> def a():
... from random import randint
... x = randint(0,2)
... print x
...
>>> a()
1
>>> randint(0,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'randint' is not defined
This way, the local namespace of the specific function is filled with the values from the module but the global one is clean.
I've written a basic program with a couple of classes, and I've had two issues I would like help with. All of the files are in the same directory, and my classes are in files with the same name as the class.
First, my class files can only import with the format
from module import class
I can't use the format
import module
Second, I've only been able to use my classes if I do the import inside of main. When I import at the beginning of the file, I get an unboundlocalerror when creating an object. I've had these issues (especially the 1st one) on more than one program. Any ideas?
Thanks!
You cannot, as you found out, use
import class
You either have to use
from module import class
And you'd call the class simply as
class # note you don't have the module namespace
Or if you'd like to keep the namespace (which I'd recommend)
import module
Then you can say
module.class
module.otherclass
...etc
As you found, you cannot just type:
import class
as that would lead python to believe that you wanted to import a module named class, when what you want is the class inside the module. That is why
from module import class
does work, as it shows python where 'class' is.
I'm working on my making a simple tester for my project, my project is a group of many self contained python files (e.g. solution1.py, solution2.py, etc.). My tester works, but it requires me to do import solution1, solution2, ..., how can I just import everything that matches a pattern?
I have tried creating a list of the files using glob and importing the list, but that gave:
ImportError: No module named solutions
I tried to eval() it, but that was 'invalid syntax'.
Perhaps the question is, how can I interpolate a list of strings into a list of modules?
Thanks!
You can import a module identified by a string with the importlib module:
import importlib
list_of_module_names = ...
for s in list_of_module_names:
importlib.import_module(s)
You can use importlib.import_module() to import a module named by a string.
If you wanted to construct an import statement instead, you'd need to use exec() instead of eval(). The latter can only evaluate expressions; the former executes statements.
I'm looking to import all the classes from one Python file to the other?
In the class you wish to import from, include a variable called __all__, and fill it with the names of the classes/variables you want.
__all__ = ['Class1', 'Class2', 'variable_i_want']
In the class you wish to import them to, you may use the asterisk to gain access to all of the classes.
from foo import *
As suggested, be careful of name collisions when doing this.
Just import the file like any other
import mythings
Then you can use
myClass = mythings.MyClass()
In addition to what the other people are saying, the file you are importing must exist somewhere in sys.path. (usually your current directory is in there, so same directory imports are no problem) For example, if you want to import from your parent directory:
#want to import ../myotherfile.py
import os
import sys
sys.path.append(os.path.abspath(os.pardir))
import myotherfile
print(myotherfile.func())
from module import *
You must be careful when doing this as you can get name collisions.
I just upgraded to Python 2.7.1 (on Mac) so I could use OrderedDicts.
After trying to run the following script:
import collections
test = OrderedDict()
I got:
NameError: name 'OrderedDict' is not defined
I fixed it with:
from collections import OrderedDict
...but I want to know why I needed to do that?
Why didn't the broad import collections work for me?
import collections
imports the collections module into the current namespace, so you could work with this import like this:
import collections
orderedDict = collections.OrderedDict()
However, if you only need a specific function (and not the entire library), you could do this:
from collections import OrderedDict
imports just the specified class into the current namespace.
You can do import * from fooModule but it's bad juju and makes Guido cry.
For a brief explanation of why it is the way it is, import this.
I think it goes like this:
When you do import collections, you’re actually assigning the module “collections” to a variable called collections in the current namespace.
At this point, you can access the OrderedDict class inside the collections module using collections.OrderedDict.
What import collections doesn’t do is assign any other variables in the local namespace. Specifically, it doesn’t automatically assign a variable to everything within the collections module (although, as noted in another answer, you can do this explicitly).
As to why it doesn’t do this, I think it stems from item two in The Zen of Python: “Explicit is better than implicit.”
That's the way Python works. Originally you just imported the module and it made the "collections" namespace available in your module with the name "collections". To reference anything in that module you must qualify it as collections.OrderedDict. The from form pulls an object reference from the module into your module namespace so you don't need to qualify it.