Star ratings with icons!

I’m not sure whether to be proud or ashamed, but I made a quick and dirty star rating display using the built-in font-awesome icons. I prefer these icons over images as they load much faster, scale easily, and the colors are limitless.

The rating is pulled from a server module and stored as a variable. All this code goes in the client form. Each star is named after its position (1-5). The function simply changes the icon based on the value.

def __init__(self, **properties):
    self.star1.icon = self.get_star(1)
    self.star2.icon = self.get_star(2)
    self.star3.icon = self.get_star(3)
    self.star4.icon = self.get_star(4)
    self.star5.icon = self.get_star(5)
    
    

  def get_star(self, position):
    rating_num = Variables.rating_num
    if position == 1:
      if rating_num >= 1:
        return 'fa:star'
      elif rating_num >= 0.5:
        return 'fa:star-half-o'
      else:
        return 'fa:star-o'
    if position == 2:
      if rating_num >= 2:
        return 'fa:star'
      elif rating_num >= 1.5:
        return 'fa:star-half-o'
      else:
        return 'fa:star-o'
    if position == 3:
      if rating_num >= 3:
        return 'fa:star'
      elif rating_num >= 2.5:
        return 'fa:star-half-o'
      else:
        return 'fa:star-o'
    if position == 4:
      if rating_num >= 4:
        return 'fa:star'
      elif rating_num >= 3.5:
        return 'fa:star-half-o'
      else:
        return 'fa:star-o'
    if position == 5:
      if rating_num >= 4.8:
        return 'fa:star'
      elif rating_num >= 4.5:
        return 'fa:star-half-o'
      else:
        return 'fa:star-o'

I’m about 99% sure there is a prettier more pythonic way to do this. But this works, seems fast, and looks good.

6 Likes

You could use data binding to assign icon property, but I like it the way you did it, in the __init__ because it’s more readable.

One little improvement could be on the get_star function. This version seems to do the same and is shorter (I have not tested it):

  def get_star(self, position):
    rating_num = Variables.rating_num

    if rating_num >= position:
      return 'fa:star'

    if rating_num >= position - 0.5:
      return 'fa:star-half-o'

    return 'fa:star-o'

Whenever you use copy and paste to add a few lines of code, there usually is a more elegant way :slight_smile:

3 Likes

Haha that is shorter and really obvious. My only excuse is that I made it at 1:00AM…

(P.S. How did you know I copy/pasted :astonished:)

2 Likes