Python import within and outside packageCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?How to get the current time in PythonHow to upgrade all Python packages with pip?Does Python have a string 'contains' substring method?How to import an SQL file using the command line in MySQL?

Testing using real data of the customer

How does the Earth's center produce heat?

What weight should be given to writers groups critiques?

Is there an idiom that means that you are in a very strong negotiation position in a negotiation?

Are cells guaranteed to get at least one mitochondrion when they divide?

Can we assume that a hash function with high collision resistance also means highly uniform distribution?

How to politely tell someone they did not hit reply all in email?

Is this homebrew "Cactus Grenade" cantrip balanced?

Does an eye for an eye mean monetary compensation?

What did the 'turbo' button actually do?

Cardio work for Muay Thai fighters

What would prevent living skin from being a good conductor for magic?

Can a ring of spell storing and access to Find spells produce an endless menagerie?

Why did it take so long for Germany to allow electric scooters / e-rollers on the roads?

Removing the last element of a list

What is the use case for non-breathable waterproof pants?

Why did Jon Snow admit his fault in S08E06?

What is the recommended procedure to land a taildragger in a crosswind?

Is there a simple example that empirical evidence is misleading?

How to keep consistency across the application architecture as a team grows?

The Maltese Falcon

Has Ursula Le Guin ever admitted to be influenced by Kibbutz for the Dispossessed?

Security vulnerabilities of POST over SSL

How was Daenerys able to legitimise Gendry?



Python import within and outside package


Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?How to get the current time in PythonHow to upgrade all Python packages with pip?Does Python have a string 'contains' substring method?How to import an SQL file using the command line in MySQL?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















This is my situation. I have the following directory structure:



$ls -R .:
driver.py package

./package:
dependent.py __init__.py standalone.py


driver.py:



#!/usr/bin/env python

from package.dependent import add_n

if __name__=='__main__':
print(add_n(2,2))


dependent.py:



#!/usr/bin/env python

from standalone import add_1

def add_n(x, n):
for _ in range(n):
x = add_1(x)
return x


standalone.py:



#!/usr/bin/env python

def add_1(x):
return x+1


Now depending on my use case, I want to run dependent.py directly or import it into driver.py. This is the problem I'm facing:



  • Running dependent.py only works if there is not a dot when importing add_1. If there is one, it throws the following error:

Traceback (most recent call last):
File "dependent.py", line 3, in <module>
from .standalone import add_1
ModuleNotFoundError: No module named '__main__.standalone'; '__main__' is not a package


  • Running package.py only works if there is a dot when importing add_1. If there is not one, it throws the following error:

Traceback (most recent call last):
File "driver.py", line 3, in <module>
from package.dependent import add_n
File "/home/su0/scratch/package/dependent.py", line 3, in <module>
from standalone import add_1
ModuleNotFoundError: No module named 'standalone'


I want both scenarios to work. This is because, in the real project, there are dependencies within the package that import other modules. And I want to be able to import it as a package as well. Any help is appreciated.



Thanks.










share|improve this question
























  • What is pwd in this case?

    – Joel Cornett
    Mar 24 at 0:02











  • I'm sorry I don't understand. It's just some directory (a directory in my home).

    – shaun
    Mar 24 at 2:15

















1















This is my situation. I have the following directory structure:



$ls -R .:
driver.py package

./package:
dependent.py __init__.py standalone.py


driver.py:



#!/usr/bin/env python

from package.dependent import add_n

if __name__=='__main__':
print(add_n(2,2))


dependent.py:



#!/usr/bin/env python

from standalone import add_1

def add_n(x, n):
for _ in range(n):
x = add_1(x)
return x


standalone.py:



#!/usr/bin/env python

def add_1(x):
return x+1


Now depending on my use case, I want to run dependent.py directly or import it into driver.py. This is the problem I'm facing:



  • Running dependent.py only works if there is not a dot when importing add_1. If there is one, it throws the following error:

Traceback (most recent call last):
File "dependent.py", line 3, in <module>
from .standalone import add_1
ModuleNotFoundError: No module named '__main__.standalone'; '__main__' is not a package


  • Running package.py only works if there is a dot when importing add_1. If there is not one, it throws the following error:

Traceback (most recent call last):
File "driver.py", line 3, in <module>
from package.dependent import add_n
File "/home/su0/scratch/package/dependent.py", line 3, in <module>
from standalone import add_1
ModuleNotFoundError: No module named 'standalone'


I want both scenarios to work. This is because, in the real project, there are dependencies within the package that import other modules. And I want to be able to import it as a package as well. Any help is appreciated.



Thanks.










share|improve this question
























  • What is pwd in this case?

    – Joel Cornett
    Mar 24 at 0:02











  • I'm sorry I don't understand. It's just some directory (a directory in my home).

    – shaun
    Mar 24 at 2:15













1












1








1








This is my situation. I have the following directory structure:



$ls -R .:
driver.py package

./package:
dependent.py __init__.py standalone.py


driver.py:



#!/usr/bin/env python

from package.dependent import add_n

if __name__=='__main__':
print(add_n(2,2))


dependent.py:



#!/usr/bin/env python

from standalone import add_1

def add_n(x, n):
for _ in range(n):
x = add_1(x)
return x


standalone.py:



#!/usr/bin/env python

def add_1(x):
return x+1


Now depending on my use case, I want to run dependent.py directly or import it into driver.py. This is the problem I'm facing:



  • Running dependent.py only works if there is not a dot when importing add_1. If there is one, it throws the following error:

Traceback (most recent call last):
File "dependent.py", line 3, in <module>
from .standalone import add_1
ModuleNotFoundError: No module named '__main__.standalone'; '__main__' is not a package


  • Running package.py only works if there is a dot when importing add_1. If there is not one, it throws the following error:

Traceback (most recent call last):
File "driver.py", line 3, in <module>
from package.dependent import add_n
File "/home/su0/scratch/package/dependent.py", line 3, in <module>
from standalone import add_1
ModuleNotFoundError: No module named 'standalone'


I want both scenarios to work. This is because, in the real project, there are dependencies within the package that import other modules. And I want to be able to import it as a package as well. Any help is appreciated.



Thanks.










share|improve this question
















This is my situation. I have the following directory structure:



$ls -R .:
driver.py package

./package:
dependent.py __init__.py standalone.py


driver.py:



#!/usr/bin/env python

from package.dependent import add_n

if __name__=='__main__':
print(add_n(2,2))


dependent.py:



#!/usr/bin/env python

from standalone import add_1

def add_n(x, n):
for _ in range(n):
x = add_1(x)
return x


standalone.py:



#!/usr/bin/env python

def add_1(x):
return x+1


Now depending on my use case, I want to run dependent.py directly or import it into driver.py. This is the problem I'm facing:



  • Running dependent.py only works if there is not a dot when importing add_1. If there is one, it throws the following error:

Traceback (most recent call last):
File "dependent.py", line 3, in <module>
from .standalone import add_1
ModuleNotFoundError: No module named '__main__.standalone'; '__main__' is not a package


  • Running package.py only works if there is a dot when importing add_1. If there is not one, it throws the following error:

Traceback (most recent call last):
File "driver.py", line 3, in <module>
from package.dependent import add_n
File "/home/su0/scratch/package/dependent.py", line 3, in <module>
from standalone import add_1
ModuleNotFoundError: No module named 'standalone'


I want both scenarios to work. This is because, in the real project, there are dependencies within the package that import other modules. And I want to be able to import it as a package as well. Any help is appreciated.



Thanks.







python python-3.x import






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 23:51









Aran-Fey

20.8k54180




20.8k54180










asked Mar 23 at 23:30









shaunshaun

140419




140419












  • What is pwd in this case?

    – Joel Cornett
    Mar 24 at 0:02











  • I'm sorry I don't understand. It's just some directory (a directory in my home).

    – shaun
    Mar 24 at 2:15

















  • What is pwd in this case?

    – Joel Cornett
    Mar 24 at 0:02











  • I'm sorry I don't understand. It's just some directory (a directory in my home).

    – shaun
    Mar 24 at 2:15
















What is pwd in this case?

– Joel Cornett
Mar 24 at 0:02





What is pwd in this case?

– Joel Cornett
Mar 24 at 0:02













I'm sorry I don't understand. It's just some directory (a directory in my home).

– shaun
Mar 24 at 2:15





I'm sorry I don't understand. It's just some directory (a directory in my home).

– shaun
Mar 24 at 2:15












1 Answer
1






active

oldest

votes


















0














The best would be to really package the code and then use absolute imports in dependent.py. As a workaround you can however use one of the following options:



Extend the path in driver.py



Before the import package.dependent you can add the following lines:



import sys
sys.path.append('package')


Then use the undotted import statement in dependent.py. This works since now package is on the path to be searched for modules, including standalone.py.



Use conditional imports in dependent.py



You can modify the imports in dependent.py as follows:



if __name__ == '__main__':
from standalone import ...
else:
from .standalone import ...





share|improve this answer























  • Does the conditional import go at the very top to replace the original import statement?

    – shaun
    Mar 24 at 2:18











  • Yes it needs to replace the original one. It can go anywhere but obviously has to be executed before you attempt to use the imported function. Anyway I'd rather use option 1 (package the code) or option 2 (extending sys.path); option 3 (conditional import) implies that dependent.py "knows" that it's going to be imported somewhere else, but then you could just put the code in a separate module anyway.

    – a_guest
    Mar 24 at 11:42












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55319336%2fpython-import-within-and-outside-package%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














The best would be to really package the code and then use absolute imports in dependent.py. As a workaround you can however use one of the following options:



Extend the path in driver.py



Before the import package.dependent you can add the following lines:



import sys
sys.path.append('package')


Then use the undotted import statement in dependent.py. This works since now package is on the path to be searched for modules, including standalone.py.



Use conditional imports in dependent.py



You can modify the imports in dependent.py as follows:



if __name__ == '__main__':
from standalone import ...
else:
from .standalone import ...





share|improve this answer























  • Does the conditional import go at the very top to replace the original import statement?

    – shaun
    Mar 24 at 2:18











  • Yes it needs to replace the original one. It can go anywhere but obviously has to be executed before you attempt to use the imported function. Anyway I'd rather use option 1 (package the code) or option 2 (extending sys.path); option 3 (conditional import) implies that dependent.py "knows" that it's going to be imported somewhere else, but then you could just put the code in a separate module anyway.

    – a_guest
    Mar 24 at 11:42
















0














The best would be to really package the code and then use absolute imports in dependent.py. As a workaround you can however use one of the following options:



Extend the path in driver.py



Before the import package.dependent you can add the following lines:



import sys
sys.path.append('package')


Then use the undotted import statement in dependent.py. This works since now package is on the path to be searched for modules, including standalone.py.



Use conditional imports in dependent.py



You can modify the imports in dependent.py as follows:



if __name__ == '__main__':
from standalone import ...
else:
from .standalone import ...





share|improve this answer























  • Does the conditional import go at the very top to replace the original import statement?

    – shaun
    Mar 24 at 2:18











  • Yes it needs to replace the original one. It can go anywhere but obviously has to be executed before you attempt to use the imported function. Anyway I'd rather use option 1 (package the code) or option 2 (extending sys.path); option 3 (conditional import) implies that dependent.py "knows" that it's going to be imported somewhere else, but then you could just put the code in a separate module anyway.

    – a_guest
    Mar 24 at 11:42














0












0








0







The best would be to really package the code and then use absolute imports in dependent.py. As a workaround you can however use one of the following options:



Extend the path in driver.py



Before the import package.dependent you can add the following lines:



import sys
sys.path.append('package')


Then use the undotted import statement in dependent.py. This works since now package is on the path to be searched for modules, including standalone.py.



Use conditional imports in dependent.py



You can modify the imports in dependent.py as follows:



if __name__ == '__main__':
from standalone import ...
else:
from .standalone import ...





share|improve this answer













The best would be to really package the code and then use absolute imports in dependent.py. As a workaround you can however use one of the following options:



Extend the path in driver.py



Before the import package.dependent you can add the following lines:



import sys
sys.path.append('package')


Then use the undotted import statement in dependent.py. This works since now package is on the path to be searched for modules, including standalone.py.



Use conditional imports in dependent.py



You can modify the imports in dependent.py as follows:



if __name__ == '__main__':
from standalone import ...
else:
from .standalone import ...






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 23 at 23:58









a_guesta_guest

7,77831446




7,77831446












  • Does the conditional import go at the very top to replace the original import statement?

    – shaun
    Mar 24 at 2:18











  • Yes it needs to replace the original one. It can go anywhere but obviously has to be executed before you attempt to use the imported function. Anyway I'd rather use option 1 (package the code) or option 2 (extending sys.path); option 3 (conditional import) implies that dependent.py "knows" that it's going to be imported somewhere else, but then you could just put the code in a separate module anyway.

    – a_guest
    Mar 24 at 11:42


















  • Does the conditional import go at the very top to replace the original import statement?

    – shaun
    Mar 24 at 2:18











  • Yes it needs to replace the original one. It can go anywhere but obviously has to be executed before you attempt to use the imported function. Anyway I'd rather use option 1 (package the code) or option 2 (extending sys.path); option 3 (conditional import) implies that dependent.py "knows" that it's going to be imported somewhere else, but then you could just put the code in a separate module anyway.

    – a_guest
    Mar 24 at 11:42

















Does the conditional import go at the very top to replace the original import statement?

– shaun
Mar 24 at 2:18





Does the conditional import go at the very top to replace the original import statement?

– shaun
Mar 24 at 2:18













Yes it needs to replace the original one. It can go anywhere but obviously has to be executed before you attempt to use the imported function. Anyway I'd rather use option 1 (package the code) or option 2 (extending sys.path); option 3 (conditional import) implies that dependent.py "knows" that it's going to be imported somewhere else, but then you could just put the code in a separate module anyway.

– a_guest
Mar 24 at 11:42






Yes it needs to replace the original one. It can go anywhere but obviously has to be executed before you attempt to use the imported function. Anyway I'd rather use option 1 (package the code) or option 2 (extending sys.path); option 3 (conditional import) implies that dependent.py "knows" that it's going to be imported somewhere else, but then you could just put the code in a separate module anyway.

– a_guest
Mar 24 at 11:42




















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55319336%2fpython-import-within-and-outside-package%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현