Тёмный

Absolute and Relative imports - Python Tutorial 28 

Automation Zone
Подписаться 6 тыс.
Просмотров 35 тыс.
50% 1

Опубликовано:

 

27 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 73   
@spoilka666
@spoilka666 2 года назад
Dude you are the best, i've searched far and wide and you are the only one who provided a good explanation
@cerkal726
@cerkal726 5 месяцев назад
For someone coming from node to python multilevel import was so confusing and this made it so simple and clear
@LeveragedAlpha
@LeveragedAlpha Месяц назад
This has been a very helpful explanation of absolute and relative imports. If init files are not required for python > 3.3, why is it still so widely used? EDIT: Just saw the next video and it answered my question
@songhaoli304
@songhaoli304 3 года назад
from package1 import file2 raise Exception ModuleNotFoundError: No module named 'package1'
@MC-vw5le
@MC-vw5le 5 месяцев назад
add these lines at the top: curr_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(curr_dir) I think OP set this somewhere in his environment or the pycharm IDE.
@henryalohfabian6686
@henryalohfabian6686 2 месяца назад
​​@MC-vw5le pls why do you do this , I am facing the same issue and dont know what to do
@novaria
@novaria 3 года назад
Note to self: Just don't use relative imports. Absolute imports are always defined from the root source folder.
@flippantfishtaco3132
@flippantfishtaco3132 2 года назад
What constitutes the "root source folder"? How do we know which folder is the root source?
@AlvaroALorite
@AlvaroALorite Год назад
@@flippantfishtaco3132 The root folder he refers to I think he me as "Current Working Directory". import os cwd = os.getcwd(__file__) print(cwd) That tells you the current one. PS: it's not recommended Co change this at runtime. That's why relative imports are important.
@Steamxys
@Steamxys 3 года назад
Thanks for the good quality and the clear explanation
@MrKracx
@MrKracx 4 года назад
This is possibly the best video that explains pythons tricky import situations. I don't normally comment, but thank you so much for this
@Automationzone
@Automationzone 4 года назад
Thank you !!
@ryanmeoni1483
@ryanmeoni1483 4 года назад
Absolutely agree.
@lepptin
@lepptin 3 года назад
I agree too
@Sethsm1
@Sethsm1 3 года назад
Agreed. I was so confused, this makes it crystal clear.
@trishandas4500
@trishandas4500 3 года назад
thank you so much....i was not understanding this for a long time......
@VamsiKrishna-yt5hi
@VamsiKrishna-yt5hi 3 года назад
I really want to thank you for making this topic clear for all
@paul_devos
@paul_devos 2 года назад
how do you get any import to work like that? Is this special to PyCharm editor? I'm using VSCode and neither relative imports nor absolute imports work like you have in this setup.
@Automationzone
@Automationzone 2 года назад
Interesting, can u email me ur code. @ theautomationzone@gmail.com I will try it myself on vscode and let u know exactly what is going on
@sureshraina321
@sureshraina321 5 месяцев назад
​@@Automationzone Hey same case with me In Vs Code the things are not working It would be very helpful
@sukanya4498
@sukanya4498 2 года назад
Very helpful! Thank you!
@lepptin
@lepptin 3 года назад
Thank you so much. The best explanation I've ever listen
@seeitall5644
@seeitall5644 Год назад
I have no hierarchy in the folder. All the files are just in a single folder. I am getting import error for pyttsx3 on from .engine import Engine. I am not sure what to do
@Automationzone
@Automationzone Год назад
Plz show me a screenshot of the folder structure
@thorhammer7153
@thorhammer7153 3 года назад
thanks really helps me
@flippantfishtaco3132
@flippantfishtaco3132 2 года назад
It would help if you told us how the root directory is determined. Is it simply whichever directory contains the entrypoint file? If so, then this means that the import paths in the module files are determined by whichever file my module files are being imported by (meaning the root file). IOW, if there's more than one root file, the import paths won't work for both root files. This would happen if you have a file for unit tests that's not in the same directory as the root file. If you have a large project with various modules, this could realistically happen. What do we do then?
@Automationzone
@Automationzone 2 года назад
This is something i did not think about, i wanted to keep it simple. But u do have a valid point here. I will make a new videos in which i will discuss only on relative path with various scenarios as u just mentioned. Also i will try using vscode in order to make the code execution as vanilla as possible.
@franciscobarrot9145
@franciscobarrot9145 2 года назад
Great video man!
@ruhaitian7761
@ruhaitian7761 2 года назад
why there are underscores between file and number e.g. file_2?
@wyldcard00
@wyldcard00 2 года назад
it s just a python convention
@engulfing_marubozu
@engulfing_marubozu 3 года назад
lifesaver man.. everything was so confusing before this video
@PepeTostado
@PepeTostado 4 года назад
What is the difference, which is better
@Automationzone
@Automationzone 4 года назад
i usually use relative if the file i am importing is from the same folder/package or sub folder/package. All imports from parent i usually do via absolute imports. Imports from parent is usually rare as i try to arrange the folder structure in a way to avoid this scenario. Other point to note is if your project has too many imports from parent and sibling folders and it is not possible for you to rearrange them, then it is better to dynamically add the project root folder into the system path and perform a absolute import from the root for all modules.
@freemanfreed1581
@freemanfreed1581 3 года назад
As long as python searches the home directory first why we need to have module relative imports? Aren't they similar to importing a file located in the same location as the importer file? The difference is files said to exist in a package
@jackqiu501
@jackqiu501 Год назад
I change my vscode setting that the cwd is always the running file, so all absolute import becomes relative. Don’t know it’s a best practice or not.
@Automationzone
@Automationzone Год назад
As a thumb rule, try to make a python file which can be executed without any editor. If that works u can execute it from anywhere u want to.
@saranzeb2183
@saranzeb2183 3 года назад
what if our root. File is in package1 or package2 and we have to import a module from another package ? is it possible because in my case when I am checking the root path the package1 or package2 depending upon where i open the file and not the parent project directory which is in yours's case
@xiaoweidu4667
@xiaoweidu4667 Год назад
good explanation!
@hariharanramamurthy9946
@hariharanramamurthy9946 3 года назад
how will you differentiate parent and sub folder sir
@Automationzone
@Automationzone 3 года назад
Could you help me understand the question more in detail. I would try to help you out
@andresespinoza2024
@andresespinoza2024 4 года назад
Hi. Thanks for the video. I got a question and I hope you can help me. I'm currently getting this error: "attempted relative import with no known parent package" The structure is like this: Arosics\ _init_.py CoReg.py DeShifter.py My current working directory is Arosics. I want to import a function called DESHIFTER that is defined inside DeShifter.py running the following line "from .DeShifter import DESHIFTER". But I keep getting the error mentioned above. Do you have any ideas what would the problem?
@Automationzone
@Automationzone 4 года назад
can u email me ur project in a zip file at theautomationzone@gmail.com. I will reply at the earliest.
@shreyasb.s3819
@shreyasb.s3819 3 года назад
Nice
@xkolm49
@xkolm49 4 года назад
How does python know what's the root directory? Why isnt the import e.g. from tutorial_25.package1 import file2?
@Automationzone
@Automationzone 4 года назад
There are two parts to this question. 1. If you are using an application like pycharm. i > in that case the root is where u have imported ur first folder in ur project explorer. So in my case all the folder tutorial_25 is my root. ii> also note that all the path variables can also be ur root. 2. If you are not using application like pycharm i > The place from where u have run ur python file is your root folder. ii> also note that all the path variables can also be ur root. Note :- Many programmers, programmatically add values path variable at run time to take care of this issue.
@clasesutnfrc8699
@clasesutnfrc8699 2 года назад
08:51 Relative imports | Error
@josephtucker9612
@josephtucker9612 3 года назад
I had a problem with imports when a module in the sub-package calls another module in the same sub-package. When I am developing I like to call modules from within the sub-package. In that case my imports would no longer work. I solved my problems by adding this code to __init__.py in the sub-package: import sys import os sys.path.append(os.path.split(__file__)[0]) Now all my imports work like they should.
@rhn122
@rhn122 4 года назад
Great video! However, I'm trying to import a module from the parent package, yet when I used the absolute import, my IDE (VSC) keeps mistaking my package for the module itself (ModuleNotFoundError), and also with the relative import I got ImportError. My folder looks like this (every package also has its own __init__.py) |- Folder |- parent_package |- sub_package |- main.py |- import_module.py I'm trying to import the import_module.py from main.py with this statement from parent_package import import_module Keeps getting the ModuleNotFoundError, keeps mistaking the Parent_Package for the module itself. Any ideas why? Error too with the relative import
@Automationzone
@Automationzone 4 года назад
Yes, i can understand your issues. U see in VS Code, you basically run the files from the command line, what i mean is ur running it as a standalone file and not as a project as it works in pycharm ( In pycharm we have two options, run via command line and normal execution ) So that that difference in mind let us look at ur folder structure. As per this the file which is run becomes ur root folder. So, 1. If ur start to executed file main.py in command line that ur root folder will be sub_package and anything outside ur package cannot be imported. [ u can add the folder in ur path if u need to import something outside ur project ] 2. What i recommend to do is, keep ur main.py file or ur main executable file in the top parent folder, i.e in the "Folder" and it should work file.
@rhn122
@rhn122 4 года назад
@@Automationzone I see, but do you recommend to use sys.path.append instead. That's what I always use whenever I get this problem. It's just that so many people don't have the same problem as I do, also I'm using scrapy so I have to run the crawler from the command line, which is why I ask in the first place. Thank you!
@Automationzone
@Automationzone 4 года назад
In your situation, yes better to add the path at run time as you are currently doing. Ur approach is good as even if code is given to ur peers it will work on their machines as well. Other approaches are 1: change ur folder Structure so that there all others python files come in the root folder 2: place app the root folder in ur system path permanently. That u don't have to add it all the time. 3: place your python files in the python dir as this dir is by default in the path .
@shivaram8930
@shivaram8930 2 года назад
It seems u urself got confused in explaining this which inturn confused me ..
@Automationzone
@Automationzone 2 года назад
Reviews always helps... I guess I will have to make another video which is more clear. 👍
@ruifonseca6147
@ruifonseca6147 4 года назад
Thank you for your class, but whenever I try import something outside the current folder, it does not work.
@Automationzone
@Automationzone 4 года назад
The concept of root folder will come with you are working with an editor like pycharm. So if your editor does not create a project your basically running a standalone python file. in this case your root folder will be the location of that file. The location of the main file is the root folder if u are running ur program starting from MainFile.py So by placing ur file in the top dir your creating a root folder with includes all files. |---folder1 |---a1.py |---folder2 |---a2.py |---MainFile.py In the below case case the root folder is inside a sub folder and so if u are execution ur program in the below way, u cannot import the other file. becoz they do not belong to the project/root folder |---folder1 |---a1.py |---folder2 |---a2.py |---folder3 |---MainFile.py
@ruifonseca6147
@ruifonseca6147 4 года назад
Hello, Sorry for not knowing your name.First of all, I would like to thank you for putting available a class explaining how to create relative and absolute imports. In order to simulate the operations I have created a directory with subfolders and then I started to simulate what you teached. Unfortunately, I was only able to do absolute imports and even so from the root folder, as you can see on the picture below. I have zipped the code and it is attached to this e-mail. If you could write a code inside p1_code.ipynb file, importing the modules in pacote_2 and in pacote_3 , using relative and absolute imports and return me the code, I would appreciate it a lot. I am trying this hard, but I am not having any success. Thank you a lot. Below you can see my folder structure Treinamento/ __init__.py código principal.ipynb /pacote_1 __init__.py p1_code.ipynb pi_modulo.py /subpacote1 __init__.py p1s1_code.ipynb p1s1_modulo.py /pacote_2 __init__.py p2_code.ipynb p2_modulo.py /subpacote2 __init__.py p2s2_code.ipynb p2s2_modulo.py /pacote_3 __init__.py p3_code.ipynb p3_modulo.py /subpacote1 __init__.py p3s3_code.ipynb p3s3_modulo.py
@Automationzone
@Automationzone 4 года назад
Very important question which editor are u using ? Is it pycharm or something else. I will go through your email and reply at the earliest.
@ruifonseca6147
@ruifonseca6147 4 года назад
@@Automationzone Hello, It is Jupyter notebook
@Automationzone
@Automationzone 4 года назад
Hi, so the answer to ur query is that there are two way to execute a python file. 1. Withing an editor : can be done in pycharm 2. As a command line : this can be done with almost all editors. If your using a command line to execute, that u have to not that the file ur execution will be ur root folder. So in ur folder structure is like this ParentFolder > SubFolder > SubSubFolder. If you place ur main executor python file in parent folder , they u can access all folders. as they are in your project. If you place your main executor file in the SubFolder, they u can only access what is in SubFolder and SubSubFolder So it's if ur creating a project which has to be run in command line, place ur main executor file in the root folder and link all other files to that main file or Place the project folder in ur system path that will work as well.
@TheShelar
@TheShelar 4 года назад
👍🏻
@out_aloud
@out_aloud 3 года назад
Purrfectt....
@ruifonseca6147
@ruifonseca6147 4 года назад
I would really aprreciate your help if you could help me
@Automationzone
@Automationzone 4 года назад
Sure, zip your project and email it to me @ theautomationzone@gmail.com Also send me ur error and the editor which you are using. I will revert with a solution asap
@404nohandlefound
@404nohandlefound 4 года назад
man's confused during the video, good attempt nonetheless
@Automationzone
@Automationzone 4 года назад
I shal try my hardest to get the video's more clear going ahead...
@404nohandlefound
@404nohandlefound 4 года назад
@@Automationzone I expect nothing less
Далее
is __init__py file needed ? - Python Tutorial 29
6:26
Avoiding import loops in Python
10:21
Просмотров 94 тыс.
Python Decorators in 15 Minutes
15:14
Просмотров 448 тыс.
Reading Relative File Paths in Python
8:43
Просмотров 32 тыс.
5 Useful Dunder Methods In Python
16:10
Просмотров 62 тыс.
Learn Python OOP in under 20 Minutes
18:32
Просмотров 81 тыс.