import statement in python - python

Why give full path to call a function when import statement is used to import a module from subpackage of package?
eg . A is package , AA is sub package of A , AA1 is module in AA
import A.AA.AA1
A.AA.AA1.AA1fun()
works correctly
but
AA1.AA1fun()
Why not this and why is 'A' got placed in global namespace why not 'AA1'?

Let's suppose that we perform an import of these two modules:
import A.AA.AA1
import B.AA.AA1
Which of the two modules would be chosen if you run the following functions?
AA.AA1.fun()
AA.AA1.fun()
AA1.fun()
AA1.fun()
To avoid this ambiguity you have to explicitly put the whole package, subpackage and module path.
A.AA.AA1.fun()
B.AA.AA1.fun()
If you want to avoid having to use the whole path every time, you have the from option:
from A.AA.AA1 import fun
fun()
But, by doing this, the name of the identifier fun is exposed. Therefore, if fun was already assigned to another object previously, it is overridden and now points to the new object in A.AA.AA1.
fun = lambda x: 2*x
from A.AA.AA1 import fun
from B.AA.AA1 import fun
In this last example, after executing these lines of code, fun refers only to the object in module B.AA.AA1.
You can also use the as option to create an alias to the imported module:
import A.AA.AA1 as AAA1
import B.AA.AA1 as BAA1
AAA1.fun()
BAA1.fun()
This way the whole path is abbreviated and avoids ambiguity when executing fun from one module or another.
In this link you can find the documentation: import doc

The main difference is in how import works, please refer to the docs section 5.4.2 for more information. As an example:
import A.AA.AA1
A.AA.AA1.AA1fun()
With as sole import you will have to provide the complete path. On the other hand, if you use a from statement you can use it directly:
from A.AA import AA1
AA1.AA1fun()

Related

ImportError attempted relative import with no known parent

Based on some answers I try to be more specific.
I want to import the print and the models AND code in my main.py
I know the question gets asked a lot, but still I could not figure out whats wrong with my code!
I have a project directory like this
-project
--__init__py
--main.py
--print.py
--requests
--__init__.py
--models.py
--code.py
i want to import from print.py and * from requests
Therefore I tried to add these lines in main.py
from . import print
#or
import print
#for requests I tried
import os.path
import sys
sys.path.append('./requests')
from requests import *
all of those lines cause the same ImportError attempted relative import with no known parent ,
using Python 39
anyone an idea where the problem is?
I am very confused that this seems not to work, was it possible in older versions?
You should definitely not be doing anything with sys.path. If you are using a correct Python package structure, the import system should handle everything like this.
From the directory structure you described, project would be the name of your package. So when using your package in some external code you would do
import package
or to use a submodule/subpackage
import project.print
import project.requests
and so on.
For modules inside the package you can use relative imports. When you write
i want to import from print.py and * from requests Therefore I tried
it's not clear from where you want to import them, because this is important for relative imports.
For example, in project/main.py to import the print module you could use:
from . import print
But if it's from project/requests/code.py you would use
from .. import print
As an aside, "print" is probably not a good name for a module, since if you import the print module it will shadow the print() built-in function.
Your main file should be outside the 'project'-directory to use that as a package.
Then, from your main file, you can import using from project.print import ....
Within the project-package, relative imports are possible.

Cannot import function from another file

I have a file called hotel_helper.py from which I want to import a function called demo1, but I am unable to import it.
My hotel_helper.py file:
def demo1():
print('\n\n trying to import this function ')
My other file:
from hotel.helpers.hotel_helper import demo1
demo1()
but I get:
ImportError: cannot import name 'demo1' from 'hotel.helpers.hotel_helper'
When I import using from hotel.helpers.hotel_helper import * instead of from hotel.helpers.hotel_helper import demo1 it works and the function gets called. I tried importing the whole file with from hotel.helpers import hotel_helper and then call the function with hotel_helper.demo1() and it works fine. I don't understand what's wrong in first method. I want to directly import function rather using * or importing the whole file.
If you filename is hotel_helper.py you have to options how to import demo1:
You can import the whole module hotel_helper as and then call your func:
import hotel_helper as hh
hh.demo1()
You can import only function demo1 from module as:
from hote_helpers import demo1
demo1()
From your fileName import your function
from hotel.helpers import demo1
demo1()
You can import a py file with the following statement:
# Other import
import os
import sys
if './hotel' not in sys.path:
sys.path.insert(0, './hotel')
from hotel import *
NOTE:
For IDE like PyCharm, you can specify the import path using the Project Structure setting tab (CTRL+ALT+S)
Helpful stack overflow questions [maybe off topic]:
What is the right way to create project structure in pycharm?
Manage import with PyCharm documentation:
https://www.jetbrains.com/help/pycharm/configuring-project-structure.html
This is probably a duplicate of: https://stackoverflow.com/posts/57944151/edit
I created two files (defdemo.py and rundefdemo.py) from your posted 2 files and substituted 'defdemo' for 'hotel.helpers.hotel_helper' in the code. My 2 files are in my script directory for Python 3.7 on windows 10 and my script directory is in the python path file python37._pth. It worked.
defdemo.py
def demo1():
print('\n\n trying to import this function ')
rundefdemo.py
from defdemo import demo1
demo1()
output
trying to import this function
I was able to solve the issue, it was related to some imports I was making in my file, when I removed all the import statement in my hotel_helper.py ,the code started working as expected , Still I don't understand reason why the issue was occurring. anyway it works.
This ImportError can also arise when the function being imported is already defined somewhere else in the main script (i.e. calling script) or notebook, or when it is defined in a separate dependency (i.e. another module). This happens most often during development, when the developer forgets to comment out or delete the function definition in the body of a main file or nb after moving it to a module.
Make sure there are no other versions of the function in your development environment and dependencies.

How to do "from x.y.z import a" when "z" is a Python keyword?

I ran into the unfortunate case where a particular file has the filename that is a keyword in Python. Is there some way to "bypass" this without renaming the file?
libraries/import.py has a function my_function()
from libraries.import import my_function
Gives:
E999 - SyntaxError: invalid syntax
and points at the ".import" part
I tried a few things:
from "libraries.import" import my_function
from libraries."import" import my_function
from libraries import import.my_function
from repr(libraries.import) import my_function
from `libraries.import` import my_function # deprecated
import libraries.import.my_function
But they all have the same result: SyntaxError.
Can't find any tips in the Python manual either - but also no warnings about using reserved names :) Is this possible to do? How?
You should really just reconsider renaming your submodules, not only do you need to resort to importlib in order to get it but, you'll also be confusing people.
To import you could just use import_module from importlib, that is:
from importlib import import_module
m = import_module('libraries.import')
If you'd also want to bind the function to the global scope:
globals()['my_function'] = import_module('libraries.import').my_function
but you can see how ugly this is getting.
All alternatives you tried are either not allowed directly by the grammar (i.e import "libraries.import" or import libraries."import") or they get rejected during the parsing phase were it is detected that one of Pythons keywords is used.

Python : 'import module' vs 'import module as'

Is there any differences among the following two statements?
import os
import os as os
If so, which one is more preferred?
It is just used for simplification,like say
import random
print random.randint(1,100)
is same as:
import random as r
print r.randint(1,100)
So you can use r instead of random everytime.
The below syntax will help you in understanding the usage of using "as" keyword while importing modules
import NAMES as RENAME from MODULE searching HOW
Using this helps developer to make use of user specific name for imported modules.
Example:
import random
print random.randint(1,100)
Now I would like to introduce user specific module name for random module thus
I can rewrite the above code as
import random as myrand
print myrand.randint(1,100)
Now coming to your question; Which one is preferred?
The answer is your choice; There will be no performance impact on using "as" as part of importing modules.
Is there any differences among the following two statements?
No.
If so, which one is more preferred?
The first one (import os), because the second one does the exact same thing but is longer and repeats itself for no reason.
If you want to use name f for imported module foo, use
import foo as f
# other examples
import numpy as np
import pandas as pd
In your case, use import os
The import .... as syntax was designed to limit errors.
This syntax allows us to give a name of our choice to the package or module we are importing—theoretically this could lead to name clashes, but in practice the as syntax is used to avoid them.
Renaming is particularly useful when experimenting with different implementations of a module.
Example: if we had two modules ModA and ModB that had the same API we could write import ModA as MyMod in a program, and later on switch to using import MoB as MyMod.
In answering your question, there is no preferred syntax. It is all up to you to decide.

importing modules from packages in python, such a basic issue I guess I can't even find the answer anyhwere

So my first python program, I downloaded the macholib package from PYPI, then unzipped it and ran installed the setup.py using python install, now I'm trying to run a program where I first import the macholib, then when I try to access methods like Macho, it gives me an error saying macholib module has no attributes called Macho.
My understanding is macholib is a package and not a module or something, hence I cant use the contents of the package.
Please answer, I've wasted too much time on such a simple newbie issue.
running a mac with the latest version of python.
Code:
import sys
import macholib
MachO(DivXInstaller.dmg)
I tried macholib.MachO(DivXInstaller.dmg) and macholib.MachO.MachO(DivXInstaller.dmg)
Error for python test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
MachO(DivXInstaller.dmg)
NameError: name 'MachO' is not defined
You have this line in your code:
MachO(DivXInstaller.dmg)
However, the name MachO is not defined anywhere. So Python tells you this with the error
NameError: name 'MachO' is not defined
If you want to use the MachO module under the name MachO, you have to import it:
from macholib import MachO
This you have not done, which is the cause of your error. All you did was
import macholib
which gives you the name "macholib" that you can use. However, macholib contains mostly submodules which you can not access like that, so that is not particularly useful. If you don't want to pollute the namespace, you can import MachO as
import machlibo.MachO
Which gives you access to the MachO module as macholib.MachO
You haven't defined DivXInstaller.dmg either, so that's going to be your next error. I recommend that you go through a Python tutorial before you start programming in it.
An import statement defines a namespace. Hence, in order to use something defined in the module or package, you need to qualify it. In this case, the module itself is macholib.MachO but you need to dig deeper, to the actual class MachO which, slightly confusingly, has the same name, so you need to import macholib.MachO and use macholib.MachO.MachO (note that when I try to do this I get an error "DistributionNotFound: altgraph", however).
Note further that it takes a filename as an argument, which is a string. Moreover, you are actually creating an instance of a class, so you probably mean
mlib = macholib.MachO.MachO("DivXInstaller.dmg")
where now mlib is actually the object you need to manipulate with further calls...
Alternately you can do from macholib import MachO or even from macholib.MachO import MachO so you could use MachO.MachO(...) or MachO(...) directly.
This is so simple if you understand Python Packages vs. Modules and import vs. from import:
A Python module is simply a Python source file.
A Python package is simply a directory of Python module(s).
1- import:
import package1.package2.module1
To access module1 classes, functions or variables you should use the whole namespace: package1.package2.modlue1.class1
You cannot import a class or function this way: (wrong)
import package1.package2.class1
2- from ... import
Instead use "from" to import a single class, function or variable of a module:
from package1.package2.module1 import class1
no need to address the whole namespace: class1.method1() works now
Note that you cannot import a method of a class this way
Example:
datetime is a class of module datetime that has a method called utcnow(), to access utcnow() one could:
import datetime
datetime.datetime.utcnow()
Or
from datetime import datetime
datetime.utcnow()

Categories

Resources