Python and Pytest wants module in different folder


#1

Hello.

I have a problem where to put a module (lexicon.py for ex 49).

My tree looks like this:

lessons/
ex48/ (finished)
ex49/                          (1)
    exercise49/parser.py, __init__.py(2)
    tests/test_parser.py, __init__.py
    venv/
    bin/
    docs/
ex50/ (to do)

If I put lexicon.py in folder ex49 (1) my test_parser.py works fine but not parser.py
If I put lexicon.py in folder exercise49 (2) parser.py works fine but not my test_parser.py
I have tried as many combinations I can imagine.

I have put “import lexicon” or “from exericse49 import lexicon” depending where lexicon are at that moment.

It works if I have a copy of lexicon in each folder.
But that would be a maintainers night mare I guess.

Is there a “way to do” this I just cannot see?
Or another workaround?

I have a init.py in both exercise and tests folder. (edit 4 november).


#2

I had a similar issue and placed everything in the ex48 folder structure.

47

You don’t seem to have a setup?

from src import parser, lexicon                                                 
from src.parser import * 

And running pytest at ex48 root:


#3

Hi @gpkesley.
Thanks for replying.

At last I got it working.
First I tried to set up my structure exactly as your. Still did not work.
Then I looked through all files to see if there was any problems with the import. I found that the import in parser.py wasn’t correct.
I had just

import lexicon

I changed it to

from ex48 import lexicon

That was a part of the problem

I copied lexicon from ex48 when started ex49.
I then called it lexicon2.py to more easily separate them. Now I decided to take it away
This “2” haunted me for a while. I found it everywhere.
When I have corrected all of these things it started to work again.

I do have a setup.py file.
However I do not know much about it. I have made a copy since ex46.
Reading now and then about how to use it.
Someone wrote even Guido van Rossum think it is a little bit tricky.
I seems to be in good company :slight_smile:

When do I have use for it?
I will problably never do this for a living.
Python is a hobby for me. A way to have some brain exericise.
Will probably write code for my self or to give to a friend or family.
Is it for when creating a distribution?
Or can it be used in other ways?


#4

I’m probably the same as you in that respect. But found this to be an interesting perspective around venvs and Django.


#5

Hi @gpkesley.

Thanks for the link.
I will try out this soon. I have sidetracks (too many perhaps) I sometimes try out. Often they are related to the book (LPTHW3). When I am back again things use to be easier to understand.
This is a sidetrack. Nevertheless very interesting.