Using these Python Ideas in your code will make you a seasoned developer!
So, demand for Python developers will keep increasing in the upcoming years. The following are four important concepts that any developer would be wise to incorporate into their work in order to stay ahead of the game.
1. Understanding lists and dictionaries
This is an often overlooked concept in programming that can cause a lot of confusion. What if you create a list called ‘x’ and then, assign this list to the variable ‘y’?
x = [9,8,7] y = x
Append new value in the y list and then print both lists:
y.append(6) print(y) # Prints [9,8,7,6] print(x) # Prints [9,8,7,6]
You’re probably asking why the new value was added to both lists! This occurs because, unless otherwise specified, lists are not copied when assigned in Python. A new reference to this list is instead created. This means that y is just a reference to x and thus it works as you wanted it to.
This means that changes in either variable will be reflected in the same list. You must use the.copy() method to make a duplicate of the list:
x = [9,8,7] y = x.copy() y.append(6) print(y) # Prints [9,8,7,6] print(x) # Prints [9,8,7]
2. Context managers
Python’s Context Managers tool, a classic example of Resource Management, helps in allocating & releasing resources when the need arises and ensures that all aspects of a resource are handled properly. The most used and recognized example of a context manager is with the statement. The file-opening/closing ‘with’ mostly indicates the start and end of each file..
file = open(‘data.txt’,’w’) try: file.write(“Follow Me”) except: file.close()
The with context manager enables you to do the task of opening a file in write mode and closing it in one line if something is not right. This would be especially useful for closing the file automatically if, for example, the user tries running the script but does not have permission to write to this file.
with open (‘data.txt’,’w’) as f: f.write(“Follow Me”)
Notice that we never called f.close() even though we opened it previously. Context managers handle these tasks automatically, and they will also catch exceptions if they are raised while cleanup is being done. Context Manager’s usefulness goes far beyond just files; they could be used to manage a game’s state or a database connection for example!
A generator is a kind of function that returns an object that can be iterated over. It contains at least a yield statement. The yield keyword in python is used to return a value from a function without destroying its current state or reference.
A generator is a function that contains the yield keyword. A generator will only generate one piece of data and anything else you ask it to once. They are very memory efficient and take less space in the brain.
def fib(limit): a,b = 0,1 while a < limit: yield a a, b = b, a + b for x in fib(10): print (x)
Yield will pause the execution of a function and return a value from it every time. On the other hand, return terminates it.
4. Type hinting
Hints are used to make your code more self-explanatory and thus easier to read. One way you can do this is by hinting the type of the parameter & return value of a function. For example, we want to validate that the input text of a user is always an integer. To achieve this, we write a function that returns True or False based on our validations:
def validate_func(input): ...
Now, you see the usefulness of this function. It’s not that complicated if you just take a look at the definition. Without that, it would be much more difficult to understand how this works.
What is the input parameter’s variable type? Where does it come from? Is it already an integer? What if it isn’t? Does this function return anything, or just raise an exception when something goes wrong…? Some questions can be answered by refactoring to this code:
def validate_func(input: str) -> bool: ...
With this function, it’s easier for a first-time reader to understand.
Logging is the process of recording the code that a programme runs. Logring facilitates debugging by displaying the steps made by a programmer while creating code. Python provides some modules that make logging fairly simple, and logs can be outputted to files afterwards if necessary.
- You can use this to determine what is wrong with your text.
- Success has been confirmed.
- When an unforeseen scenario arises, issue a warning.
- Error: Because of a more serious issue than a warning.
- Critical: A critical error occurs after which the software is unable to run.
Soon, I will provide a special article on “Logging in Python.” Subscribe to receive an email when it is published.
Here are the Top 5 Python Ideas That Will Help You Advance Your Career. The concepts mentioned above are just a few of the Python insights that experienced developers keep in mind.
I hope you found this essay useful and learned something new.