-1

In a Flask tutorial, https://www.youtube.com/watch?v=cYWiDiIUxQc&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=4 There is a syntax I want to understand

return f"Post('{self.title}', '{self.dateposted}')"

Can someone decompose this line for me?

  1. f string means to return the result of Post() in a string
  2. '{self.title}' is an argument that is a string, because with ''
  3. {} is used to get a variable.
  4. But in the context self.title is ALREADY a string, why use ' '? Are my explanations correct? And what does ' ' do here?
davidism
  • 121,510
  • 29
  • 395
  • 339
Dark Lei
  • 31
  • 1
  • 7

2 Answers2

1

In the tutorial he returns this value for the __repr__ method of a class.
This method is called when repr() is called on the object. It's also called when you use str() or print() on the class, if a __str__ method has not been implemented for it.

The intention of implementing a __repr__ method is to aid debugging.
If you tried to print the object without defining a __repr__, it would print out like <Post object at 0x00000000>, which doesn't help!

The single-quotes are used for decoration, and they aren't really necessary.


See also: Difference between __str__ and __repr__?

You might also be interested in reading Fluent Python by Luciano Ramalho as it covers these methods and gives great examples of how they might be used (in addition to a lot of other Python wisdom)

Vasili Syrakis
  • 9,321
  • 1
  • 39
  • 56
0

I didn't check the link but this just returns a string that would break down to this.

return "Post('" + self.title + "', '" + self.dateposted + "')"

What is done with the returned string I don't know, but I assume it's evaluated somewhere else.

But all an f string does is embed variables or expressions into your string.

If the variable is not a string it converts it to a string first.

To break down your example, in an fstring, anything within the {} gets embedded. Since the ' are single quotes and outside of the curly braces, they are also part of the string.

Lets say self.title is equal to "My Title" and self.dateposted is equal to "08-22-2020". The returned string would then result in

"Post('My Title', '08-22-2020')"

If you were to then call exec() with this string it would call Post() with 2 positional string arguments.

Axe319
  • 4,255
  • 3
  • 15
  • 31
  • I don't think it is a concatenation of strings. It's calling Post function. – Dark Lei Aug 31 '20 at 20:24
  • It is definitely not calling a `Post` function. as @VasilSyrakis mentioned `Post` is a `class` and this is returning a `__repr__` string. – Axe319 Sep 01 '20 at 10:52