skip to navigation
skip to content

Planet Python

Last update: April 10, 2021 10:46 AM UTC

April 10, 2021


Wingware

Wing Python IDE 7.2.9 - April 12, 2021

Wing 7.2.9 adds remote development for 64-bit Raspberry Pi, improves auto-closing of quotes, optimizes change tracking when large numbers of project files change at once, improves debugger data display for some value types, and makes a number of other usability improvements.

See the change log for details.

Download Wing 7.2.9 Now: Wing Pro | Wing Personal | Wing 101 | Compare Products


What's New in Wing 7.2


Wing 7.2.9 Screen Shot

Auto-Reformatting with Black and YAPF (Wing Pro)

Wing 7.2 adds support for Black and YAPF for code reformatting, in addition to the previously available built-in autopep8 reformatting. To use Black or YAPF, they must first be installed into your Python with pip, conda, or other package manager. Reformatting options are available from the Source > Reformatting menu group, and automatic reformatting may be configured in the Editor > Auto-reformatting preferences group.

See Auto-Reformatting for details.

Improved Support for Virtualenv

Wing 7.2 improves support for virtualenv by allowing the command that activates the environment to be entered in the Python Executable in Project Properties, Launch Configurations, and when creating new projects. The New Project dialog now also includes the option to create a new virtualenv along with the new project, optionally specifying packages to install.

See Using Wing with Virtualenv for details.

Support for Anaconda Environments

Similarly, Wing 7.2 adds support for Anaconda environments, so the conda activate command can be entered when configuring the Python Executable and the New Project dialog supports using an existing Anaconda environment or creating a new one along with the project.

See Using Wing with Anaconda for details.

And More

Wing 7.2 also introduces support for Python 3.9, adds How-Tos for using Wing with AWS and PyXLL, makes it easier to debug modules with python -m, adds support for Python 3 enums, supports remote development to 64-bit Raspberry Pi, simplifies manual configuration of remote debugging, allows using a command line for the configured Python Executable, supports constraining Find Uses of imported symbols to only the current file, improves vi mode, allows folding .pyi and .pi files, improves Debug I/O process management, enhances accuracy of some types of code warnings, supports remote development without SSH tunnels, improves debugger data display for some value types, improves support for recent macOS versions, and makes a number of usability and stability improvements.

For a complete list of new features in Wing 7, see What's New in Wing 7.


Try Wing 7.2 Now!


Wing 7.2 is an exciting new step for Wingware's Python IDE product line. Find out how Wing 7.2 can turbocharge your Python development by trying it today.

Downloads: Wing Pro | Wing Personal | Wing 101 | Compare Products

See Upgrading for details on upgrading from Wing 6 and earlier, and Migrating from Older Versions for a list of compatibility notes.

April 10, 2021 10:46 AM UTC

April 09, 2021


TestDriven.io

Django vs. Flask in 2021: Which Framework to Choose

In this article, we'll look at the best use cases for Django and Flask along with what makes them unique, from an educational and development standpoint.

April 09, 2021 10:28 PM UTC


Learn PyQt

PyQt6 Book now available: Create GUI Applications with Python & Qt6 — The hands-on guide to making apps with Python

Hello! Today I have released the first PyQt6 edition of my book Create GUI Applications, with Python & Qt6.

This update follows the 4th Edition of the PyQt5 book updating all the code examples and adding additional PyQt6-specific detail. The book contains 600+ pages and 200+ complete code examples taking you from the basics of creating PyQt applications to fully functional apps.

To celebrate the milestone, the book is available this week with 20% off. As with earlier editions, readers get access to all future updates for free -- so it's a great time to snap it up! You'll also get a copy of the PyQt5, PySide6 and PySide2 editions.

PyQt6 book cover

If you bought a previous edition of the book (for PyQt5, PySide2 or PySide6) you get this update for free! Just log into your account on LearnPyQt and you'll find the book already waiting for you under "My Books & Downloads".

If you have any questions or difficulty getting hold of this update, just get in touch.

Enjoy!

See the complete PyQt5 tutorial, from first steps to complete applications with Python & Qt5.

April 09, 2021 03:00 PM UTC


Quansight Labs Blog

PyTorch TensorIterator Internals - 2021 Update

For contributors to the PyTorch codebase, one of the most commonly encountered C++ classes is TensorIterator. TensorIterator offers a standardized way to iterate over elements of a tensor, automatically parallelizing operations, while abstracting device and data type details.

In April 2020, Sameer Deshmukh wrote a blog article discussing PyTorch TensorIterator Internals. Recently, however, the interface has changed significantly. This post describes how to use the current interface as of April 2021. Much of the information from the previous article is directly copied here, but with updated API calls and some extra details.

Read more… (8 min remaining to read)

April 09, 2021 02:00 PM UTC


Real Python

The Real Python Podcast – Episode #55: Getting Started With Refactoring Your Python Code

Do you think it's time to refactor your Python code? What should you think about before starting this task? This week on the show, we have Brendan Maginnis and Nick Thapen from Sourcery. Sourcery is an automated refactoring tool that integrates into your IDE and suggests improvements to your code.


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

April 09, 2021 12:00 PM UTC


Python for Beginners

Convert a list containing float numbers to string in Python

There may be situations where we want to convert a list containing float numbers to string while working in python. In this article, we will look at different ways to convert the list containing float numbers to a string which contains the elements of the list as space separated sub strings.

Important functions for the task to convert a list containing float numbers to string

To convert a list of floating point numbers to string, we will need several string methods which we will discuss first and then perform the operations.

str() function

The str() function converts an integer literal,a float literal or any other given  input to a string literal and returns the string literal of the input after conversion. This can be done as follows.

float_num=10.0
str_num=str(float_num)

join() method

join() method is invoked on a separator and an iterable object of strings is passed to the method as input. It joins each string in the iterable object with the separator and returns a new string. 

The syntax for join() method is as separator.join(iterable) where separator can be any character and iterable can be a list or tuple etc. This can be understood as follows.


str_list=["I","am","Python","String"]
print("List of strings is:")
print(str_list)
separator=" "
str_output=separator.join(str_list)
print("String output is:")
print(str_output)

Output:

List of strings is:
['I', 'am', 'Python', 'String']
String output is:
I am Python String

map() function

The map() function takes as input a function(functions are first class objects and can be passed as a parameter in python) and an iterable as argument and executes the function on each element of the iterable object and returns  the output map object which can be converted into any iterable.

The syntax for map() function is map(function,iterable). This can be understood as follows.


float_list=[10.0,11.2,11.7,12.1]
print("List of floating point numbers is:")
print(float_list)
str_list=list(map(str,float_list))
print("List of String numbers is:")
print(str_list)

Output:

List of floating point numbers is:
[10.0, 11.2, 11.7, 12.1]
List of String numbers is:
['10.0', '11.2', '11.7', '12.1']

Now we will see how to convert a list containing floating point numbers to string using the above functions.

Convert a list containing float numbers to string using for loop

We can convert the list of float numbers to string by declaring an empty string and then performing string concatenation to add the elements of the list to the string as follows.


float_list=[10.0,11.2,11.7,12.1]
print("List of floating point numbers is:")
print(float_list)
float_string=""
for num in float_list:
    float_string=float_string+str(num)+" "
    
print("Output String is:")
print(float_string.rstrip())

Output:

List of floating point numbers is:
[10.0, 11.2, 11.7, 12.1]
Output String is:
10.0 11.2 11.7 12.1

 In the above program, the output string contains an extra space at the end which has to be removed using rstrip() method.To avoid this additional operation, We can use the join() method instead of performing concatenation operation by adding the strings to create the output string as follows.


float_list=[10.0,11.2,11.7,12.1]
print("List of floating point numbers is:")
print(float_list)
float_string=""
for num in float_list:
    float_string=" ".join([float_string,str(num)])
print("Output String is:")
print(float_string.lstrip())

Output

List of floating point numbers is:
[10.0, 11.2, 11.7, 12.1]
Output String is:
10.0 11.2 11.7 12.1

In the above method, an extra space is added at left of the output string which has to be removed using lstrip() method. To avoid this,Instead of applying str() function on every element of the list, we can use map() function  to convert the list of float numbers to a list of strings and then perform the string concatenation using join() method to get the output string as follows.

float_list=[10.0,11.2,11.7,12.1]
print("List of floating point numbers is:")
print(float_list)
str_list=list(map(str,float_list))
print("List of String numbers is:")
print(str_list)
float_string=""
for num in float_list:
    float_string=" ".join(str_list)
    
print("Output String is:")
print(float_string)

Output:

List of floating point numbers is:
[10.0, 11.2, 11.7, 12.1]
List of String numbers is:
['10.0', '11.2', '11.7', '12.1']
Output String is:
10.0 11.2 11.7 12.1

Convert a list containing float numbers to string using list comprehension

Instead of for loop, we can use list comprehension to perform the conversion of a list of floating point numbers to string as follows. We can use the join() method with list comprehension as follows.

float_list=[10.0,11.2,11.7,12.1]
print("List of floating point numbers is:")
print(float_list)
str_list=[str(i) for i in float_list]
print("List of floating string numbers is:")
print(str_list)
float_string=" ".join(str_list)
print("Output String is:")
print(float_string)

Output:

List of floating point numbers is:
[10.0, 11.2, 11.7, 12.1]
List of floating string numbers is:
['10.0', '11.2', '11.7', '12.1']
Output String is:
10.0 11.2 11.7 12.1

Conclusion

In this article, we have seen how to convert a list containing floating point numbers into string using different string methods like str(), join() and for loop or list comprehension in python. Stay tuned for more informative articles.

The post Convert a list containing float numbers to string in Python appeared first on PythonForBeginners.com.

April 09, 2021 11:58 AM UTC


CubicWeb

CubicWeb Monthly news february/march 2021

It has been quite a time since the last public news ; we will try in the letter to summarize what we did during february and march 2021. During this period, we tried to fix issues, migrate a lot of our code base to latest version of CubicWeb. We also did some archeology ; we have been looking at all the old heads in CubicWeb's repository, and we have tried to rebase them on the latest public head. A lot of merge requests have been created and are still under review.

CubicWeb 3.30 is out!

We released Cubicweb 3.30 on march 16th. There are no “big” changes in this release. A lot of issues have been fixed, the documentation have been improved − a new tuto is coming ! − and a few new features have been implemented.

Here is an extract of the changelog:

One can find the full changelog on Cubicweb release page here.

Adding python types to RQL

In the past months, python types have progressively been included in RQL. This is a step forward to python types in CubicWeb itself.

A lot of work has been done, and there is still a lot of work to do. Adding types to RQL help us to simplify the refactorings. As RQL's API is not clearly defined, we will run CubicWeb's tests on each merge request of RQL, to make sure nothing breaks.

Separate Back and Front

For some time now, the trend has been towards a clear separation between front and back. We are adding more features to use React in the front.

CwClientLibJS, a library allowing to use rql in the browser. CwClientLibJS is now in version 1.1.0 and is able to generate query on entity state (see !20).

react-admin-cubicweb, new tools to generate admin pages. react-admin-cubicweb is still at an early stage but can display entity attribute and relation. It also allows edition as well. The version 0.3.0 has been released !

Release-new

Release-new is one of our latest utility to release new versions of our cubes. Assuming that you are using conventional commits, you should really like this tool to release new version of your cubes.

Release-new takes care to:

By default, it will try to guess if it is a major, minor or patch release (you can specify the release type if need be). The changelog will be updated and you will be able to edit it before the commit is done. The update of the changelog will be eased if you use conventionnal commit as your commit history will be dispatched in the appropriate sections. For instance, the last changelog of CubicWeb has been produced by this tool !

Docker images

During our last hackathon, a team worked on our CubicWeb Docker images. The code to generate them has been rewritten to be simpler. During this refactoring, we took care to generate docker images for minor versions of CubicWeb as well. Therefore, on https://hub.docker.com/r/logilab/cubicweb/tags you can find docker images for major and minor versions of CubicWeb with different versions of python, to suit your needs the best we can :)

See you next month!

April 09, 2021 07:38 AM UTC


Janusworx

I Can’t Do This … Yet.

I’ve been “soft” looking for a job, since the end of last year when I learnt the basics of Python.
(Want me to come work you as a junior developer? Here’s my resume!)

Read more… (2 min remaining to read)

April 09, 2021 03:20 AM UTC

April 08, 2021


Patrick Kennedy

What is Werkzeug?

I wrote a blog post on TestDriven.io explaining what Werkzeug is and how Flask uses it for its core HTTP functionality. In this blog post, you’ll develop your own WSGI-compatible application using Werkzeug to create a Flask-like web framework:

https://testdriven.io/blog/what-is-werkzeug/

This blog post looks at explores the following functionality provided by Werkzeug (which Flask uses):

  1. Request processing
  2. Response handling
  3. URL routing
  4. Middleware
  5. HTTP utilities
  6. Exception handling
  7. Development server (with hot reloading)

To help explain this functionality, a web application is built using Werkzeug:

https://gitlab.com/patkennedy79/werkzeug_movie_app

April 08, 2021 03:51 PM UTC


Janusworx

A Love Letter to Books

Despite financial troubles there’s a sense in which my childhood was immensely privileged — a pauper in the material world, I was a sultan in the world of ideas.

Erik Hoel

I started by wanting to share that quote and link on my microblog and then my thoughts turned into a blog post sized comment.
I decided to post it here too, then.


Read more… (2 min remaining to read)

April 08, 2021 01:08 PM UTC


Mike Driscoll

Python 101 is Pay What You Want for 24 Hours

For the next 24 hours, Python 101 will be Pay What You Want, $3 minimum (usually $25).
Python 101 2nd Ed Kickstarter

The second edition of Python 101 is completely rewritten from the ground up. In this book, you will learn the Python programming language and lots more.

This book is split up into four sections:

  1. The Python Language
  2. Intermediate Topics
  3. Creating Sample Applications
  4. Distributing Your Code
 

The post Python 101 is Pay What You Want for 24 Hours appeared first on Mouse Vs Python.

April 08, 2021 12:39 PM UTC


Talk Python to Me

#311 Get inside the .git folder

These days Git is synonymous with source control itself. Rare are the current debates of whether to use git vs SVN vs some fossil like SourceSafe vs you name it. But do you know how Git works? What about it's internals? I'm sure you've seen a .git folder in your project's root. But to most folks, it's a black box. <br/> <br/> In this episode, you'll meet Rob Richardson. He's going pop the lid on that black box as we dive into git internals and the .git folder, among other things source control.<br/> <br/> <strong>Links from the show</strong><br/> <br/> <div><b>Rob's Site</b>: <a href="https://robrich.org/" target="_blank" rel="noopener">robrich.org</a><br/> <b>Rob on Twitter</b>: <a href="https://twitter.com/rob_rich" target="_blank" rel="noopener">@rob_rich</a><br/> <br/> <b>YouTube Live Stream Recording</b>: <a href="https://www.youtube.com/watch?v=gdY_RpY2oyU" target="_blank" rel="noopener">youtube.com</a><br/> <br/> <b>Talk at PWC</b>: <a href="https://pwc2021.loudswarm.com/session/definitive-deep-dive-git-folder" target="_blank" rel="noopener">loudswarm.com</a><br/> <b>Git Explorer App</b>: <a href="https://github.com/robrich/git-explorer" target="_blank" rel="noopener">github.com</a><br/> <b>Pre-commit framework</b>: <a href="https://pre-commit.com/" target="_blank" rel="noopener">pre-commit.com</a><br/> <b>.gitignore project</b>: <a href="https://github.com/github/gitignore" target="_blank" rel="noopener">github.com</a><br/> <b>git-hooks project</b>: <a href="https://www.npmjs.com/package/git-hooks" target="_blank" rel="noopener">npmjs.com</a><br/> <b>Git Source Control</b>: <a href="https://git-scm.com/" target="_blank" rel="noopener">git-scm.com</a><br/> <b>SVN</b>: <a href="https://subversion.apache.org/" target="_blank" rel="noopener">subversion.apache.org</a><br/> <br/> <b>Oh My Posh Shell</b>: <a href="https://ohmyposh.dev/" target="_blank" rel="noopener">ohmyposh.dev</a><br/> <b>Oh My ZSH Shell</b>: <a href="https://ohmyz.sh/" target="_blank" rel="noopener">ohmyz.sh</a><br/> <br/> <b>Oh !*#! Git Site</b>: <a href="https://ohshitgit.com/" target="_blank" rel="noopener">oh*!#!git.com</a><br/> <b>Work-safe version</b>: <a href="https://dangitgit.com/en" target="_blank" rel="noopener">dangitgit.com</a><br/></div><br/> <strong>Sponsors</strong><br/> <br/> <a href='https://talkpython.fm/training'>Talk Python Training</a>

April 08, 2021 08:00 AM UTC


PyPy

PyPy v7.3.4: release of python 2.7 and 3.7

PyPy v7.3.4: release of python 2.7 and 3.7

The PyPy team is proud to release the version 7.3.4 of PyPy, which includes two different interpreters:

  • PyPy2.7, which is an interpreter supporting the syntax and the features of Python 2.7 including the stdlib for CPython 2.7.18+ (the + is for backported security updates)

  • PyPy3.7, which is an interpreter supporting the syntax and the features of Python 3.7, including the stdlib for CPython 3.7.10. We no longer refer to this as beta-quality as the last incompatibilities with CPython (in the re module) have been fixed.

We are no longer releasing a Python3.6 version, as we focus on updating to Python 3.8. We have begun streaming the advances towards this goal on Saturday evenings European time on https://www.twitch.tv/pypyproject. If Python3.6 is important to you, please reach out as we could offer sponsored longer term support.

The two interpreters are based on much the same codebase, thus the multiple release. This is a micro release, all APIs are compatible with the other 7.3 releases. Highlights of the release include binary Windows 64 support, faster numerical instance fields, and a preliminary HPy backend.

A new contributor (Ondrej Baranovič - thanks!) took us up on the challenge to get windows 64-bit support. The work has been merged and for the first time we are releasing a 64-bit Windows binary package.

The release contains the biggest change to PyPy's implementation of the instances of user-defined classes in many years. The optimization was motivated by the report of performance problems running a numerical particle emulation. We implemented an optimization that stores int and float instance fields in an unboxed way, as long as these fields are type-stable (meaning that the same field always stores the same type, using the principle of type freezing). This gives significant performance improvements on numerical pure-Python code, and other code where instances store many integers or floating point numbers.

There were also a number of optimizations for methods around strings and bytes, following user reported performance problems. If you are unhappy with PyPy's performance on some code of yours, please report an issue!

A major new feature is prelminary support for the Universal mode of HPy: a new way of writing c-extension modules to totally encapsulate PyObject*. The goal, as laid out in the HPy documentation and recent HPy blog post, is to enable a migration path for c-extension authors who wish their code to be performant on alternative interpreters like GraalPython (written on top of the Java virtual machine), RustPython, and PyPy. Thanks to Oracle and IBM for sponsoring work on HPy.

Support for the vmprof statistical profiler has been extended to ARM64 via a built-in backend.

Several issues exposed in the 7.3.3 release were fixed. Many of them came from the great work ongoing to ship PyPy-compatible binary packages in conda-forge. A big shout out to them for taking this on.

Development of PyPy takes place on https://foss.heptapod.net/pypy/pypy. We have seen an increase in the number of drive-by contributors who are able to use gitlab + mercurial to create merge requests.

The CFFI backend has been updated to version 1.14.5 and the cppyy backend to 1.14.2. We recommend using CFFI rather than C-extensions to interact with C, and using cppyy for performant wrapping of C++ code for Python.

As always, we strongly recommend updating to the latest versions. Many fixes are the direct result of end-user bug reports, so please continue reporting issues as they crop up.

You can find links to download the v7.3.4 releases here:

https://pypy.org/download.html

We would like to thank our donors for the continued support of the PyPy project. If PyPy is not quite good enough for your needs, we are available for direct consulting work. If PyPy is helping you out, we would love to hear about it and encourage submissions to our renovated blog site via a pull request to https://github.com/pypy/pypy.org

We would also like to thank our contributors and encourage new people to join the project. PyPy has many layers and we need help with all of them: PyPy and RPython documentation improvements, tweaking popular modules to run on PyPy, or general help with making RPython's JIT even better. Since the previous release, we have accepted contributions from 10 new contributors, thanks for pitching in, and welcome to the project!

If you are a python library maintainer and use C-extensions, please consider making a cffi / cppyy version of your library that would be performant on PyPy. In any case both cibuildwheel and the multibuild system support building wheels for PyPy.

What is PyPy?

PyPy is a Python interpreter, a drop-in replacement for CPython 2.7, 3.7, and soon 3.8. It's fast (PyPy and CPython 3.7.4 performance comparison) due to its integrated tracing JIT compiler.

We also welcome developers of other dynamic languages to see what RPython can do for them.

This PyPy release supports:

  • x86 machines on most common operating systems (Linux 32/64 bits, Mac OS X 64 bits, Windows 32/64 bits, OpenBSD, FreeBSD)

  • big- and little-endian variants of PPC64 running Linux,

  • s390x running Linux

  • 64-bit ARM machines running Linux.

PyPy does support ARM 32 bit processors, but does not release binaries.

What else is new?

For more information about the 7.3.4 release, see the full changelog.

Please update, and continue to help us make PyPy better.

Cheers, The PyPy team

April 08, 2021 05:53 AM UTC


Codementor

Online Job Support

Proxy job support provides the best job support for IT related works. We have a good ability and experts personality to complete our customer’s regular task. Our Online Job support team provide support on all the time zone. Our mission is to complete the job support queries from customers on punctually.

April 08, 2021 05:20 AM UTC

April 07, 2021


Mike Driscoll

Python’s with Statement and Context Managers

Python came out with a special new keyword several years ago in Python 2.5 that is known as the with statement. This new keyword allows a developer to create context managers. But wait! What’s a context manager? They are handy constructs that allow you to set something up and tear something down automatically. For example, you might want to open a file, write a bunch of stuff to it and then close it. This is probably the classic example of a context manager. In fact, Python creates one automatically for you when you open a file using the with statement:

with open(path, 'w') as f_obj:
    f_obj.write(some_data)

Back in Python 2.4, you would have to do it the old fashioned way:

f_obj = open(path, 'w')
f_obj.write(some_data)
f_obj.close()

The way this works under the covers is by using some of Python’s magic methods: __enter__ and __exit__. Let’s try creating your own context manager to demonstrate how this all works!

Creating a Context Manager class

Rather than rewrite Python’s open method here, you’ll create a context manager that can create a SQLite database connection and close it when it’s done. Here’s a simple example:

import sqlite3


class DataConn:
    """"""

    def __init__(self, db_name):
        """Constructor"""
        self.db_name = db_name

    def __enter__(self):
        """
        Open the database connection
        """
        self.conn = sqlite3.connect(self.db_name)
        return self.conn

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Close the connection
        """
        self.conn.close()
        if exc_val:
            raise

if __name__ == '__main__':
    db = '/home/mdriscoll/test.db'
    with DataConn(db) as conn:
        cursor = conn.cursor()

In the code above, you created a class that takes a path to an SQLite database file. The __enter__ method executes automatically where it creates and returns the database connection object. Now that you have that, you can create a cursor and write to the database or query it. When you exit the with statement, it causes the __exit__ method to execute and that closes the connection.

Let’s try creating a context manager using another method.

Creating a Context Manager using contextlib

Python 2.5 not only added the with statement, but it also added the contextlib module. This allows you to create a context manager using contextlib’s contextmanager function as a decorator.

Let’s try creating a context manager that opens and closes a file after all:

from contextlib import contextmanager

@contextmanager
def file_open(path):
    try:
        f_obj = open(path, 'w')
        yield f_obj
    except OSError:
        print("We had an error!")
    finally:
        print('Closing file')
        f_obj.close()

if __name__ == '__main__':
    with file_open('/home/mdriscoll/test.txt') as fobj:
        fobj.write('Testing context managers')

Here you import contextmanager from contextlib and decorate your file_open() function with it. This allows you to call file_open() using Python’s with statement. In your function, you open the file and then yield it out so the calling function can use it.

Once the with statement ends, control returns back to file_open() and it continues with the code following the yield statement. That causes the finally statement to execute, which closes the file. If you happen to have an OSError while working with the file, it gets caught, and the finally statement still closes the file handler.

contextlib.closing()

The contextlib module comes with some other handy utilities. The first one is the closing class which will close the thing upon the completion of the code block. The Python documentation gives an example that’s similar to the following one:

from contextlib import contextmanager

@contextmanager
def closing(db):
    try:
        yield db.conn()
    finally:
        db.close()

Basically what you’re doing is creating a closing function that’s wrapped in a contextmanager. This is the equivalent of what the closing class does. The difference is that instead of a decorator, you can use the closing class itself in your with statement.

Here’s what that will look like:

from contextlib import closing
from urllib.request import urlopen

with closing(urlopen('http://www.google.com')) as webpage:
    for line in webpage:
        # process the line
        pass

In this example, you open a URL but wrap it with your closing class. This will cause the handle to the web page to be closed once you fall out of the with statement’s code block.

contextlib.suppress(*exceptions)

Another handy little tool is the suppress class which was added in Python 3.4. The idea behind this context manager utility is that it can suppress any number of exceptions. A common example is when you want to ignore the FileNotFoundError exception. If you were to write the following context manager, it wouldn’t work:

>>> with open('fauxfile.txt') as fobj:
        for line in fobj:
            print(line)

Traceback (most recent call last):
  Python Shell, prompt 4, line 1
builtins.FileNotFoundError: [Errno 2] No such file or directory: 'fauxfile.txt'

This context manager doesn’t handle this exception. If you want to ignore this error, then you can do the following:

from contextlib import suppress

with suppress(FileNotFoundError):
    with open('fauxfile.txt') as fobj:
        for line in fobj:
            print(line)

Here you import suppress and pass it the exception that you want to ignore, which in this case is the FileNotFoundError exception. If you run this code, nothing happens as the file does not exist, but an error is also not raised. It should be noted that this context manager is reentrant. This will be explained later on in this article.

contextlib.redirect_stdout / redirect_stderr

The contextlib library has a couple of neat tools for redirecting stdout and stderr that were added in Python 3.4 and 3.5 respectively. Before these tools were added, if you wanted to redirect stdout, you would do something like this:

path = '/path/to/text.txt'

with open(path, 'w') as fobj:
    sys.stdout = fobj
    help(sum)

With the contextlib module, you can now do the following:

from contextlib import redirect_stdout

path = '/path/to/text.txt'
with open(path, 'w') as fobj:
    with redirect_stdout(fobj):
        help(redirect_stdout)

In both of these examples, you are redirecting stdout to a file. When you call Python’s help(), instead of printing to stdout, it gets saved directly to the file. You could also redirect stdout to some kind of buffer or a text control type widget from a user interface toolkit like Tkinter or wxPython.

ExitStack

ExitStack is a context manager that will allow you to easily programmatically combine other context managers and cleanup functions. It sounds kind of confusing at first, so let’s take a look at an example from the Python documentation to help you understand this idea a bit better:

>>> from contextlib import ExitStack
>>> with ExitStack() as stack:
        file_objects = [stack.enter_context(open(filename))
            for filename in filenames]
                    ]

This code basically creates a series of context managers inside the list comprehension. The ExitStack maintains a stack of registered callbacks that it will call in reverse order when the instance is closed, which happens when you exit the bottom of the with statement.

There are a bunch of neat examples in the Python documentation for contextlib where you can learn about topics like the following:

You should check it out so you get a good feel for how powerful this class is.

Wrapping Up

Context managers are a lot of fun and come in handy all the time. I use them in my automated tests all the time for opening and closing dialogs, for example. Now you should be able to use some of Python’s built-in tools to create your own context managers. Be sure to take the time to read the Python documentation on contextlib as there are lots of additional information that is not covered in this chapter. Have fun and happy coding!

 

The post Python’s with Statement and Context Managers appeared first on Mouse Vs Python.

April 07, 2021 06:52 PM UTC


PyCharm

PyCharm 2021.1 Is Out!

Try our new out-of-the-box collaborative development tool, auto-import for module member completion, and enhanced WSL support.

PyCharm-2021-1

Download the new version

We’ve added quite a lot of new functionality in this release. Let’s focus on the “editor picks” first, from the PyCharm team:

In addition to those highlights, we’ve improved code insight, frontend development tools, and working with databases. For more details, please visit the release web page or browse the release notes to see all the new features we’ve added to PyCharm with this release.

Read on for more insight into the highlighted features, or upgrade to PyCharm 2021.1 and start using them right now!

Upgrade to PyCharm 2021.1

Faster indexing

Our new prebuilt indexes for the most popular Python interpreters have made standard library indexing much faster. The new approach to prebuilt indexes also helped us make the PyCharm installation file smaller.

WSL 2 support

You can now work in PyCharm with your project stored on the WSL filesystem without copying the project to your Windows file system.

pc-wsl-open-folder

Also, PyCharm now detects the WSL interpreter. If no WSL interpreter is configured for your project, PyCharm will look for system interpreters and set them as the default interpreter automatically.

What’s more, you can open any directory in \\wsl$ with PyCharm. If PyCharm detects any Python file in the directory, it will suggest creating a WSL-based interpreter. See the dedicated PyCharm Help page.

pc-wsl-terminal

Once the project is open, PyCharm Terminal will already be configured to run on the WSL. As for version control, you can use Git that is installed on your WSL instance.

PyCharm now allows you to use custom Linux distributions run on the WSL. PyCharm auto-detects these distributions and adds it to the Linux Distribution list. You don’t need to add extra pre-configuring – starting with 2021.1, PyCharm will do everything for you.

Although debugging is fully supported for WSL 2, users still need to do a few things manually to configure the debugger to work with WSL 2. Thanks to the feedback from the PyCharm community (PY-44230), we’ve created a set of simple instructions on how to enable debugging for WSL configurations.

Auto import on module member completion

PyCharm now automatically adds an import statement when you refer to any module or package name in Python code and you invoke code completion with the list of available module members.

Auto-import on code completion is also applied to some popular package name aliases, such as np for NumPy or pd for pandas. You can learn more about autocompletion here.

pc-module-auto-import

Tool window for Python packages

You can install a new Python package or browse through all the packages available for download using the new Tool window, without having to leave the editor. This window is enabled by default, and you can find it at the bottom of the IDE together with the Terminal and Python Console. You can open it using the main menu at any time: View | Tool Windows | Python Packages.

Python-packages

The Python Packages tool window shows the installed packages and the packages that are available in the PyPI repository. Use the Search field to filter the list of the available packages. You can find a detailed description of how to use the Tool window to search packages in the Installing and Upgrading packages in PyCharm section of the documentation.

Code With Me for collaborative development

Code With Me connects remote teams in a feature-rich collaborative environment and helps you boost productivity, no matter where your team members are based. The essential IDE features, such as smart code insight, navigation, remote unit testing, and debugging, are available for participants during collaborative sessions. Teams can simultaneously edit code, track changes with diff previews, and follow each other in the shared project.

code-with-me

The embedded audio and video calls, along with chat messaging, will help software developers discuss the code, share their knowledge, and cooperate even more efficiently.

DOWNLOAD PYCHARM 2021.1

Those are the major features of this release. To learn about other important features included in PyCharm 2021.1, please head on to the What’s New page. And if you’d like to check out all the enhancements and changes in v2021.1, look through the release notes.

Do not hesitate to submit a bug request using our bug tracker.

Happy developing!

April 07, 2021 02:07 PM UTC


Real Python

The k-Nearest Neighbors (kNN) Algorithm in Python

In this tutorial, you’ll get a thorough introduction to the k-Nearest Neighbors (kNN) algorithm in Python. The kNN algorithm is one of the most famous machine learning algorithms and an absolute must-have in your machine learning toolbox. Python is the go-to programming language for machine learning, so what better way to discover kNN than with Python’s famous packages NumPy and scikit-learn!

Below, you’ll explore the kNN algorithm both in theory and in practice. While many tutorials skip the theoretical part and focus only on the use of libraries, you don’t want to be dependent on automated packages for your machine learning. It’s important to learn about the mechanics of machine learning algorithms to understand their potential and limitations.

At the same time, it’s essential to understand how to use an algorithm in practice. With that in mind, in the second part of this tutorial, you’ll focus on the use of kNN in the Python library scikit-learn, with advanced tips for pushing performance to the max.

In this tutorial, you’ll learn how to:

  • Explain the kNN algorithm both intuitively and mathematically
  • Implement kNN in Python from scratch using NumPy
  • Use kNN in Python with scikit-learn
  • Tune hyperparameters of kNN using GridSearchCV
  • Add bagging to kNN for better performance

Free Bonus: Click here to get access to a free NumPy Resources Guide that points you to the best tutorials, videos, and books for improving your NumPy skills.

Basics of Machine Learning

To get you on board, it’s worth taking a step back and doing a quick survey of machine learning in general. In this section, you’ll get an introduction to the fundamental idea behind machine learning, and you’ll see how the kNN algorithm relates to other machine learning tools.

The general idea of machine learning is to get a model to learn trends from historical data on any topic and be able to reproduce those trends on comparable data in the future. Here’s a diagram outlining the basic machine learning process:

General Idea Behind of Machine Learning

This graph is a visual representation of a machine learning model that is fitted onto historical data. On the left are the original observations with three variables: height, width, and shape. The shapes are stars, crosses, and triangles.

The shapes are located in different areas of the graph. On the right, you see how those original observations have been translated to a decision rule. For a new observation, you need to know the width and the height to determine in which square it falls. The square in which it falls, in turn, defines which shape it is most likely to have.

Many different models could be used for this task. A model is a mathematical formula that can be used to describe data points. One example is the linear model, which uses a linear function defined by the formula y = ax + b.

If you estimate, or fit, a model, you find the optimal values for the fixed parameters using some algorithm. In the linear model, the parameters are a and b. Luckily, you won’t have to invent such estimation algorithms to get started. They’ve already been discovered by great mathematicians.

Once the model is estimated, it becomes a mathematical formula in which you can fill in values for your independent variables to make predictions for your target variable. From a high-level perspective, that’s all that happens!

Distinguishing Features of kNN

Now that you understand the basic idea behind machine learning, the next step is understanding why there are so many models available. The linear model that you just saw is called linear regression.

Linear regression works in some cases but doesn’t always make very precise predictions. That’s why mathematicians have come up with many alternative machine learning models that you can use. The k-Nearest Neighbors algorithm is one of them.

All these models have their peculiarities. If you work on machine learning, you should have a deep understanding of all of them so that you can use the right model in the right situation. To understand why and when to use kNN, you’ll next look at how kNN compares to other machine learning models.

kNN Is a Supervised Machine Learning Algorithm

The first determining property of machine learning algorithms is the split between supervised and unsupervised models. The difference between supervised and unsupervised models is the problem statement.

In supervised models, you have two types of variables at the same time:

  1. A target variable, which is also called the dependent variable or the y variable.
  2. Independent variables, which are also known as x variables or explanatory variables.

The target variable is the variable that you want to predict. It depends on the independent variables and it isn’t something that you know ahead of time. The independent variables are variables that you do know ahead of time. You can plug them into an equation to predict the target variable. In this way, it’s relatively similar to the y = ax + b case.

In the graph that you’ve seen before and the following graphs in this section, the target variable is the shape of the data point, and the independent variables are height and width. You can see the idea behind supervised learning in the following graph:

Read the full article at https://realpython.com/knn-python/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

April 07, 2021 02:00 PM UTC


Python for Beginners

Single Line and Multi Line Comments in Python

A comment is a piece of code that isn’t executed by the compiler or interpreter when the program is executed. Comments can only be read when we have access to the source code. Comments are used to explain the source code and to make the code more readable and understandable. In this article, we will see how to write single line and multi line comments using different methods in python.

What is a single line comment in python?

Single line comments are those comments which are written without giving a line break or newline in python. A python comment is written by initializing the text of comment with a # and terminates when the end of line is encountered. The following example shows a single line comment in a program where a function is defined to add a number and its square to a python dictionary as key value pair.


#This is a single line comment in python
def add_square_to_dict(x,mydict):
    a=x*x
    mydict[str(x)]=a
    return mydict

We can also add a single line comment after another statement.

#This is a single line comment in python
print("Pythonforbeginners.com") #This is also a python comment

What is a multi line comment?

As the name specifies, a multi line comment expands up to multiple lines. But python does not have syntax for multi line comments. We can implement multi line comments in python using single line comments or triple quoted python strings.

How to implement multi line comments using # sign?

To implement multi line comments using # sign, we can simply depict each line of a multi line comment as a single line comment. Then we can start each line by using # symbol and we can implement multi line comments.

#This is a multiline comment in python
#and expands to more than one line
print("Pythonforbeginners.com")

When writing multi line comments using # symbol, we can also start multi line comments after any python statement.

#This is a multiline comment in python
#and expands to more than one line
print("Pythonforbeginners.com") #This is also a python comment
#and it also expands to more than one line.

How to implement multi line comments using triple quoted strings?

Multi line strings in python can be used as multi line comments if they are not assigned to variables. When the string isn’t assigned to any variable, they are parsed and evaluated by the interpreter but no byte code is generated because no address can be assigned to the strings. Effectively the unassigned multi line string works as a multi line comment.  

"""This is 
a 
multiline comment in python
which expands to many lines"""

Here we have to keep in mind that the multi line comments are only string constants that have not been assigned to any variable. So they have to be properly intended unlike single line comments with # symbol so that syntax errors can be avoided.

Also, multi line comments which use triple quotes should always start with a newline which is not the case for a single line comment. 


#This is a multiline comment in python
#and expands to more than one line
"""This is 
a 
multiline comment in python
which expands to many lines"""
print("Pythonforbeginners.com") """This is not 
a 
multiline comment in python
and will cause syntax error"""

Conclusion

In this article, we have seen how to write single line and multi line comments in python. We have also seen how to write multi line comments using strings. Stay tuned for more informative articles.

The post Single Line and Multi Line Comments in Python appeared first on PythonForBeginners.com.

April 07, 2021 11:45 AM UTC


Learn PyQt

Create applications with QtQuick — Build modern applications with declarative QML

In previous tutorials we've used the Qt Widgets API for building our applications. This has been the standard method for building applications since Qt was first developed. However, Qt provides another API for building user interfaces: Qt Quick. This is a modern mobile-focused API for app development, with which you can create dynamic and highly customizable user interfaces.

QtQuick

Qt Quick uses a declarative scripting language -- the Qt Modeling Language (QML) -- to define user interfaces. With it you can build completely custom UIs, with dynamic graphical elements and fluid transitions and effects. UIs build with QML have more in common with mobile apps than traditional desktop applications, reflecting it's origin with Nokia, but Qt Quick can be used on all platforms supported by Qt.

QML syntax also supports embedded Javascript which can be used to handle application logic -- in simple applications the entire app can be implemented in the QML! But using PyQt/PySide you can also write your application code in Python and hook this up to your QML. This has the advantage of keeping your UI design (QML) and business logic (Python) implementation properly isolated, and gives you access to all the Python libraries to power the backend of your app.

Before starting this tutorial you will need to install PyQt or PySide, see the installation guides.

For building QML applications you can use PyQt5, PySide2, PyQt6 or PySide6. If using Qt 6 you will need v6.1 or later.

Getting started

In this tutorial we will be using PyQt/PySide with the Qt Quick/QML API. If you've used Qt Widgets before, many of the Qt Quick concepts will seem familiar. While QML does not make use of QtWidget classes, all the other parts of Qt (QtCore, QtGui, etc.) are still available.

Before we start writing out application, we can set up our project folder with the files we'll need in the right structure. You can also download a zip file containing these files.

Creating a “Hello World” app

Open up the main.py in your editor and add the following skeleton code. This is the bare minimum code required to load a QML file and display it using the QML application engine.

main.py

python
import sys

from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine


app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('./UI/main.qml')

sys.exit(app.exec())
python
import sys

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine


app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('./UI/main.qml')

sys.exit(app.exec_())
python
import sys

from PyQt6.QtGui import QGuiApplication
from PyQt6.QtQml import QQmlApplicationEngine


app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

sys.exit(app.exec())
python
import sys

from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine


app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

sys.exit(app.exec_())

The above code calls QGuiApplication and QQmlApplicationEngine Which will use QML instead of QtWidgets as the UI layer for the Qt Application. It then connects the UI layers quit function with the app’s main quit function. So both can close when the UI has been closed by the user. Next it loads the QML file as the QML code for the UI. The app.exec() starts the Qt event loop and launches the application, just as in Qt Widgets.

Here the call to app.exec() is wrapped inside sys.exit() to return the exit code to the calling process in case of errors, but this isn't strictly necessary.

Next, add the following code to the main.qml.

main.qml

qml
import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 600
    height: 500
    title: "HelloApp"

    Text {
        anchors.centerIn: parent
        text: "Hello World"
        font.pixelSize: 24
    }

}

The above code creates a Window with a width and height as specified, a title of HelloApp and a Text object that is centered in the parent (in this case the window). The text displayed is “Hello World”, with a pixel size of 24px.

The visible: true is very important, without that the UI will be created but will be invisible!

Once you've entered the above into the two files and save them, you can run it and see the result. You can run the code like any other Python script -- navigate into the folder containing the main.py script and run it using python (or python3 depending on your system).

shell
$ cd helloApp
$ python main.py

When the application launches you should see a window which looks like the following.

Hello World shown in an application

Success! We have a QML application, although it's very basic to start with. Next we'll modify the UI to make it a little more interesting and build towards a simple clock.

Updating the UI design

First lets add an image as a background.

Place this image in the folder we created earlier named images. This will be the background for our application window.

A simple background image with a gradient effect A simple background image with a gradient effect

If you like, you can substitute any other image you have. We'll be placing white text over it, so dark simple images will work better.

main.qml

qml
import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 400
    height: 600
    title: "Clock"

    Rectangle {
        anchors.fill: parent

        Image {
            anchors.fill: parent
            source: "./images/background.png" loading="lazy" width="564" height="1003"
            fillMode: Image.PreserveAspectCrop
        }

        Rectangle {
            anchors.fill: parent
            color: "transparent"

            Text {
                text: "16:38:33"
                font.pixelSize: 24
                color: "white"
            }

        }

    }

}

In this QML file we've defined our main application window using the ApplicationWindow object type. Within this we've defined an Image which holds our background image, filling the parent. The fillMode defines how the image will be sized. In this example we've set the image to fill the parent window using anchors.fill: parent while preserving aspect ratio and cropping. This ensures the image fills the window area, without being deformed. You can also set the image to follow the size of the parent using sourceSize, e.g.

qml
        Image {
            sourceSize.width: parent.width
            sourceSize.height: parent.height
            source: "./images/playas.jpg"
            fillMode: Image.PreserveAspectCrop
        }

This approach allows you some more control -- for example, you could scale an image to half the size of the parent window by dividing the sizes in two and use this to tile multiple images.

qml
        Image {
            sourceSize.width: parent.width/2
            sourceSize.height: parent.height/2
            source: "./images/background.png" loading="lazy" width="564" height="1003"
            fillMode: Image.PreserveAspectCrop
        }

Alongside the Image we've also defined a transparent Rectangle which also fills the window. Since the rectangle is defined alongside the Image you might think it would appear adjacent in the UI, however since there isn't a layout defined on the window the elements are stacked -- the Rectangle appears on top of the Image.

By default Rectangle objects have a white background.

Finally, inside the rectangle, we've defined a Text object with the text "16:38:33" to mock up a standard time display.

If you run the app now, the text will appear at the top-left corner of our application window.

shell
$ python main.py

By default text appears in the top left By default text appears in the top left

Let's move it somewhere else -- down to the bottom-left, with some margins to make it look nicer. In your QML code, update the Text object to include position anchors for the Text and change the size and color of the font.

main.qml

qml
            Text {
                anchors {
                    bottom: parent.bottom
                    bottomMargin: 12
                    left: parent.left
                    leftMargin: 12
                }
                text: "16:38:33"
                font.pixelSize: 48
                color: "white"
            }

Run the application again as before.

shell
$ python main.py

You will see the text has now moved to the bottom left.

Application window with text in the bottom left Application window with text in the bottom left

So far, our time display is just a fixed text string -- it doesn't update, and unless you run it at the right time, it's going to be wrong. Not the most useful of clocks! Next we'll add some Python code to get the current system time and update our clock display automatically.

Getting the time from Python

The Python standard library provides functions for handling time and date, including a number of options for getting the current time. For example, the Python function time.gmtime() provides a struct containing the current GMT time, while time.localtime() will give the time in your current local timezone.

Once you have a time struct you can pass this to the time.strftime() function to get a properly formatted string. The strftime function accepts two arguments -- first a time format string, and second the time struct to use. The time format string uses tokens such as %H to place specific parts of the time date in a specific format.

For example, if you enter the following in a Python shell you'll get the current GMT (UTC) time output.

python
from time import strftime, gmtime
strftime("%H:%M:%S", gmtime())

The %H, %M and %S tokens tell strftime to insert the hours (24 hour, zero padded), minutes (zero padded) and seconds (zero padded) into the string.

You can read more about format codes for strftime in the Python documentation.

For local time, you can use the localtime method instead of gmtime.

python
from time import strftime, localtime
strftime("%H:%M:%S", localtime())

This adjusts to your computers local time settings and should output the same time displayed on your computer's clock.

If you're used to working with datetime objects, every datetime has a .strftime() method, which uses the same format strings and returns the same output. For example, the following will give the same output as the localtime example above.

python
from time import strftime
from datetime import datetime
datetime.now().strftime("%H:%M:%S")

Updating our app time display

To pass our formatted time string from Python to QML we can use QML properties. First, let's define a property on our QML ApplicationWindow called currTime. Update your QML code in main.qml as follows:

main.qml

qml
...
ApplicationWindow {
    ...
    title: "Clock"
    property string currTime: "00:00:00"

    ...

The ... marks indicate where existing code should be left as it is.

Next, modify the text object to use the currTime property as its text value. When the currTime property is modified the text label will update automatically (along with any other places it is used).

main.qml

qml
...
            Text {
                ...
                text: currTime  // used to be; text: "16:38:33"
                font.pixelSize: 48
                color: "white"
            }

...

Finally, we need to send out curr_time variable from our Python code through to QML. Modified the Python code to add the time formatting code, using localtime() and then setting this property onto the QML object. The following code will set the QML property currTime to value of the Python variable curr_time.

main.py

python
import sys

from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

# Pass the current time to QML.
curr_time = strftime("%H:%M:%S", localtime())
engine.rootObjects()[0].setProperty('currTime', curr_time)

sys.exit(app.exec())
python
import sys

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

# Pass the current time to QML.
curr_time = strftime("%H:%M:%S", localtime())
engine.rootObjects()[0].setProperty('currTime', curr_time)

sys.exit(app.exec_())
python
import sys

from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

# Pass the current time to QML.
curr_time = strftime("%H:%M:%S", localtime())
engine.rootObjects()[0].setProperty('currTime', curr_time)

sys.exit(app.exec())
python
import sys

from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

# Pass the current time to QML.
curr_time = strftime("%H:%M:%S", localtime())
engine.rootObjects()[0].setProperty('currTime', curr_time)

sys.exit(app.exec_())

The code engine.rootObjects()[0] gets all the root objects from the QML engine as a list. Our ApplicationWindow object is a root object because it appears at the top of the hierarchy. Next we use [0] to select the first item in that list -- in our case, there is only one item, our ApplicationWindow and that is what is returned. The .setProperty method is then called on that object.

If you run the application now, you should see the correct time displayed in the window. This means the time will be correct when the application starts -- try closing it and re-running it to see the time update. But you'll notice that the time doesn't update yet -- we'll do that next.

The correct time (at least it was when I took the screenshot) The correct time (at least it was when I took the screenshot)

Updating the time using timers

To update the timer we need to run our time fetching and formatting code on a regular interval (every second). There are two options for implementing this

  1. using a timer which fires every 1 second triggering our time method
  2. using a long-running thread, which calculates the time with a delay (sleep) between each update

In Qt timers are handled on the GUI thread main loop, meaning that each time the timer is triggered the GUI is blocked while the function is executed. If that function is long running this can become noticeable in the UI. In that case, using a thread makes more sense. But here, our time fetching and formatting code is very quick -- there will be no noticeable delay. For that reason, in this example we'll use a simple timer.

setProperty

Based on the code we have so far, the simplest approach to updating the time automatically is to just take our update code, wrap it inside a function and then call that function repeatedly using a timer. The following code shows this approach in action, using a QTimer with an interval of 1000 msecs (1 second).

main.py

python
import sys

from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QTimer

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

def update_time():
    # Pass the current time to QML.
    curr_time = strftime("%H:%M:%S", localtime())
    engine.rootObjects()[0].setProperty('currTime', curr_time)

timer = QTimer()
timer.setInterval(1000)  # msecs 1000 = 1 sec
timer.timeout.connect(update_time)
timer.start()

sys.exit(app.exec())
python
import sys

from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QTimer

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

def update_time():
    # Pass the current time to QML.
    curr_time = strftime("%H:%M:%S", localtime())
    engine.rootObjects()[0].setProperty('currTime', curr_time)

timer = QTimer()
timer.setInterval(1000)  # msecs 1000 = 1 sec
timer.timeout.connect(update_time)
timer.start()

sys.exit(app.exec_())
python
import sys

from PyQt6.QtGui import QGuiApplication
from PyQt6.QtQml import QQmlApplicationEngine
from PyQt6.QtCore import QTimer

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

def update_time():
    # Pass the current time to QML.
    curr_time = strftime("%H:%M:%S", localtime())
    engine.rootObjects()[0].setProperty('currTime', curr_time)

timer = QTimer()
timer.setInterval(1000)  # msecs 1000 = 1 sec
timer.timeout.connect(update_time)
timer.start()

update_time() # initial startup

sys.exit(app.exec())
python
import sys

from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtCore import QTimer

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

def update_time():
    # Pass the current time to QML.
    curr_time = strftime("%H:%M:%S", localtime())
    engine.rootObjects()[0].setProperty('currTime', curr_time)

timer = QTimer()
timer.setInterval(1000)  # msecs 1000 = 1 sec
timer.timeout.connect(update_time)
timer.start()

update_time() # initial startup

sys.exit(app.exec_())

If you run this you'll see the time updating correctly.

You may also notice that when the application is first run the time displays as '00:00:00' (the default value) for a second. That is because the UI is rendered before the first interval timer executes. You can avoid this by adding a call to update_time() just before app.exec() is called, e.g.

python
update_time() # initial startup
sys.exit(app.exec())
python
update_time() # initial startup
sys.exit(app.exec_())

Now, when the app launches it will be showing the correct time immediately.

Using signals

While this approach of setting properties from the Python code works well for this small example it's not ideal as your applications grow in size. By hooking your Python code to change specific properties in your QML you are tying your Python code to the structure of the UI. That makes it easy to break things when restructuring your applications. Just like in the Qt Widgets API you can use Qt signals to avoid this problem: your code can emit signals without needing to know where they will be received, or how they will be used -- and you can even hook a single signal up to multiple receivers. This keeps your logic and UI code nicely decoupled.

If you're not familiar with Qt signals, take a look at our Signals, Slots & Events tutorials.

Let's rework our example to make use of Qt signals in Python & QML to achieve the same result.

First we must define our signals in the main.py file. Signals can only be defined on objects that are subclassed from QObject so we'll need to implement a small class. This is also a logical place to put our time-handling code to keep things nicely self-contained. We'll also define our signal for passing the current time to QML.

Multiple signals can be handled under a single QObject class and it often makes sense to use a single class for simplicity.

main.py

python
import sys

from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QTimer, QObject, pyqtSignal

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')


class Backend(QObject):

    updated = pyqtSignal(str, arguments=['time'])

    def __init__(self):
        super().__init__()

        # Define timer.
        self.timer = QTimer()
        self.timer.setInterval(1000)  # msecs 1000 = 1 sec
        self.timer.timeout.connect(self.update_time)
        self.timer.start()

    def update_time(self):
        # Pass the current time to QML.
        curr_time = strftime("%H:%M:%S", localtime())
        self.updated.emit(curr_time)


# Define our backend object, which we pass to QML.
backend = Backend()

engine.rootObjects()[0].setProperty('backend', backend)

# Initial call to trigger first update. Must be after the setProperty to connect signals.
backend.update_time()

sys.exit(app.exec())
python
import sys

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QTimer, QObject, Signal

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')

class Backend(QObject):

    updated = Signal(str, arguments=['time'])

    def __init__(self):
        super().__init__()

        # Define timer.
        self.timer = QTimer()
        self.timer.setInterval(1000)  # msecs 1000 = 1 sec
        self.timer.timeout.connect(self.update_time)
        self.timer.start()

    def update_time(self):
        # Pass the current time to QML.
        curr_time = strftime("%H:%M:%S", localtime())
        self.updated.emit(curr_time)


# Define our backend object, which we pass to QML.
backend = Backend()

engine.rootObjects()[0].setProperty('backend', backend)

# Initial call to trigger first update. Must be after the setProperty to connect signals.
backend.update_time()

sys.exit(app.exec_())
python
import sys

from PyQt6.QtGui import QGuiApplication
from PyQt6.QtQml import QQmlApplicationEngine
from PyQt6.QtCore import QTimer, QObject, pyqtSignal

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')


class Backend(QObject):

    updated = pyqtSignal(str, arguments=['time'])

    def __init__(self):
        super().__init__()

        # Define timer.
        self.timer = QTimer()
        self.timer.setInterval(1000)  # msecs 1000 = 1 sec
        self.timer.timeout.connect(self.update_time)
        self.timer.start()

    def update_time(self):
        # Pass the current time to QML.
        curr_time = strftime("%H:%M:%S", localtime())
        self.updated.emit(curr_time)


# Define our backend object, which we pass to QML.
backend = Backend()

engine.rootObjects()[0].setProperty('backend', backend)

# Initial call to trigger first update. Must be after the setProperty to connect signals.
backend.update_time()

sys.exit(app.exec())
python
import sys

from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtCore import QTimer, QObject, Signal

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')


class Backend(QObject):

    updated = Signal(str, arguments=['time'])

    def __init__(self):
        super().__init__()

        # Define timer.
        self.timer = QTimer()
        self.timer.setInterval(1000)  # msecs 1000 = 1 sec
        self.timer.timeout.connect(self.update_time)
        self.timer.start()

    def update_time(self):
        # Pass the current time to QML.
        curr_time = strftime("%H:%M:%S", localtime())
        self.updated.emit(curr_time)


# Define our backend object, which we pass to QML.
backend = Backend()

engine.rootObjects()[0].setProperty('backend', backend)

# Initial call to trigger first update. Must be after the setProperty to connect signals.
backend.update_time()

sys.exit(app.exec_())

While this looks like a lot of changes, the majority of the code is exactly the same, just reorganized to put everything under the container class. Everything in __init__ will be run when we create an instance of the Backend class using backend = Backend().

The signal definition (repeated below) creates a signal which accepts a single parameter -- a string. This will be sent with the signal to the receivers. The arguments= parameter is used to define the names under which the arguments will be known in QML (if using keyword arguments).

python
    updated = pyqtSignal(str, arguments=['time'])
python
    updated = Signal(str, arguments=['time'])

You'll also notice that we pass our backend object through to QML. This allows the signal we've just implemented to be used from the QML code and hooked up to an appropriate target.

python
engine.rootObjects()[0].setProperty('backend', backend)

As before we need to implement the property in QML which these will set. Previously when defining our property to receive the formatted time string, we used a string type. This isn't appropriate for the Backend object, as it's not a string. To receive the Backend object (which is a QObject) from Python we need to use the QtObject type.

main.qml

qml
...
property string currTime: "00:00:00"
property QtObject backend
...

There are not that many types. QML converts python base types into bool, int, double, string, list, QtObject and var. The var type is a generic handler which can handle any Python type.

To receive the signal itself, we need to define a Connections object, setting it's target as our backend property (in QML).

main.qml

qml
ApplicationWindow {
    ...

    Connections {
        target: backend
    }

    ...
}

We can now implement any other logic we link inside this Connections object to handle the signals on the backend object. Let's create a signal handler to handle our updated signal. Signal handlers are automatically named using the capitalized form of the signal name, preceded by lowercase on. Underscores and existing capitalization are ignored.

Python name QML name
mySignal onMySignal
mysignal onMysignal
my_signal onMy_signal

main.qml

qml
ApplicationWindow {
    ...

    Connections {
    target: backend

    function onUpdated(msg) {
        currTime = msg;
    }

    ...
}

The above code shows the signal handler for the updated signal, named onUpdated. This receives the current time as a string (named msg) and sets that onto the QML property currTime. As before, setting this property automatically updates the associated text label.

If you run the application now, you'll see the time updating exactly the same as before!

We could replace the Python time formatting with formatting code in Javascript inside QML if we wanted and send a timestamp as a signal. In fact, you can get the time and define timers in QML too!

Removing the window decorations

To create a desktop-widget like application you can hide the window decorations on your QML app. This removes the title bar and buttons for closing/minimizing the app. However, you can still close the window from the taskbar if you need to. Make the following changes to the top of the QML file, setting the flags property and positioning the widget into the bottom right of the display.

main.qml

qml
...
ApplicationWindow {
    visible: true
    width: 400
    height: 600
    x: screen.desktopAvailableWidth - width - 12
    y: screen.desktopAvailableHeight - height - 48
    title: "Clock"
    flags: Qt.FramelessWindowHint | Qt.Window
...

The code sets x, y for the window and adds the flag Qt.Window to make the window frameless. The Qt.Window flag ensures that even though the window is frameless, we still get an entry on the taskbar. Run it, and you will see the window we've created.

The final view with the updating clock and no window decorations The final view with the updating clock and no window decorations

In the next tutorial we'll expand on this simple clock by using image manipulations, transitions and animations to build a fully-functional analog clock.

The complete final code

Below is the complete final code for PyQt5, PySide2, PyQt6 and PySide6.

main.py

python
import sys

from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QTimer, QObject, pyqtSignal

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')


class Backend(QObject):

    updated = pyqtSignal(str, arguments=['time'])

    def __init__(self):
        super().__init__()

        # Define timer.
        self.timer = QTimer()
        self.timer.setInterval(1000)  # msecs 1000 = 1 sec
        self.timer.timeout.connect(self.update_time)
        self.timer.start()

    def update_time(self):
        # Pass the current time to QML.
        curr_time = strftime("%H:%M:%S", localtime())
        self.updated.emit(curr_time)


# Define our backend object, which we pass to QML.
backend = Backend()

engine.rootObjects()[0].setProperty('backend', backend)

# Initial call to trigger first update. Must be after the setProperty to connect signals.
backend.update_time()

sys.exit(app.exec())
python
import sys

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QTimer, QObject, Signal

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')


class Backend(QObject):

    updated = Signal(str, arguments=['time'])

    def __init__(self):
        super().__init__()

        # Define timer.
        self.timer = QTimer()
        self.timer.setInterval(1000)  # msecs 1000 = 1 sec
        self.timer.timeout.connect(self.update_time)
        self.timer.start()

    def update_time(self):
        # Pass the current time to QML.
        curr_time = strftime("%H:%M:%S", localtime())
        self.updated.emit(curr_time)


# Define our backend object, which we pass to QML.
backend = Backend()

engine.rootObjects()[0].setProperty('backend', backend)

# Initial call to trigger first update. Must be after the setProperty to connect signals.
backend.update_time()

sys.exit(app.exec())
python
import sys

from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QTimer, QObject, pyqtSignal

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')


class Backend(QObject):

    updated = pyqtSignal(str, arguments=['time'])

    def __init__(self):
        super().__init__()

        # Define timer.
        self.timer = QTimer()
        self.timer.setInterval(1000)  # msecs 1000 = 1 sec
        self.timer.timeout.connect(self.update_time)
        self.timer.start()

    def update_time(self):
        # Pass the current time to QML.
        curr_time = strftime("%H:%M:%S", localtime())
        self.updated.emit(curr_time)


# Define our backend object, which we pass to QML.
backend = Backend()

engine.rootObjects()[0].setProperty('backend', backend)

# Initial call to trigger first update. Must be after the setProperty to connect signals.
backend.update_time()

sys.exit(app.exec())
python
import sys

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QTimer, QObject, Signal

from time import strftime, localtime

app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
engine.load('main.qml')


class Backend(QObject):

    updated = Signal(str, arguments=['time'])

    def __init__(self):
        super().__init__()

        # Define timer.
        self.timer = QTimer()
        self.timer.setInterval(1000)  # msecs 1000 = 1 sec
        self.timer.timeout.connect(self.update_time)
        self.timer.start()

    def update_time(self):
        # Pass the current time to QML.
        curr_time = strftime("%H:%M:%S", localtime())
        self.updated.emit(curr_time)


# Define our backend object, which we pass to QML.
backend = Backend()

engine.rootObjects()[0].setProperty('backend', backend)

# Initial call to trigger first update. Must be after the setProperty to connect signals.
backend.update_time()

sys.exit(app.exec_())

main.qml

qml
import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 400
    height: 600
    x: screen.desktopAvailableWidth - width - 12
    y: screen.desktopAvailableHeight - height - 48
    title: "Clock"
    flags: Qt.FramelessWindowHint | Qt.Window
    property string currTime: "00:00:00"
    property QtObject backend

    Rectangle {
        anchors.fill: parent

        Image {
            sourceSize.width: parent.width
            sourceSize.height: parent.height
            source: "./images/background.png" loading="lazy" width="564" height="1003"
            fillMode: Image.PreserveAspectCrop
        }

        Rectangle {
            anchors.fill: parent
            color: "transparent"


            Text {
                anchors {
                    bottom: parent.bottom
                    bottomMargin: 12
                    left: parent.left
                    leftMargin: 12
                }
                text: currTime  // used to be; text: "16:38:33"
                font.pixelSize: 48
                color: "white"
            }

        }

    }

    Connections {
        target: backend

        function onUpdated(msg) {
            currTime = msg;
        }
    }

}

Now you have your basic QML application, you should experiment with customizing and changing the behavior. Try changing the background image, modifying the text color or sending different (or multiple bits) of information from Python to your app.

See the complete PyQt5 tutorial, from first steps to complete applications with Python & Qt5.

April 07, 2021 11:00 AM UTC


Python Insider

Python 3.10.0a7 is now available for testing

Brrrrr… do you feel that? That’s the chill of beta freeze coming closer. Meanwhile, your friendly CPython release team doesn’t rest even on holidays and we have prepared a shiny new release for you: Python 3.10.0a7.

Get the new release here:

https://www.python.org/downloads/release/python-3100a7/

Python 3.10.0a7

Release Date: April 5, 2021

This is an early developer preview of Python 3.10

Major new features of the 3.10 series, compared to 3.9

Python 3.10 is still in development. This release, 3.10.0a7 is the last of seven planned alpha releases. Alpha releases are intended to make it easier to test the current state of new features and bug fixes and to test the release process. During the alpha phase, features may be added up until the start of the beta phase (2021-05-03) and, if necessary, may be modified or deleted up until the release candidate phase (2021-10-04). Please keep in mind that this is a preview release and its use is not recommended for production environments.

Many new features for Python 3.10 are still being planned and written. Among the new major new features and changes so far:

The next pre-release of Python 3.10 will be 3.10.0b1 ( the first beta release and feature freeze ), currently scheduled for Monday, 2021-05-03.

More resources

And now for something completely different

In physics, the twin paradox is a thought experiment in special relativity involving identical twins, one of whom makes a journey into space in a high-speed rocket and returns home to find that the twin who remained on Earth has aged more. This result appears puzzling because each twin sees the other twin as moving, and so, as a consequence of an incorrect and naive application of time dilation and the principle of relativity, each should paradoxically find the other to have aged less. However, this scenario can be resolved by realising that the travelling twin is undergoing acceleration, which makes him a non-inertial observer. In both views, there is no symmetry between the spacetime paths of the twins. Therefore, the twin paradox is not a paradox in the sense of a logical contradiction.

We hope you enjoy those new releases!

Thanks to all of the many volunteers who help make Python Development and these releases possible! Please consider supporting our efforts by volunteering yourself or through organization contributions to the Python Software Foundation.

Your friendly release team,
Pablo Galindo Salgado @pablogsal
Ned Deily @nad
Steve Dower @steve.dower

April 07, 2021 10:41 AM UTC


EuroPython

Presenting our EuroPython 2021 logo

Over the last couple of weeks, we have worked with our designer Jessica Peña to come up with a logo which reflects both our desire to come together online during the pandemic and shows how well our community is interconnected around the world.

Here's our brand new logo for EuroPython 2021 Online:

alt

Hope you like it 😃

We will soon make EuroPython 2021 merchandise available with the new logo in our EuroPython merch shop, so you can order t-shirts, sweatshirts, caps and mugs to show your support and love for the conference.

Enjoy,
EuroPython 2021 Team
EuroPython Society
https://www.europython-society.org/

April 07, 2021 10:17 AM UTC


Abhijeet Pal

Creating Custom Model Validation In Django

In this tutorial, we will learn how to create custom model validators using Django. Understanding The Problem Django models come with their own built-in validations, that we put while creating ... Read more

The post Creating Custom Model Validation In Django appeared first on Django Central.

April 07, 2021 08:46 AM UTC


Python Bytes

#228 Supreme Court decides API copyright battle

<p><strong>Watch the live stream:</strong></p> <a href='https://www.youtube.com/watch?v=IpHNmIe1g20' style='font-weight: bold;'>Watch on YouTube</a><br> <br> <p><strong>About the show</strong></p> <p>Sponsored by us! Support our work through:</p> <ul> <li>Our <a href="https://training.talkpython.fm/"><strong>courses at Talk Python Training</strong></a></li> <li><a href="https://pragprog.com/titles/bopytest/python-testing-with-pytest/"><strong>pytest book</strong></a></li> <li><a href="https://www.patreon.com/pythonbytes"><strong>Patreon Supporters</strong></a></li> </ul> <p><strong>Special guest</strong> </p> <ul> <li><a href="https://twitter.com/guyroyse"><strong>Guy Royse</strong></a></li> </ul> <p><strong>Brian #1:</strong> <a href="https://antonz.org/python-packaging/"><strong>How to make an awesome Python package in 2021</strong></a></p> <ul> <li>Anton Zhiyanov, <a href="https://twitter.com/ohmypy">@ohmypy</a></li> <li>Also thanks John Mitchell, <a href="https://twitter.com/JohnTellsAll">@JohnTellsAll</a> for posting about it.</li> <li>Great writing taking you through everything in a sane order. <ul> <li>Stubbing a project</li> <li>with just <code>.gitignore</code> and a directory with a stub <code>__init__.py</code>.</li> <li>Test packaging and publishing</li> <li>use <code>flit init</code> to create initial pyproject.toml</li> <li>set up your <code>~/.pypirc</code> file</li> <li>publish to the test repo</li> <li>Make the real thing </li> <li>make an implementation</li> <li>publish</li> <li>Extras</li> <li>Adding <code>README.md</code> &amp; <code>CHANGELOG.md</code> and updating <code>pyproject.toml</code> to include <code>README.md</code> and a Python version selector.</li> <li>Adding linting and testing with pytest, tox, coverage, and others</li> <li>Building in the cloud with GH Actions, Codecov, Code Climate</li> <li>Adding badges</li> <li>Task automation with a Makefile</li> <li>Publishing to PyPI from a GH Action</li> </ul></li> <li>Missing (but possibly obvious): <ul> <li>GitHub project</li> <li>Checking your project name on PyPI early</li> </ul></li> <li>Super grateful for: <ul> <li>Do all of this early in the project</li> <li>Using <code>flit publish --repository pypitest</code> and spelling out how to set up a <code>~/.pypirc</code> file.</li> <li>Start to finish workflow</li> <li>Example project with all filled out project files</li> </ul></li> </ul> <p><strong>Michael #2:</strong> <a href="https://github.com/vchinnipilli/kubestriker"><strong>Kubestriker</strong></a> Kubestriker performs numerous in depth checks on kubernetes infra to identify the security misconfigurations</p> <ul> <li>Focuses on running in production and at scale.</li> <li><strong>kubestriker</strong> is Platform agnostic and works equally well across more than one platform such as self hosted <a href="https://kubernetes.io/">kubernetes</a>, <a href="https://aws.amazon.com/eks">Amazon EKS</a>, <a href="https://azure.microsoft.com/en-us/services/kubernetes-service/">Azure AKS</a>, <a href="https://cloud.google.com/kubernetes-engine">Google GKE</a> etc.</li> <li>Current Capabilities <ul> <li>Scans Self Managed and cloud provider managed kubernetes infra</li> <li>Reconnaissance phase checks for various services or open ports</li> <li>Performs automated scans incase of insecure, readwrite or readonly services are enabled</li> <li>Performs both authenticated scans and unauthenticated scans</li> <li>Scans for wide range of IAM Misconfigurations in the cluster</li> <li>Scans for wide range of Misconfigured containers</li> <li>Scans for wide range of Misconfigured Pod Security Policies</li> <li>Scans for wide range of Misconfigured Network policies</li> <li>Scans the privileges of a subject in the cluster</li> <li>Run commands on the containers and streams back the output</li> <li>Provides the endpoints of the misconfigured services</li> <li>Provides possible privilege escalation details</li> <li>Elaborative report with detailed explanation</li> </ul></li> </ul> <p><strong>Guy #3:</strong> <a href="https://wasmtime.dev/"><strong>wasmtime</strong></a></p> <ul> <li>WebAssembly runtime with support for: <ul> <li>Python, Rust, C, Go, .NET</li> <li>Documentation here: https://docs.wasmtime.dev/</li> </ul></li> <li>Supports <a href="https://wasi.dev/">WASI</a> (Web Assembly System Interface): <ul> <li>WASI supports IO operations—it does for WebAssembly what Node.js did for JavaScript</li> </ul></li> </ul> <p><strong>Brian #4:</strong> <a href="https://github.com/apps/depend-a-lot-bot"><strong>Depend-a-lot-bot</strong></a></p> <ul> <li>Anthony Shaw, <a href="https://twitter.com/anthonypjshaw">@anthonypjshaw</a></li> <li>A bot for GitHub that automatically approves + merges PRs from dependabot and PyUp.io when they meet certain criteria: <ul> <li>All the checks are passing</li> <li>The package is on a safe-list (see configuration)</li> </ul></li> <li>Example picture shows an auto approval and merge of a tox version update, showing “This PR looks good to merge automatically because tox is on the save-list for this repository”.</li> <li>Configuration in a .yml file. <em>I learned recently that most programming jobs that can be automated eventually devolve into configuring a yml file.</em></li> </ul> <p><strong>Michael #5:</strong> <a href="https://arstechnica.com/tech-policy/2021/04/supreme-court-sides-with-google-in-api-copyright-battle-with-oracle/"><strong>Supreme Court sides with Google in API copyright battle with Oracle</strong></a></p> <ul> <li>The Supreme Court has <a href="https://www.supremecourt.gov/opinions/20pdf/18-956_d18f.pdf">sided with Google</a> in its decade-long legal battle with Oracle over the copyright status of application programming interfaces. </li> <li>The ruling means that Google will not owe Oracle billions of dollars in damages. It also has big implications for the broader software industry</li> <li>The ruling heads off an expected wave of lawsuits over API copyrights.</li> <li>The case dates back to the creation of the Android platform in the mid-2000s.</li> <li>Google independently implemented the Java API methods, but to ensure compatibility, it copied Java's method names, argument types, and the class and package hierarchy.</li> <li>Over a decade of litigation, Google won twice at the trial court level, but each time, the <a href="https://law.justia.com/cases/federal/appellate-courts/cafc/13-1021/13-1021-2014-05-09.html">ruling</a> was <a href="https://arstechnica.com/tech-policy/2018/03/googles-use-of-the-java-api-packages-was-not-fair-appeals-court-rules/">overruled</a> by the Federal Circuit appeals court. The case finally <a href="https://arstechnica.com/tech-policy/2020/10/googles-supreme-court-faceoff-with-oracle-was-a-disaster-for-google/">reached the Supreme Court</a> last year.</li> <li>Writing for a six-justice majority, Justice Stephen Breyer held that Google's <strong>copying of the Java API calls was permissible under copyright's fair use doctrine</strong>.</li> </ul> <p><strong>Guy #6:</strong> <a href="https://oss.redislabs.com/redisai/"><strong>RedisAI</strong></a></p> <ul> <li>Module for Redis that add AI capabilities</li> <li>Turns Redis into a model server: <ul> <li>Supports TF, PyTorch, and <a href="https://onnx.ai/">ONNX</a> models</li> </ul></li> <li>Adds the TENSOR data type</li> <li>ONNX + Redis has positive architectural implications</li> </ul> <p><strong>Extras</strong></p> <p><strong>Michael</strong></p> <ul> <li><a href="https://gitforwindows.org/"><strong>git for Windows</strong></a></li> <li><a href="https://blog.jupyter.org/jupyterlab-3-0-is-out-4f58385e25bb"><strong>JupyterLab reaches v3</strong></a> (via via Allan Hansen)</li> <li><a href="https://gist.github.com/bskinn/cde59de17d00f8260197f6a866f6155d"><strong>Why not support Python letter by Brian Skinn</strong></a></li> <li><a href="https://www.djangoproject.com/weblog/2021/apr/06/django-32-released/"><strong>Django 3.2 is out &amp; is LTS</strong></a></li> <li><a href="https://blog.jetbrains.com/pycharm/2021/04/pycharm-2021-1/"><strong>PyCharm 2021.1</strong></a> just dropped with <a href="https://www.jetbrains.com/code-with-me/"><strong>Code With Me</strong></a></li> </ul> <p><strong>Brian</strong></p> <ul> <li><a href="https://pyfound.blogspot.com/2021/04/the-psf-is-hiring-developer-in.html">The PSF is hiring a Developer-in-Residence to support CPython!</a></li> </ul> <p><strong>Joke</strong> </p> <ul> <li><a href="https://twitter.com/anthonypjshaw/status/1377834823268458498"><strong>Vim Escape Rooms</strong></a></li> <li><a href="https://twitter.com/towernter/status/1379525329778262021?s=20"><strong>Happiness</strong></a> -</li> </ul>

April 07, 2021 08:00 AM UTC


Python Pool

How to Use Numpy cumsum() Function in Python

In the Numpy module, we have discussed many functions used to operate on the multidimensional array. Sometimes, we occur when we want to calculate the cumulative sum of the element present in the given array. In this tutorial, we will discuss the concept of the numpy cumsum() function, which is used when we want to compute the cumulative sum of array elements over a given axis.

What is the Numpy cumsum() function?

The Numpy cumsum() function is used when we need to compute the cumulative sum of array elements. If the axis is provided, it will return the array with the cumulative sum of elements along the axes. The cumulative sum of an array is like the first element, and the second element is the sum of the first element and the second element, the third element is the sum of the first element, the second element, and the third element, and so on.

Syntax of Numpy cumsum

numpy.cumsum(arr, axis=None, dtype=None, out=None)

Parameters

Return Value of Numpy cumsum

The return value is a new array unless out is specified, in which case it is returned.

Example of Numpy cumsum() function?

Here, we will be discussing how we can write the cumsum() function from the numpy library.

1. Taking only a variable as input

In this example, we will import the numpy library in python. We will not be taking input as an array. We will take an integer variable and then apply the numpy cumsum() function. Hence, we will see the conversion is done. Let us look at the example for understanding the concept in detail.

#taking input as a variable
#importing numpy library
import numpy as np

a = 15
print("input taken : ",a)
output = np.cumsum(a)
print("conversion done : ",output)

Output:

input taken :  15
conversion done :  [15]

Explanation:

2. Taking input as array

In this example, we will import the numpy module. We will then be taking input as an array and then applying the numpy cumsum() function. At last, we will see the cumulative sum of the array. Let us look at the example for understanding the concept in detail.

#taking input as an array
#importing numpy library
import numpy as np

arr = np.array([[1,2,3,4], [5,3,6,7]])
print("input taken : ",arr)
output = np.cumsum(arr)
print("Cumulative sum of array : ",output)

Output:

input taken :  [[1 2 3 4]
 [5 3 6 7]]
Cumulative sum of array :  [ 1  3  6 10 15 18 24 31]

Explanation:

3. Taking an array and axis as a parameter

In this example, we will import the numpy module. Then, we will be taking input as an array and applying the axis as 0 and 1 as a parameter. At last, we will see the output on both the axis and see the difference. Let us look at the example for understanding the concept in detail.

#taking input as an array and axis parameter
#importing numpy library
import numpy as np

arr = np.array([[1,2,3,4], [5,3,6,7]])
print("input taken : ",arr)
output = np.cumsum(arr, axis = 0)
print("Cumulative sum of array at axis = 0: ",output)
out = np.cumsum(arr, axis = 1)
print("Cumulative sum of array at axis = 1 : ",out)

Output:

input taken :  [[1 2 3 4]
 [5 3 6 7]]
Cumulative sum of array at axis = 0:  [[ 1  2  3  4]
 [ 6  5  9 11]]
Cumulative sum of array at axis = 1 :  [[ 1  3  6 10]
 [ 5  8 14 21]]

Explanation:

4. Taking an array and dtype as a parameter

In this example, we will import the numpy module. Then, we will be taking input as an array and dtype = float as the datatype of the array. At last, we will see the output. Let us look at the example for understanding the concept in detail.

#taking input as an array and dtype as a parameter
#importing numpy library
import numpy as np

arr = np.array([[1,2,3,4], [5,3,6,7]])
print("input taken : ",arr)
output = np.cumsum(arr, dtype = float)
print("Cumulative sum of array : ",output)

Output:

input taken :  [[1 2 3 4]
 [5 3 6 7]]
Cumulative sum of array :  [ 1.  3.  6. 10. 15. 18. 24. 31.]

Explanation:

Conclusion

In this tutorial, we have learned about the concept of the numpy cumsum() function. We got to know what is numpy cumsum() function and how the cumulative sum of the given array element is calculated. We have explained all the multiple ways through which we can calculate the cumulative sum. All the ways are explained with examples in detail. You can use any of the functions according to your choice and your requirement in the program.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

The post How to Use Numpy cumsum() Function in Python appeared first on Python Pool.

April 07, 2021 07:10 AM UTC

How to Use numpy trapz() Function in Python

In the Numpy module, we have discussed many functions used to operate on the multidimensional array. In this tutorial, we will discuss the concept of the numpy trapz() function used to integrate along the given axis using the composite trapezoidal rule.

What is numpy trapz() function?

The numpy trapz() function integrates along the given axis using the composite trapezoidal rule.

Syntax numpy trapz()

numpy.trapz(y, x = None, dx = 1.0, axis = -1)

Parameters

Return value

The return value is the float value and the definite integral as approximated by the trapezoidal rule.

Examples of numpy trapz() function

Here, we will be discussing how we can write the trapz() function from the numpy library.

1. Taking only y as a parameter

In this example, we will take y as an array-like input parameter and see the output. Let us look at the example for understanding the concept in detail.

#taking y as a parameter
#import numpy library
import numpy as np

y = [3,4,5,6]
output = np.trapz(y)
print("Output : ",output)

Output:

Output :  13.5

Explanation:

2. Taking x and y as parameter

In this example, we will be taking x and y both as an array-like input and perform the trapz() function. Hence, we will see the output. Let us look at the example for understanding the concept in detail.

#taking x and y as a parameter
#import numpy library
import numpy as np

y = [3,4,5,6]
x = [1,2,3,4]
output = np.trapz(y,x)
print("Output : ",output)

Output:

Output :  13.5

Explanation:

3. Taking y and dx as a parameter

In this example, we will be taking x as an array-like input and dx = 2 and perform the trapz() function. Hence, we will see the output. Let us look at the example for understanding the concept in detail.

#taking dx and y as a parameter
#import numpy library
import numpy as np

y = [3,4,5,6]

output = np.trapz(y,dx = 2)
print("Output : ",output)

Output:

Output :  27.0

Explanation:

4. Taking multidimensional array and axis as a parameter

In this example, we will be taking input as a multidimensional array with the help of arange() function in the numpy library. Then, we will set the axis as 0 and 1 and check the output on both the axis. Hence, you can see the output. Let us look at the example for understanding the concept in detail.

#taking dx and y as a parameter
#import numpy library
import numpy as np

a = np.arange(6).reshape(2, 3)
print(a)
print("\n")

output = np.trapz(a,axis = 0)
out = np.trapz(a,axis = 1)
print("Output with axis = 0 : ",output)
print("\n")
print("Output with axis = 1 : ",out)

Output:

[[0 1 2]
 [3 4 5]]


Output with axis = 0 :  [1.5 2.5 3.5]


Output with axis = 1 :  [2. 8.]

Explanation:

Faster alternative for Numpy trapz() function

The faster alternative for numpy trapz() function simps() function from scipy. simps() function is used to get the integration of y(x) using samples along the axis and composite simpson’s rule by using scipy.integrate.simps() method.

Let us look at the example for understanding the concept in detail.

import numpy as np
from scipy.integrate import simps

arr = np.array([5, 20, 4, 18, 20, 18, 3, 4])
output = simps(arr, dx=5)
print("output =", output)

Output:

output = 443.333333333

Conclusion

In this tutorial, we have discussed the concept of the numpy trapz() function. We have discussed what the numpy trapz() function is and when we use it. We have discussed how we can use the numpy trapz() function from the numpy library, with examples explained in detail. You can use any of the functions according to your choice and your requirement in the program.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

The post How to Use numpy trapz() Function in Python appeared first on Python Pool.

April 07, 2021 06:52 AM UTC