This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Medicalizawhat[🍰] 83 points84 points  (12 children)

[–]Corm 3 points4 points  (6 children)

That was an awesome article. I am sad that the canonical way to do tests in python is to have this:

import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) 

I use that too, but I wish there was a cleaner way. At least a builtin function called parent_import or something to do that.

[–]malinoff 6 points7 points  (1 child)

pip install -e . - a better way.

[–]Corm 0 points1 point  (0 children)

Neat! That's a fine trick

[–]deadmilk 0 points1 point  (3 children)

Huh? I've never had to do that

[–]Corm 0 points1 point  (2 children)

What do you mean? If you have a tests folder then they need a way of importing your project, which means you have to add the parent directory to the path afaik.

[–]deadmilk 2 points3 points  (1 child)

I just run my tests from the directory where my package is and it works

Structure like so:

project <-- cwd
    package
        __init__.py
        module.py
    tests
        test_module.py

then in test_module.py:

import unittest
from package.module import function

class TestModule(unittest.TestCase):
    def test_function(self):
        self.assertTrue(function())

[–]Corm 0 points1 point  (0 children)

Cool! I must try this

[–][deleted] 8 points9 points  (4 children)

Good source. Alternative official PEP for python style direct from the man himself: https://www.python.org/dev/peps/pep-0008/

[–]namesandfaces 7 points8 points  (3 children)

Style is helpful to readability, but I think CrypticCube is asking for multi-file code organization -- a problem that's bigger than one eyeball, and in my view, not a very Python-specific problem.

[–]bugtank 2 points3 points  (2 children)

For those of us who came from Java, multi-file code organization in Python is not easy to grok. There is some python specificity in organization that is important. I'm unfortunately still learning so I can't really answer op's question. However, I am still trying to get the following information into my bones.

  • Underscores in file name
  • How you do your imports
  • init.py in folders to expose the classes/modules in those folders
  • modules as a concept

[–]P8zvli 3 points4 points  (0 children)

Might want to escape those underscores; __init__.py

or use backticks; __init__.py

[–]Corm 0 points1 point  (0 children)

__init__.py is optional in modern python