Python, features you may not know. Part 1

in python •  7 years ago  (edited)

python-logo-3.6.gif

Hi, here I will enumerate and give you examples of some cool features of python, you may or may not know, so let's start.

For .. else

for i in [1, 2, 4]:
    if i == 3:
        break
else:
    print("i was never 3")

Output: i was never 3
How it works? If the fore will not break then the else statement will be executed. This is the cleaner version of:

found = False
for i in [1, 2, 4]:
    if i == 3:
        found = True
        break
if not found: 
    print("i was never 3")

Function argument unpacking

You can unpack a list or dictionary as function arguments using * and **.
Example:

def draw_point(x, y):
    # do some magic

point_foo = (3, 4)
point_bar = {'y': 3, 'x': 2}

draw_point(*point_foo)
draw_point(**point_bar)

Manipulating lists

a = [1,2,3,4,5]
print(a[::2])  # iterate over the whole list in 2-increments

Output: [1, 3, 5]
But here we have a special case when we want to reverse a list we can do a[::-1] and the new list will be [5,4,3,2,1]

Decorators

Decorators allow to wrap a function or method in another function that can add functionality, modify arguments or results, etc. You write decorators one line above the function definition, beginning with an "at" sign (@).

def login_required(view_func):
    @wraps(view_func)
    def is_authenticated(request, *args, **kwargs):
        if request.user and request.user.is_authenticated():
            return view_func(request, *args, **kwargs)
        return HttpResponse(status=405)
    return is_authenticated


@login_required
def submit_order(request):
    pass

Before the method submit_order will be called the function login_required is called and if the user is authenticated the submit_order will be called, else we will return 405.
On one method you can use multiple decorators, ex:

@login_required
@do_stuff
def submit_order(request):
    pass

The execution order is from top to bottom, login_required -> do_stuff -> submit_order, as long every decorator is returning the view_func.

Braces

You can use braces?
from __future__ import braces
Hell NO. This is an easter egg in Python, you will get SyntaxError: not a chance

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!