what does forward slash do in this django settings.py python list?

Viewed 376

I'm new to python and I don't understand how this forward slash works in the django settings.py

STATICFILES_DIRS = [
    BASE_DIR / "static",
]

It seems like it is concatenating the value of BASE_DIR + "static", but that would actually be str(BASE_DIR) + "static" correct?

Is it a special Django delimiter of sometype?

This is the correct usage according to the Django documentation: https://docs.djangoproject.com/en/3.1/howto/static-files/#configuring-static-files

STATICFILES_DIRS Is not a parameter list - so this doesn't seem to apply https://docs.python.org/3/faq/programming.html#what-does-the-slash-in-the-parameter-list-of-a-function-mean

It's not a binary division operator: https://docs.python.org/3/reference/expressions.html#binary

2 Answers

Probably BASE_DIR is a pathlib.Path object. The / is the path component concatenation operator.

>>> from pathlib import Path
>>> BASE_DIR = Path('/tmp')
>>> BASE_DIR / 'foo' / 'bar'
PosixPath('/tmp/foo/bar')
>>> str(BASE_DIR / 'foo' / 'bar')
'/tmp/foo/bar'

By default BASE_DIR would be set from Django 3.1 to (source):

BASE_DIR = Path(__file__).resolve().parent.parent

/ does the same as os.path.join() ( pathlib is new module introduced in python 3.4) as documented

The slash operator helps create child paths, similarly to os.path.join()

For example

BASE_DIR = Path('/base')
print(BASE_DIR / 'static')

would result in /base/static

Related