Kevin  Simon

Kevin Simon

1640853886

16 Quick Python Refactoring Tips

In this Tutorial I show you 16 quick Python refactoring tips for cleaner and more pythonic code. 

1: Merge nested if statements

Let’s start pretty simple. Instead of having nested if statements like this, just merge them into one.

if a:
    if b:
        pass

# -> refactor
if a and b:
    pass

2: Use any instead of a loop

Here we want to check if there is at least one positive element in a list. The longer solution is to loop over all numbers, check the current number, and then break once the condition is True. But for this task there exists a dedicated method in Python, the any function. Any returns True if any element of the iterable is true. This is much shorter and more pythonic than manually looping.

numbers = [-1, -2, -4, 0, 3, -7]
has_positives = False
for n in numbers:
    if n > 0:
        has_positives = True
        break

# -> refactor
has_positives = any(n > 0 for n in numbers)

3: Pull statements out of for/while loops

A lot of times you see loops where a variable is defined inside the loop, but it never changes. These are unnecessary operations, so just pull it out of the loop and then you only have to create it once.

for building in buildings:
    city = 'London'
    addresses.append(building.street_address, city)

# -> refactor
city = 'London'
for building in buildings:
    addresses.append(building.street_address, city)

4: Remove inline variables that are only used once and are immediately returned

A lot of times you see code where a variable is defined inside a function at the end, and one line later it is immediately returned. If it’s clear what the function is doing, just return the result directly. This is more concise and avoids an unnecessessary variable. However, it can still be helpful sometimes if it’s not exactly clear what the function is doing, and then you can give your last variable a meaningful name and use it as self-documenting code.

def state_attributes(self):
    """Return the state attributes."""
    state_attr = {
        ATTR_CODE_FORMAT: self.code_format,
        ATTR_CHANGED_BY: self.changed_by,
    }
    return state_attr

# -> refactor
def state_attributes(self):
    """Return the state attributes."""
    return {
        ATTR_CODE_FORMAT: self.code_format,
        ATTR_CHANGED_BY: self.changed_by,
    }

5: Replace if statement with if expression

Instead of using the if else statement to set the value of a variable, you can just set this in one line with the if expression like so. This refactoring technique is a little bit debatable, though. Some people still prefer the first option and this is just fine.

if condition:
    x = 1
else:
    x = 2

# -> refactor
x = 1 if condition else 2

6: Add a guard clause

When looking at this code it’s hard to quickly grasp what’s going on. There are multiple if-else statements and multiple indentations. Once you look closer you might realize that the first if statement covers almost the whole function code, only at the end we have the corresponding else clause where we just return False.

We can take this else clause and move it to the very beginning. This is also known as a guard statement. So if the condition is not true, we don’t execute the rest of the function code. This way wet got rid of one else clause and now there is one less level of indentation in the whole code. This looks much cleaner and is easier to understand.

def should_i_wear_this_hat(self, hat):
    if isinstance(hat, Hat):
        current_fashion = get_fashion()
        weather_outside = self.look_out_of_window()
        is_stylish = self.evaluate_style(hat, current_fashion)
        if weather_outside.is_raining:
            print("Damn.")
            return True
        else:
            print("Great.")
            return is_stylish
    else:
        return False

# -> refactor
def should_i_wear_this_hat(self, hat):
    if not isinstance(hat, Hat):
        return False

    current_fashion = get_fashion()
    weather_outside = self.look_out_of_window()
    is_stylish = self.evaluate_style(hat, current_fashion)
    if weather_outside.is_raining:
        print("Damn.")
        return True
    else:
        print("Great.")
        return is_stylish

7: Move assignments closer to their usage

This is the improved code from the last example, but it still takes a few moments to understand what’s happening here. So we want to check if we should wear a hat or not. The logic is this: If it’s raining, we always say True, and if it’s not raining, we say True if the hat is stylish. One easy way how we can drastically improve the readability of this logic is by moving the assignments closer to it’s usage. Let’s get the weather right before using the if statement. And now the fashion and the style variables are only needed in the else clause, so move them down. Now it should be a lot clearer what’s going on.

Remember my tip number 4? We could further shorten the code and immediately return the evaluate style result. However, in this example I also like the is_stylish name because it let’s you know that if the hat is stylish you say True, and otherwise False. So here it’s fine to leave the extra variable.

def should_i_wear_this_hat(self, hat):
    if not isinstance(hat, Hat):
        return False

    current_fashion = get_fashion()
    weather_outside = self.look_out_of_window()
    is_stylish = self.evaluate_style(hat, current_fashion)
    if weather_outside.is_raining:
        print("Damn.")
        return True
    else:
        print("Great.")
        return is_stylish

# -> refactor
def should_i_wear_this_hat(self, hat):
    if not isinstance(hat, Hat):
        return False

    weather_outside = self.look_out_of_window()
    if weather_outside.is_raining:
        print("Damn.")
        return True
    else:
        print("Great.")
        current_fashion = get_fashion()
        return self.evaluate_style(hat, current_fashion)
        # is_stylish = self.evaluate_style(hat, current_fashion)
        # return is_stylish

8: Simplify sequence checks

This is another thing I see very often. When you need to check if there are elements in a collection, for example in a list, you don’t need to write if len(your_list) > 0. You can simply say if your_list. This is the pep 8 recommended way and is also known as Truth Value Testing. It is possible because in Python, empty seqeuences and collections evaluate to False. So this can be applied to strings, tuples, lists, dictionaries, and sets.

if len(list_of_hats) > 0:
    hat_to_wear = choose_hat(list_of_hats)

# -> refactor
if list_of_hats:
    hat_to_wear = choose_hat(list_of_hats)


9. Merge append into list declaration

Let’s start with a simple one. Instead of declaring an empty list and then appending to it, just initialize the list directly with all elements. This shortens the code and makes the intent more explicit. It is also slightly more performant since it avoids the function calls to append().

players = []
players.append("Patrick")
players.append("Max")
players.append("Jessi")

# -> refactor
players = ["Patrick", "Max", "Jessi"]

The same holds true for filling up other collection types like sets and dictionaries.

10. Use items() to directly unpack dictionary values

When iterating over a dictionary and you need both the key and the value, then don’t access the values manually. Instead iterate over dictionary.items() which gives you both the keys and values at the same time.

This saves us the line that we used to assign to players, and the code now reads more naturally, with a touch less duplication.

teams_by_color = {"blue": ["Patrick", "Jessi"]}

for team_color in teams_by_color:
    players = teams_by_color[team_color]
    if is_winning(team_color):
        advance_level(players)

# -> refactor
for team_color, players in teams_by_color.items():
    if is_winning(team_color):
        advance_level(players)

11. Replace range(len) with enumerate

If we need to iterate over a list and need to track both the index and the current item, use the built-in enumerate() function instead of range(len). This returns both the current index and the current item as a tuple. So we can directly check the value here and also access the item with the index.

for i in range(len(players)):
    print(i, players[i])

# -> refactor
for i, player in enumerate(players):
    print(i, player)

Enumerate also comes with an optional start argument. If you use it, the counter starts at this value. But be aware that the items still start at the very first one.

for i, player in enumerate(players, start=1):
    print(i, player)

12. Replace a manual loop counter with a call to enumerate

This is very similar to before. Sometimes I see code where iteration is performed over the items directly - which is not bad by itself - but then a counter is needed and this gets manually incremented inside the loop. Again here you can simply use the enumerate function. This is simpler and also faster.

i = 0
for player in players:
    print(i, player)
    i += 1

# -> refactor
for i, player in enumerate(players):
    print(i, player)

12.1 Don’t manually update counter

If you just need to count the number of items, also don’t iterate over the loop and manually count all items. Instead, simply use the len() function to get the number of elements in the list.

num_players = 0
for player in players:
    num_players += 1

# -> refactor
num_players = len(players)

13. Simplify conditional into return statement

When we reach the end of a method and want to return True or False, a common way of doing this is like so. If the condition is True, we return True. And otherwise we return False at the end. However, it’s neater just to return the result directly:

def function():
    if isinstance(a, b) or issubclass(b, a):
        return True
    return False

# -> refactor
def function():
    return isinstance(a, b) or issubclass(b, a)

One thing we should be aware of here is that this can only be done if the expression evaluates to a boolean. Both isinstance() and issubclass() are functions that return a boolean, so this is fine. But in the next example the first expression pythonistas is a list and not a boolean value.

If pythonistas is a valid non-empty list, this would return the list instead of an expected boolean and then potentially be a bug in your application. So to make sure we’re returning a boolean here, we can wrap the return in a call to the bool() function.

def any_pythonistas():
    pythonistas = [coder for coder in coders if is_good_in_python(coder)]
    if pythonistas or self.is_pythonista():
        return True
    return False

# -> refactor
def any_hats():
    pythonistas = [coder for coder in coders if is_good_in_python(coder)]
    return bool(pythonistas or self.is_pythonista())

14. Merge duplicate blocks in conditional

We should always be searching for opportunities to remove duplicated code. A good place to do so is where there are multiple identical blocks inside an if …elif chain.

In this example both the if and the elif lead to the same performed function. So we can combine the first two blocks using or to remove the duplicated call to the function. Now if we need to change the processstandardpayment() line we can do it in one place instead of two.

def process_payment(payment, currency):
    if currency == "USD":
        process_standard_payment(payment)
    elif currency == "EUR":
        process_standard_payment(payment)
    else:
        process_international_payment(payment)

# -> refactor
def process_payment(payment, currency):
    if currency == "USD" or currency == "EUR":
        process_standard_payment(payment)
    else:
        process_international_payment(payment)

15. Replace multiple comparisons of same variable with in operator

We can refactor the previous code even one step further. Since we repeatedly check the same variable against multiple values, we can shorten this by using the in operator. If the currency value is in the defined list, we do the dedicated action.

def process_payment(payment, currency):
    if currency == "USD" or currency == "EUR":
        process_standard_payment(payment)
    else:
        process_international_payment(payment)

# -> refactor
def process_payment(payment, currency):
    if currency in ["USD", "EUR"]:
        process_standard_payment(payment)
    else:
        process_international_payment(payment)

And to improve this once more, we should use a set here. Looking up values in a set is faster, and we want unique elements here anyway, so a set is the better choice.

# -> refactor
def process_payment(payment, currency):
    if currency in {"USD", "EUR"}:
        process_standard_payment(payment)
    else:
        process_international_payment(payment)

16. Replace yield inside for loop with yield from

This is an advanced tip if you are already familiar with generators. One little trick that often gets missed is that Python’s yield keyword has a corresponding yield from for iterables.

If you have an iterable like a list, instead of saying for item in iterable: yield item, you can simply say yield from iterable. This is shorter and removes the manual looping over the iterable, which can also result in an improved performance.

def get_content(entry):
    for block in entry.get_blocks():
        yield block

# -> refactor
def get_content(entry):
    yield from entry.get_blocks()

What is GEEK

Buddha Community

Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

Art  Lind

Art Lind

1602666000

How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.

Intro

In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

  • md5
  • sha1
  • sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc…

You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like init, call, str etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Now there are a number of such special methods, which you might have come across too, in Python. We will just be taking an example of a few of them to understand how they work and how we can use them.

1. init

class AnyClass:
    def __init__():
        print("Init called on its own")
obj = AnyClass()

The first example is _init, _and as the name suggests, it is used for initializing objects. Init method is called on its own, ie. whenever an object is created for the class, the init method is called on its own.

The output of the above code will be given below. Note how we did not call the init method and it got invoked as we created an object for class AnyClass.

Init called on its own

2. add

Let’s move to some other example, add gives us the ability to access the built in syntax feature of the character +. Let’s see how,

class AnyClass:
    def __init__(self, var):
        self.some_var = var
    def __add__(self, other_obj):
        print("Calling the add method")
        return self.some_var + other_obj.some_var
obj1 = AnyClass(5)
obj2 = AnyClass(6)
obj1 + obj2

#python3 #python #python-programming #python-web-development #python-tutorials #python-top-story #python-tips #learn-python