I am newbie to Python 3 and currently learning how to create Python modules. I have created below package structure.
maindir
test.py
package
__init__.py
subpackage
__init__.py
module.py
This is my module.py file
name="John"
age=21
and this is my test.py file
import package.subpackage.module
print(module.name)
When I run test.py I am getting this error NameError: name 'module' is not defined
However, when I change the import statement to import package.subpackage.module as mymod and print the name with print(mymod.name) then its working as expected. Its printing name John.
I didn't understand why its working with second case and not with first.
Perhaps what you were attempting was this:
from package.subpackage import module
Then you can reference module as a name afterwards.
If you do:
import package.subpackage.module
Then your module will be called exactly package.subpackage.module.
With little bit of reading I understood this behaviour now. Please correct me If I am wrong.
With this import package.subpackage.module style of import statement you have to access the objects with their fully qualified names. For example, in this case
print(package.subpackage.module.name)
With aliasing I can shorten the long name with import package.subpackage.module as mymod and print directly with print(mymod.name)
In short print(package.subpackage.module.name) == print(mymod.name)
Related
i've run through many posts about this, but still doesn't seem to work. The deal is pretty cut. I've the got the following hierarchy.
main.py
DirA/
__init__.py
hello.py
DirB/
__init__.py
foo.py
bla.py
lol.py
The__init__.py at DirA is empty. The respective one at DirB just contains the foo module.
__all__.py = ["foo"]
The main.py has the following code
import DirA
import DirB
hey() #Def written at hello.py
foolish1() #Def written at foo.py
foolish2() #Def written at foo.py
Long story short, I got NameError: name 'foo' is not defined. Any ideas? Thanks in advance.
You only get what you import. Therefore, in you main, you only get DirA and DirB. You would use them in one of those ways:
import DirA
DirA.something_in_init_py()
# Importing hello:
import DirA.hello
DirA.hello.something_in_hello_py()
# Using a named import:
from DirA.hello import something_in_hello_py
something_in_hello_py()
And in DirB, just make the __init__.py empty as well. The only use of __all__ is for when you want to import *, which you don't want because, as they say, explicit is better than implicit.
But in case you are curious, it would work this way:
from DirB import *
something_in_dirb()
By default the import * will import everything it can find that does not start with an underscore. Specifying a __all__ restricts what it imported to the names defined in __all__. See this question for more details.
Edit: about init.
The __init__.py is not really connected to the importing stuff. It is just a special file with the following properties:
Its existence means the directory is a python package, with several modules in it. If it does not exist, python will refuse to import anything from the directory.
It will always be loaded before loading anything else in the directory.
Its content will be available as the package itself.
Just try it put this in DirA/__init__.py:
foo = 42
Now, in your main:
from DirA import foo
print(foo) # 42
It can be useful, because you can import some of your submodules in the __init__.py to hide the inner structure of your package. Suppose you build an application with classes Author, Book and Review. To make it easier to read, you give each class its own file in a package. Now in your main, you have to import the full path:
from myapp.author import Author
from myapp.book import Book
from myapp.review import Review
Clearly not optimal. Now suppose you put those exact lines above in your __init__.py, you may simplify you main like this:
from myapp import Author, Book, Review
Python will load the __init__.py, which will in turn load all submodules and import the classes, making them available on the package. Now your main does not need to know where the classes are actually implemented.
Have you tried something like this:
One way
from DirA import hello
Another way
from DirA.hello import hey
If those don't work then append a new system path
You need to import the function itself:
How to call a function from another file in Python?
In your case:
from DirA import foolish1, foolish2
I am trying out the answer in this.
The __init__.py file in a folder named MyLibs contains:
LogFile = r'D:\temp'
In utils.py in the same folder MyLibs, I tried various ways to access the LogFile variable:
from __init__ import *
print LogFile #Gives: NameError: name 'LogFile' is not defined`:
and:
import __init__
print MyLibs.LogFile #Gives: NameError: name 'MyLibs' is not defined
I got the errors while executing from MyLibs.utils import *
What is the fix I must do? I prefer a method where I can reference LogFile directly without having to add namespace prefixes.
My mistake.
The updated __init__.py was somehow not executed. I started a new Python session and it worked.
Sorry for the false alarm.
Not sure how to do this with 2.7's implicit relative imports, but you could try this:
from __future__ import absolute_import
from . import LogFile
If you're running the Python module directly, you need to run it with python -m MyLibs.utils rather than python MyLibs/utils.py.
I got the following files
1 ./run.py
2 ./code/util.py
3 ./code/__init__.py
and inside util.py I have
def funA():
print 'Hello World !'
and inside ./code/init.py I have
__all__=['util'];
from util import *
now I open python prompt (actually, ipython) in the current directory then I type
from code import *
and all I've got is the util module
util module <module 'code.util' from 'code/util.pyc'>
and I have to include the package name in order to use funA().
I expected that funA is now in my namespace and I can use it without the package name code.funA . However, this is not the case and I am wondering where the problem is.
I guess I am still somewhat confused to how exactly __ init __.py should be used.
The purpose of __all__ (as documented) is to indicate that you want only the names listed there to be available via from mymodule import *. By specifying only 'util', you are explicitly telling your package to not make anything but util available. If you remove that __all__, then everything you import from within util will also be available in code, and so if you do from code import *, then everything from util will also be available.
Whether this is a good idea is another matter. Importing * often leads to confusion.
i'm creating a python program, and i want to split it up into seperate files. I'm using import to do this, but its not working (specifically, a variable is stored in one python file, and its not being read by the main one.
program /
main.py
lib /
__init__.py
config.py
functions.py
I have in main.py:
import lib.config
import lib.functions
print(main)
and config.py has
main = "hello"
I should be getting the output "hello", when i'm executing the file main.py, but i'm not. I have the same problem with functions stored in functions.py
Any help would be great,
Importing the module with a simple import statement does not copy the names from that module into your own global namespace.
Either refer to the main name through attribute access:
print(lib.config.main)
or use the from ... import ... syntax:
from lib.config import main
instead.
You can learn more about how importing works in the Modules section of the Python tutorial.
In my project I want to change the main package name.
I've a dir structure like this:
hallo/sub
hallo/foo
hallo/bar
And I want to change the main name for example to 'goodbye':
goodbye/sub
goodbye/foo
goodbye/bar
But as result the new name is always rejected! for example if I import
import goodbye.sub.utils as utils
It return the error
ImportError: No module named sub.utils
And clearly the old name don't works.
The file __init__.py is written in all subdirectories!
I've tried to remove all *.pyc files and cache directory, I've tried to re-clone the project in another directory, but nothing, the new name is always rejected!
I'm using python2 under *nix and I'm never moved under windows.
Some idea?
Edit:
The old name works perfectly:
import hallo.sub.utils as utils
Has always worked without any errors, the problem is the name change.
For imports from the outside, check the contents of __init__.py for variables that can throw things off -- like __all__.
Also, the typical idiom is:
from hallo.sub import utils #tyically this
import hallo.sub.utils as utils #instead of this
I can't imagine why that would make a difference, but python occasionally has silly bugs.
For imports from within the package, you can instead use relative imports. Within your hallo package you can change this:
import hallo.sub as sub
import hallo.sub.utils as utils
to this
from . import sub
from .sub import utils
Then it doesn't matter what the outer package is called.