quantifiedcode / python-anti-patterns

An open collection of Python anti-patterns and worst practices.
https://quantifiedcode.github.io/python-anti-patterns
Other
1.71k stars 249 forks source link

Correctness: Not using forward slashes #54

Open smotes opened 9 years ago

smotes commented 9 years ago

The best practice suggests using forward slashes, even while on Windows. An even better practice would be to use the build in os module to join paths together. This technique is also OS independent since it knows to use the correct directory separator. Furthermore, it's a part of the Python standard library and Django even sets up a BASE_DIR variable in your settings automatically when creating a project.

In your settings.py:

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
    # etc...
]
lanshark commented 9 years ago

I might point out that even your 'best practices' window uses backslashes in the example (cut/paste problem?) instead of the correct forward slashes...

jcdyer commented 9 years ago

And furthermore, the anti-pattern doesn't escape the backslashes or use a raw string, which means that the actual string object doesn't have backslashes in it.

programmdesign commented 9 years ago

@smotes: good point. The original idea for this pattern came from a comment in the Django docs: https://docs.djangoproject.com/en/1.8/ref/settings/#staticfiles-dirs. In their example, they seem not to have a base dir, unless you consider "/" the base dir.

@lanshark: thanks. cut/paste problem indeed, fixed @jcdyer: valid point too, fixed