Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python @ (at) prefix in top level module code - What does it stand for? [duplicate]

Tags:

python

syntax

What does the @ symbol do in Python?

like image 211
AJ00200 Avatar asked Mar 31 '26 01:03

AJ00200


2 Answers

An @ symbol at the beginning of a line is used for class and function decorators:

  • PEP 318: Decorators

  • Python Decorators - Python Wiki

  • The most common Python decorators are:

    • @property
    • @classmethod
    • @staticmethod

An @ in the middle of a line is probably matrix multiplication:

  • @ as a binary operator.
like image 81
FogleBird Avatar answered Apr 02 '26 02:04

FogleBird


Example

class Pizza(object):
    def __init__(self):
        self.toppings = []

    def __call__(self, topping):
        # When using '@instance_of_pizza' before a function definition
        # the function gets passed onto 'topping'.
        self.toppings.append(topping())

    def __repr__(self):
        return str(self.toppings)

pizza = Pizza()

@pizza
def cheese():
    return 'cheese'
@pizza
def sauce():
    return 'sauce'

print pizza
# ['cheese', 'sauce']

This shows that the function/method/class you're defining after a decorator is just basically passed on as an argument to the function/method immediately after the @ sign.

First sighting

The microframework Flask introduces decorators from the very beginning in the following format:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

This in turn translates to:

rule      = "/"
view_func = hello
# They go as arguments here in 'flask/app.py'
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
    pass

Realizing this finally allowed me to feel at peace with Flask.

like image 27
Morgan Wilde Avatar answered Apr 02 '26 04:04

Morgan Wilde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!