Repository navigation
Code-Runner run module instead of run python file #17180
Description
Discussed in #16651
Originally posted by jwang1122 July 11, 2021
A lots of people discuss unit test path issue online. If one module import another module, it works on code runner, but unit test could NOT find it. if you make the unit test find it, and code runner no longer works. It is because the code runner run python file directly. Is it possible change the code runner from
python $filename
to
python -m mypackage.$filename-without-py-extension
This way will make both unit test and code runner work same time. So developer can organize their file in different folder easily.
here is an example:
from .card import Card # use this line for unit test
# from card import Card # use this line for product
class BlackjackCard(Card):
def getValue(self):
switch = {"A":11,"J":10,"Q":10,"K":10}
if self.face.isdigit():
return int(self.face)
return switch.get(self.face)
if __name__ == '__main__':
heartsQ = BlackjackCard('Q', 'HEARTS')
print(heartsQ)
print(heartsQ.getValue())as you can see, the first line use python relative path, so unit test can find module card. but if you run this module locally
PS C:\Users\John\workspace\python-I> & c:/Users/John/workspace/python-I/env/Scripts/python.exe c:/Users/John/workspace/python-I/src/blackjack/blackjackcard.py
Traceback (most recent call last):
File "c:/Users/John/workspace/python-I/src/blackjack/blackjackcard.py", line 1, in <module>
from .card import Card # use this line for unit test
ImportError: attempted relative import with no known parent package
PS C:\Users\John\workspace\python-I>
We get ImportError. But if we can change code runner run the following command
PS C:\Users\John\workspace\python-I> python -m src.blackjack.blackjackcard
(Q, HEARTS)
10
PS C:\Users\John\workspace\python-I>
Obviously, it works.
The hard part for this is,
❓How to determine the package path? But I don't think it is something very hard to do.
✔️😄We know current folder, we know the file path, simply remove current folder from the path, change all '/' to '.' and then remove the file extension.
Don't you think this is a good idea?
Activity
brettcannon commentedon Sep 1, 2021
Thanks for the feature request! We are going to give the community 60 days from when this issue was created to provide 5 👍 upvotes on the opening comment to gauge general interest in this idea. If there's enough upvotes then we will consider this feature request in our future planning. If there's unfortunately not enough upvotes then we will close this issue.
brettcannon commentedon Nov 1, 2021
Thank you for submitting your feature request and everyone who considered it! Unfortunately this issue did not receive enough votes over the allotted time, and so we are closing the issue.