Skip to content
Cuelogic
  • Services
    • Services

      Build better software and explore engineering excellence with our industry-leading tech services.

      • Product Engineering
        • Product Engineering
          • Product Development
          • UX Consulting
          • Application Development
          • Application Modernization
          • Quality Assurance Services
          Menu
          • Product Development
          • UX Consulting
          • Application Development
          • Application Modernization
          • Quality Assurance Services
          Migrating application and databases to the cloud, moving from legacy technologies to a serverless platform for a FinTech organization.
          Download ❯
      • Cloud Engineering
        • Cloud Engineering
          • Cloud Services
          • DevOps Services
          • Cloud Migration
          • Cloud Optimization
          • Cloud Computing Services
          Menu
          • Cloud Services
          • DevOps Services
          • Cloud Migration
          • Cloud Optimization
          • Cloud Computing Services
          Building end-to-end data engineering capabilities and setting up DataOps for a healthcare ISV managing sensitive health data.
          Download ❯
      • Data & Machine Learning
        • Data & Machine Learning
          • Big Data Services
          • AI Consulting
          Menu
          • Big Data Services
          • AI Consulting
          Setting up a next-gen SIEM system, processing PB scale data with zero lag, and implementing real-time threat detection.
          Download ❯
      • Internet of Things
        • Internet of Things
          • IoT Consulting
          • IoT App Development
          Menu
          • IoT Consulting
          • IoT App Development
          Building a technically robust IoT ecosystem that was awarded the best implementation in Asia Pacific for a new age IoT business.
          Download ❯
      • Innovation Lab as a Service
        • Innovation Lab as a Service
          • Innovation Lab as a Service
          Menu
          • Innovation Lab as a Service
          Establishing an Innovation Lab for the world’s largest Pharma ISV, accelerating product innovation & tech research while ensuring BaU.
          Download ❯
      • Cybersecurity Services
        • Cybersecurity Services
          • Cybersecurity Services
          Menu
          • Cybersecurity Services
          Big Data Engineering at scale for IAC’s SIEM system, processing PB scale data to help brands like Tinder, Vimeo, Dotdash, etc.
          Download ❯
      • Healthcare IT Services
        • Healthcare IT Services
          • Healthcare IT Services
          Menu
          • Healthcare IT Services
          Upgrading a platform for patients to access doctors via chat or video consultation, modernizing design, & migrating infra to the cloud.
          Download ❯
  • Company
    • Company

      Find out why Cuelogic, a world-leading software product development company, is the best fit for your needs. See how our engineering excellence makes a difference in the lives of everyone we work with.

    • about usAbout

      Discover how Cuelogic is as a global software consultancy and explore what makes us stand apart.

    • CultureCulture

      Read about our free and open culture, a competitive edge that helps clients and employees thrive.

    • Current openingCurrent Openings

      Want to join us? Search current openings, check out the recruitment process, or email your resume.

  • Insights
  • Tell Us Your Project
Tell Us Your Project  ❯
Product Development  5 Mins Read  May 26, 2015  Cuelogic

Python Tips & Tricks (Hacks)

Share Via –
Share on facebook
Share on twitter
Share on linkedin

Home > Python Tips & Tricks (Hacks)

Python-tips-trics-hacks-for-web-application-development Python is one of the most powerful and productive languages used by sites like Youtube & Dropbox. It is used outside of web development too! It's becoming one of the standard languages used in graphics and is heavily used in science and engineering. There are also very popular desktop applications written in Python.

Python is utilized by bigger companies mostly that can evaluate vast data sets; it is also used for system automation, web applications, big data, analytics, and security software. This article aims to show off some lesser-known tricks to put you on the path to faster development, easier debugging, and general fun.

TIPS:

1) For a critical code you should depend on an external package

Python makes many tasks easier, however it is not continuously possible to provide the best performance with time critical tasks. Utilizing a C, C++ programming language external package for time-critical tasks can improve application performance. These packages are platform-specific, so that you need the appropriate package for the platform you’re using. concisely, this solution gives up some application portability in exchange for performance that you can obtain only by programming directly to the underlying host.

Packages that helps to increase your app performance. They all operate in different ways:

  • Cython
  • Pyrex
  • PyPy
  • PyInlne

2) Use keys for sorts

Old Python sorting code out there that will cost you time in creating a custom sort and speed in actually performing the sort during runtime. The best way to sort items is to use keys and the default sort() method whenever possible.

Ex:

In following example, each case the list is sorted according to the index you select as part of the key argument. This approach works just as well with strings as it does with numbers.

import operator somelist = [(1, 5, 8), (6, 2, 4), (9, 7, 5)] somelist.sort(key=operator.itemgetter(0)) somelist #Output = [(1, 5, 8), (6, 2, 4), (9, 7, 5)] somelist.sort(key=operator.itemgetter(1)) somelist #Output = [(6, 2, 4), (1, 5, 8), (9, 7, 5)] somelist.sort(key=operator.itemgetter(2)) somelist #Output = [(6, 2, 4), (9, 7, 5), (1, 5, 8)],

 

3) Optimizing loops

With Python, you can rely on a wealth of techniques for making loops run faster. However, one method developers often miss is to avoid the use of dots within a loop.

For example, consider the following code:

 

lowerlist = ['this', 'is', 'lowercase'] upper = str.upper upperlist = [] append = upperlist.append for word in lowerlist: append(upper(word)) print(upperlist) #Output = ['THIS', 'IS', 'LOWERCASE']

 

Here the aim is to reduce the amount of work that Python performs within loops because the interpreted nature of Python can really slow it down in those instances. Whenever you make a call to str.upper, Python evaluates the method. Despite, if you place the evaluation in a variable, the value is already known and Python can perform tasks faster.

 

4) Multiple coding approach

Using precisely the same coding approach every time you create an application will almost certainly result in some situations where the application runs slower than it might. Try a little experimentation as part of the profiling process. For example, when managing items in a dictionary, you can take the safe approach of determining whether the item already exists and update it or you can add the item directly and then handle the situation where the item doesn’t exist as an exception.

Consider this example: 

 

n = 16 myDict = {} for i in range(0, n): char = 'abcd'[i%4] if char not in myDict: myDict[char] = 0 myDict[char] += 1 print(myDict)

 

This code will generally run faster when myDict is empty to start with. However, whenmyDict is usually filled with data, an alternative approach works better.

n = 16 myDict = {} for i in range(0, n): char = 'abcd'[i%4]

try:

myDict[char] += 1 except KeyError: myDict[char] = 1 print(myDict)

The output of {'d': 4, 'c': 4, 'b': 4, 'a': 4} is the same in both cases. The only difference is how the output is obtained. Thinking outside the box and creating new coding techniques can help you obtain faster results with your applications.

 

5) Use a newer version

In general, every new version of Python included optimizations that make it faster than the previous version. You need to use the new libraries you obtained to use with the new version of Python and then check your application for breaking changes. The limiting factor is whether your favorite libraries have also made the move to the newer version of Python. Rather than asking whether the move should be made, the key question is determined when a new version has sufficient support to make a move viable. You need to verify that your code still runs. Only after you make the required corrections will you notice any difference.

However, if you just ensure your application runs with the new version, you could miss out on new features found in the update. Once you make the move, profile your application under the new version, check for problem areas, and then update those areas to use new version features first. Users will see a larger performance gain earlier in the upgrade process.

 

6) Cross compile your app:

When working with a cross-compiler, be sure it supports the version of Python you work with. To make this solution work, you need both a Python interpreter and a C++ compiler.

 

 

Tricks:
1) Build strings using str.join not +

Suppose you wanted to build the string '0--1--2--3--4'.

You could use a for-loop like this: 

result = '' for i in range(5): result = result + str(i) if i < 4: result = result + '--' But there are at least three problems here: (1) it can be written more succinctly, (2) it uses '+' instead of 'str.join' and worst of all, (3) it has to test if i is the last item before adding the separator --.
The better way to build a string with a repeated separator is to use str.join: >>> '--'.join(map(str,range(5))) '0—1--2--3--4'

 

'--'is a string. '—'.joinis the string's join method. The join method expects one argument, which is a sequence of strings.

>>> map(str, range(5)) ['0', '1', '2', '3', '4']

 

2) Dictionaries within dictionaries:

This amazing trick for nesting dictionaries as values within other dictionaries to an arbitrary depth

import collections def tree(): return collections.defaultdict(tree)

 

3) Build lists:

duplicate – change [5]to the list and 5to the multiplier you need 

>>> [5]*5 [5, 5, 5, 5, 5]

comprehension – change x**2 to the value and range(5)to the list you need

>>> [x**2 for x in range(5)] [0, 1, 4, 9, 16]

mapping – change intto the function and ['1', '2', '3']to the list you need

>>> map(int, ['1', '2', '3']) [1, 2, 3]

All of the above hacks can help you develop faster Python apps. However there are no silver bullets. None of the tips will work every time. Some work better than others with specific versions of Python even the platform can make a difference.

 

Recommended Content
Low Code Platform: The Future of Software Development ❯
Micro Frontend Deep Dive – Top 10 Frameworks To Know About ❯
Micro Frontends – Revolutionizing Front-end Development with Microservices ❯
Go Back to Main Page ❯
Tags
web apps python web application technologies python hacks python tips and tricks
Share This Blog
Share on facebook
Share on twitter
Share on linkedin

Leave a Reply Cancel reply

People Also Read

Product Development

Low Code Platform: The Future of Software Development

8 Mins Read
Quality Engineering

BDD vs TDD : Highlighting the two important Quality Engineering Practices

8 Mins Read
DevOps

Getting Started With Feature Flags

10 Mins Read
Subscribe to our Blog
Subscribe to our newsletter to receive the latest thought leadership by Cuelogic experts, delivered straight to your inbox!
Services
Product Engineering
  • Product Development
  • UX Consulting
  • Application Development
  • Application Modernization
  • Quality Assurance Services
Menu
  • Product Development
  • UX Consulting
  • Application Development
  • Application Modernization
  • Quality Assurance Services
Data & Machine Learning
  • Big Data Services
  • AI Consulting
Menu
  • Big Data Services
  • AI Consulting
Innovation Lab as a Service
Cybersecurity Services
Healthcare IT Solutions
Cloud Engineering
  • Cloud Services
  • DevOps Services
  • Cloud Migration
  • Cloud Optimization
  • Cloud Computing Services
Menu
  • Cloud Services
  • DevOps Services
  • Cloud Migration
  • Cloud Optimization
  • Cloud Computing Services
Internet of Things
  • IoT Consulting
  • IoT App Development
Menu
  • IoT Consulting
  • IoT App Development
Company
  • About
  • Culture
  • Current Openings
Menu
  • About
  • Culture
  • Current Openings
We are Global
India  |  USA  | Australia
We are Social
Facebook
Twitter
Linkedin
Youtube
Subscribe to our Newsletter

We don't spam!

cuelogic

We are Hiring!

Blogs

Recent Posts

  • Low Code Platform: The Future of Software Development
  • BDD vs TDD : Highlighting the two important Quality Engineering Practices
  • Getting Started With Feature Flags
  • Data Mesh – Rethinking Enterprise Data Architecture
  • Top Technology Trends for 2021
cuelogic

We are Hiring!

Blogs

Recent Posts

  • Low Code Platform: The Future of Software Development
  • BDD vs TDD : Highlighting the two important Quality Engineering Practices
  • Getting Started With Feature Flags
  • Data Mesh – Rethinking Enterprise Data Architecture
  • Top Technology Trends for 2021
We are Global
India  |  USA  | Australia
We are Social
Facebook
Twitter
Linkedin
Youtube
Subscribe to our Newsletter

We don't spam!

Services
Product Engineering

Product Development

UX Consulting

Application Development

Application Modernization

Quality Assurance Services

Cloud Engineering

Cloud Services

DevOps Services

Cloud Migration

Cloud Optimization

Cloud Computing Services

Data & Machine Learning

Big Data Services

AI Consulting

Internet of Things

IoT Consulting

IoT Application Services

Innovation Lab As A Service
Cybersecurity Services
Healthcare IT Services
Company

About

Culture

Current Openings

Insights
Privacy Policy  
All Rights Reserved © Cuelogic 2021

Close

Do you have an app development challenge? We'd love to hear about it!

By continuing to use this website, you consent to the use of cookies in accordance with our Cookie Policy.