I found sometimes forward slash "/" is used to concatenate "BASE_DIR" and "static" or "media" for "STATIC_ROOT" and "MEDIA_ROOT" in "settings.py" as shown below:
# "settings.py"
# Here
STATIC_ROOT = BASE_DIR / 'static'
# Here
MEDIA_ROOT = BASE_DIR / 'media'
So, it's possible to concatenate BASE_DIR which is 'PosixPath' type and 'static' which is 'str' type with forward slash "/".
But when I tried to concatenate 'str' type and 'str' type with "/":
# "settings.py"
STATIC_ROOT = 'abc' / 'static'
I got this error below:
TypeError: unsupported operand type(s) for /: 'str' and 'str'
And for 'int' type and 'str' type with "/":
STATIC_ROOT = 123 / 'static'
I got this error below:
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Then for 'MyClass' type and 'str' type with "/":
# "settings.py"
class MyClass:
pass
STATIC_ROOT = MyClass() / 'static'
I got this error below:
TypeError: unsupported operand type(s) for /: 'MyClass' and 'str'
So, can we only concatenate 'PosixPath' type and 'str' type with forward slash "/"? Aren't there any other types to concatenate with forward slash "/"?
CodePudding user response:
Django==3.x
use pathlib, which allow you to use / to concatenate paths.
CodePudding user response:
If you want to achieve the same behaviour in one of your classes you will have to implement the method __truediv__
.
class Thing:
def __init__(self, name):
self.name = name
def __truediv__(self, other):
return Thing(self.name other)
thing = Thing('Monty')
other_thing = thing / 'Python'
print(other_thing.name)
This will give you the output MontyPython
.
If you want to be able to concatenate not only a Thing
instance and a string but two Thing
instances you have to check the type of other
.
class Thing:
def __init__(self, name):
self.name = name
def __truediv__(self, other):
if isinstance(other, Thing):
return Thing(self.name other.name)
return Thing(self.name other)
thing = Thing('Monty')
thing2 = Thing('Python')
other_thing = thing / thing2
print(other_thing.name)