Thursday, February 3, 2022

Python for Beginners: Lambda Function In Python

While programming, we can face several situations where we need to use the same mathematical statement again and again. In such cases, using the same statement multiple times decreases the readability of our source code. In this article, we will discuss how we can use the lambda function in place of repetitive statements to remove such redundancy in our code in python.

What Is A Function In Python?

A function in python is a group of statements that are used to perform an atomic task. A function may accept zero or more arguments and may also return a value or an object. 

For instance, The square() function defined below takes a number as an input argument and returns its square as the output value. 

def square(n):
    return n ** 2

You may observe that we have defined the function using the def statement. On the contrary, A lambda function is defined using the lambda statement.

What Is A Lambda Function In Python? 

A lambda function is similar to a function in python. But it has some restrictions. 

A function in python can have multiple statements, while loop, if-else statement, and other programming constructs to perform any task. On the other hand, a lambda function can have only one statement.

We define a lambda function using the lambda keyword in python. The syntax for declaring a lambda function is as follows.

myFunction = lambda [arguments]: expression

Here, 

  • “myFunction” is the name of the lambda function that will be created using this statement.
  • “lambda” is the keyword used for defining the lambda function.
  • “Arguments” are the parameters of the lambda function. Here, we have kept “arguments” in a square bracket [] as a lambda function may or may not have input arguments.
  • “expression” is generally a mathematical expression or a function call like print().

How To Use A Lambda Function?

In python, we can use lambda functions to replace single-line mathematical statements. For example, we can create a lambda function that takes a number and calculates its square as follows.

square = lambda n: n ** 2
print("Square of 4 is: ", square(4))

Output:

Square of 4 is:  16

Another way to use a lambda function is to reduce the redundancy in code. For instance, suppose that you need to calculate the square of four numbers and print their squares one by one as follows.

def square(n):
    return n ** 2


print("Square of {} is:{} ".format(4, square(4)))
print("Square of {} is:{} ".format(3, square(3)))
print("Square of {} is:{} ".format(5, square(5)))
print("Square of {} is:{}".format(10, square(10)))

Output:

Square of 4 is:16 
Square of 3 is:9 
Square of 5 is:25 
Square of 10 is:100

 Here, you can observe that the print statements are causing the code to be redundant. In such cases, we can create a lambda function that takes the input arguments that are being passed to the format() method in the print function. Then, we can use this lambda function to remove the redundancy in the code as follows.

def square(n):
    return n ** 2


print_square = lambda x, y: print("Square of {} is:{} ".format(x, y))
print_square(4, square(4))
print_square(3, square(3))
print_square(5, square(5))
print_square(10, square(10))

Output:

Square of 4 is:16 
Square of 3 is:9 
Square of 5 is:25 
Square of 10 is:100 

Conclusion

In this article, we have discussed lambda functions in python. We also looked at some situations where we can use a lambda function in python. I would suggest you read this article on closures in python.

The post Lambda Function In Python appeared first on PythonForBeginners.com.



from Planet Python
via read more

Python GUIs: PyQt5 vs PyQt6: What are the differences, and is it time to upgrade?

If you are already developing Python GUI apps with PyQt5, you might be asking yourself whether it's time to upgrade to PyQt6 and use the latest version of the Qt library. In this article we'll look at the main differences between PyQt5 and PyQt6, benefits of upgrading and problems you might encounter when doing so.

Background

Qt is a GUI framework written in the C++ programming language created by Trolltech, now developed by The Qt Company. There are two Python bindings: PySide and PyQt. The former is developed in-house by The Qt Company while PyQt is developed independently by Riverbank Computing Ltd. The first version of PyQt6 was released on January 4th, 2021, just one month after the release of Qt6 itself.

For more information on the differences between the latest versions of the two bindings, take a look at PyQt6 vs PySide6.

Upgrading from PyQt5 to PyQt6

The upgrade path from PyQt5 to PyQt6 is fairly straightforward, with one main gotcha. For some applications, just renaming the imports from PyQt5 to PyQt6 will be enough to convert your application to work with the new library. For most however, you will need to account for changes in both PyQt and Qt itself.

Let’s get acquainted with a few differences between the two versions to know how to write code that works seamlessly with both. After reading this, you should be able to take any PyQt5 example online and convert it to work with PyQt6.

Enums

The change mostly likely to impact your projects is the removal of the short-form names for enum members. In PyQt6 all enum members must be named using their fully qualified names. This applies to all enums and flags, including those in the QtCore.Qt namespace. For example the Qt.Checked flag in PyQt6 becomes Qt.CheckState.Checked.

python
widget = QCheckBox("This is a checkbox")
widget.setCheckState(Qt.Checked)
python
widget = QCheckBox("This is a checkbox")
widget.setCheckState(Qt.CheckState.Checked)

There are too many updated values to mention them all here. But if you're converting a codebase you can usually just search online for the short-form and the longer form will be in the results.

The good news is that the change is backwards compatible: the fully-qualified names also work in PyQt5. So you can make the changes in your PyQt5 code before beginning the upgrade progress.

.exec() or .exec_()?

The .exec() method in Qt starts the event loop of your QApplication or dialog boxes. In Python 2.7, exec was a keyword, meaning that it could not be used as a variable name, a function name, or a method name. In earlier versions of PyQt the method was renamed as .exec_() – adding a trailing underscore – to avoid a conflict.

Python 3.0 removed the exec keyword, freeing up the name to be used. And since PyQt6 targets only Python 3.x versions, the underscored names have been removed. These were previously deprecated in PyQt5, and the .exec() method will work there too.

No more QResources

PyQt6 has removed support for Qt's Resource Framework. For packaging data files with your applications, you can use PyInstaller's data file support.

Differences in Qt6

In addition to the changes above there are many other minor changes that reflect underlying differences in Qt6 vs. Qt5 and aren't unique to PyQt itself.

QAction moved

In Qt6 the QAction class, which is used for creation toolbars and menus, has been moved from the QtWidgets to the QtGui module.

python
from PyQt5.QtWidgets import QAction
python
from PyQt6.QtGui import QAction

This may seem strange, but the move makes sense since actions can also be used in QML (non-widgets) applications.

High DPI Scaling

The high DPI (dots per inch) scaling attributes Qt.AA_EnableHighDpiScaling, Qt.AA_DisableHighDpiScaling and Qt.AA_UseHighDpiPixmaps have been deprecated because high DPI is enabled by default in PyQt6 and can’t be disabled.

QMouseEvent

QMouseEvent.pos() and QMouseEvent.globalPos() methods returning a QPoint object as well as QMouseEvent.x() and QMouseEvent.y() returning an int object have been deprecated – use QMouseEvent.position() and QMouseEvent.globalPosition() returning a QPointF object instead, so like QMouseEvent.position().x() and QMouseEvent.position().y().

Qt.MidButton has been renamed to Qt.MiddleButton

Platform specific

Finally, platform-specific methods in the QtWin and QtMac modules have been deprecated, in favor of using the native calls instead. In PyQt applications the only likely consequence of this will be the setCurrentProcessExplicitAppUserModelID call to set an application ID, for taskbar icon grouping on Windows.

python
try:
    # Include in try/except block if you're also targeting Mac/Linux
    from PyQt5.QtWinExtras import QtWin
    myappid = 'com.learnpyqt.examples.helloworld'
    QtWin.setCurrentProcessExplicitAppUserModelID(myappid)
except ImportError:
    pass
python
try:
    # Include in try/except block if you're also targeting Mac/Linux
    from ctypes import windll  # Only exists on Windows.
    myappid = 'mycompany.myproduct.subproduct.version'
    windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
except ImportError:
    pass

Miscellaneous

  • QDesktopWidget has been removed – use QScreen instead, which can be retrieved using QWidget.screen(), QGuiApplication.primaryScreen(), or QGuiApplication.screens().
  • .width() of QFontMetrics has been renamed to .horizontalAdvance().
  • .get() of QOpenGLVersionFunctionsFactory() has been recommended to be used instead of .versionFunctions() of QOpenGLContext() when obtaining any functions of the Open GL library.
  • QRegularExpression has replaced QRegExp.
  • QWidget.mapToGlobal() and QWidget.mapFromGlobal() now accept and return a QPointF object.

Missing modules

This isn’t a concern anymore, but when Qt6 was new, not all of the Qt modules had been ported yet, and so were not available in PyQt. If you needed any of these modules, the upgrade to PyQt6 was not previously workable. Fast forward to Qt 6.2 and PyQt 6.2, the good news is that all of those missing modules are now back, so you can upgrade without problems.

Is it time to upgrade?

Whether or not it's time to upgrade depends on your project. If you're starting out learning PyQt (or GUI programming in general), you may prefer to stick with PyQt5 for the time being as there are far more examples available online. While the differences are relatively minor, anything not working is confusing when you are learning something new. Anything you learn with PyQt5 will carry over to PyQt6, so you can switch once you're a bit more confident.

If you're starting a new project however, or are reasonably familiar with PyQt, I'd recommend jumping into PyQt6 now.

If you want to get started with PyQt6, the PyQt6 book is available with all code examples updated for this latest edition of PyQt.

PyQt Backwards compatibility

If you're developing software that's targeting both PyQt5 and PyQt6 you can use conditional imports to import the classes from whichever module is loaded.

python
try:
    from PyQt6 import QtWidgets, QtGui, QtCore # ...
except ImportError:
    from PyQt5 import QtWidgets, QtGui, QtCore # ...

If you add these imports to a file in the root of your project named qt.py. You can then, in your own code files import use from qt import QtWidgets and the available library will be imported automatically.

If you use the fully-qualified names for enums and exec() then many applications previously written in PyQt5 will work as-is. However, importing in this way won't work around any of the differences between Qt5 and Qt6 mentioned above. For that, we recommend using the QtPy library.

Universal compatibility

If you need to support all Python Qt libraries (PyQt5, PyQt6, PySide2, PySide6) or are dependent on features which have changed between versions of Qt, then you should consider using QtPy. This package is a small abstraction layer around all versions of the Qt libraries, which allows you to use them interchangeably (as far as possible) in your applications.

If you're developing Python libraries or applications that need to be portable across different versions it is definitely worth a look.

Conclusion

As we've discovered, there are no major differences between PyQt5 and PyQt6. The changes that are there can be easily worked around. If you are new to Python GUI programming with Qt you may find it easier to start with PyQt5 still, but for any new project I'd suggest starting with PyQt6.

For more, see the complete PySide6 tutorial.



from Planet Python
via read more

Django Weblog: Could you host DjangoCon Europe 2023?

DjangoCon Europe 2022 will be held from the 21st - 25th September in Porto, Portugal, hopefully, but we're already looking ahead to next year's conference. Could your town - or your football stadium, circus tent, private island, or city hall - host this wonderful community event?

Under the usual circumstances, the DjangoCon Europe licensee picks the date of the conference but the event must fall more than one month from DjangoCon US and PyCon US, and EuroPython in the same calendar year. Also, at the end of DjangoCon Europe, the next hosts for DjangoCon Europe would be announced and a call for proposals for volunteers to organise DjangoCon Europe in 2 years would be made.

However, the pandemic has disturbed this tradition for the past three years resulting in the Porto team organizing DjangoCon Europe for the third time in a row. We have also had to offer exceptional permission for DjangoCon Europe to take place less than one month away from DjangoCon US due to challenges we faced in 2021 with finding new hosts for the conference.

We are hoping to find organizers for DjangoCon Europe by April 2022 so that we can keep in line with the tradition of DjangoCon Europe taking place between April and July and announcing the next DjangoCon Europe at DjangoCon Europe 2022 in Porto.

Hosting a DjangoCon is an ambitious undertaking. It's hard work, but each year it has been successfully run by a team of community volunteers, not all of whom have had previous experience - more important is enthusiasm, organisational skills, the ability to plan and manage budgets, time and people - and plenty of time to invest in the project.

You'll find plenty of support on offer from previous DjangoCon organisers, so you won't be on your own.

How to apply

If you're interested, we'd love to hear from you. Following the established tradition, the selected hosts will be announced at this year's DjangoCon by last year's organiser but must fall more than one month from DjangoCon US and PyCon US, and EuroPython in the same calendar year, so we'll need to receive your proposal before then.

The more detailed and complete your proposal, the better. Things you should consider, and that we'd like to know about, are:

  • dates
  • numbers of attendees
  • venue(s)
  • accommodation
  • transport links
  • budgets and ticket prices
  • committee members

We'd like to see:

  • timelines
  • pictures
  • prices
  • draft agreements with providers
  • alternatives you have considered

They will all help show that your plans are serious and thorough and that you have the organisational capacity to make it a success.

Just drop us a line.



from Planet Python
via read more

Wednesday, February 2, 2022

Best DataRobot Alternatives for Model Registry

DataRobot is an enterprise AI platform that provides tools for building, managing, and deploying models at scale for businesses, and automating end-to-end ML lifecycles. It contains different kinds of models, data, latest open-source algorithms that can be used on-premise, or as a fully managed AI service, DataRobot gives you the power of AI to drive […]

The post Best DataRobot Alternatives for Model Registry appeared first on neptune.ai.



from Planet SciPy
read more

ItsMyCode: TypeError: ‘builtin_function_or_method’ object is not subscriptable

In Python, Built-in functions are not subscriptable, if we use the built-in functions as an array to perform operations such as indexing, you will encounter TypeError: ‘builtin_function_or_method’ object is not subscriptable.

This article will look at what TypeError: ‘builtin_function_or_method’ object is not subscriptable error means and how to resolve this error with examples.

What is TypeError: ‘builtin_function_or_method’ object is not subscriptable?

If we use the square bracket [] instead of parenthesis() while calling a function, Python will throw TypeError: ‘builtin_function_or_method’ object is not subscriptable.

The functions in Python are called using the parenthesis “()", and that’s how we distinguish the function call from the other operations, such as indexing the list. Usually, when working with lists or arrays, it’s a common mistake that the developer makes. 

Let us take a simple example to reproduce this error.

Here in the example below, we have a list of car brands and are adding the new car brand to the list.

We can use the list built-in function to add a new car brand to the list, and when we execute the code, Python will throw TypeError: ‘builtin_function_or_method’ object is not subscriptable.

cars = ['BMW', 'Audi', 'Ferrari', 'Benz']

# append the new car to the list
cars.append["Ford"]

# print the list of new cars
print(cars)

Output

Traceback (most recent call last):
  File "c:\Personal\IJS\Code\main.py", line 4, in <module>
    cars.append["Ford"]
TypeError: 'builtin_function_or_method' object is not subscriptable

We are getting this error because we are not correctly using the append() method. We are indexing it as if it is an array (using the square brackets), but in reality, the append() is a built-in function.

How to Fix TypeError: ‘builtin_function_or_method’ object is not subscriptable?

We can fix the above code by treating the append() as a valid function instead of indexing.

In simple terms, we need to replace the square brackets with the parentheses (), making it a proper function.

This happens while working with arrays or lists and using functions like append(), pop(), remove(), etc., and if we perform the indexing operation using the function.

After replacing the code, you can observe that it runs successfully and adds a new brand name as the last element to the list.

cars = ['BMW', 'Audi', 'Ferrari', 'Benz']

# append the new car to the list
cars.append("Ford")

# print the list of new cars
print(cars)

Output

['BMW', 'Audi', 'Ferrari', 'Benz', 'Ford']

Conclusion

The TypeError: ‘builtin_function_or_method’ object is not subscriptable occurs if we use the square brackets instead of parenthesis while calling the function. 

The square brackets are mainly used to access elements from an iterable object such as list, array, etc. If we use the square brackets on the function, Python will throw a TypeError.

We can fix the error by using the parenthesis while calling the function.



from Planet Python
via read more

Python⇒Speed: Finding leaked secrets in your Docker image with a scanner

If you’re not careful, you can end up with a private SSH key, AWS access token, or password embedded in your Docker image. That means anyone who access the image will be able to get that secret, and potentially use it to gain further access to additional systems.

While you can and should take steps to prevent leaking secrets in the first place, it’s still useful to catch leaks if they do happen. If you can catch the leak before you push the image to a remote registry, no harm done.

That’s where a secrets scanner comes in handy: it can automatically catch secrets, up to a point anyway.

Recap: how secrets get leaked in Docker images

Here’s an example of a Dockerfile that leaks secrets two ways: with build args, and by copying secrets in. You can view the former with docker image history, and the latter is available in the image much in the way old commits are accessible in a Git repository, accessible for example via docker image save. (For more details, and the secure alternative, see my article on Docker build secrets.)

FROM busybox

# Copy in SSH private key, then delete it; this is INSECURE,
# the secret will still be in the image.
COPY id_dsa .
RUN rm id_dsa

# Accept a secret as build arg. This is INSECURE.
ARG mypassword
RUN echo $mypassword

I build the image:

$ docker build --build-arg mypassword=XW835S3d20-3432S%K@345 -t bad-secrets .

And now this image has leaked two secrets, a build argument (“XW8…”) and a SSH private key.

Note: Outside any specific best practice being demonstrated, the Dockerfiles in this article are not examples of best practices, since the added complexity would obscure the main point of the article.

Python on Docker Production Handbook Make sure your production software is packaged securely, efficiently, and quickly: Read the pragmatic, thorough, and concise Python on Docker Production Handbook.

Using a secrets scanner

A good secrets scanner with Docker support will be able to find both. There aren’t that many secrets scanners that support Docker, and the ones I’ve tried haven’t been able to find both. The only one I’ve found that does work is GitGuardian.

You can get a free account from the service that gives a pretty decent number of free scans. You’ll need to generate an API token through their dashboard. Then:

$ export GITGUARDIAN_API_KEY=the-token-you-got-from-dashboard
$ python3 -m venv /tmp/venv
$ /tmp/venv/bin/pip install ggshield
$ ggshield scan docker bad-secrets
...
>>> Incident 1(Secrets detection): Generic High Entropy Secret (Validity: Cannot Check)  (Ignore with SHA: 73c43dc3b30b828a082b5ea3401c69fa07145aec16202fb1babec325db2dad6c) (2 occurrences)
1 | …usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],"Cmd":["|1","mypassword=XW8*******-**32S%K@345","/bin/sh","-c","echo $mypassword"],"Image":"sha256:504c3ee7a91b445126658150ed2…
...
>>> Incident 1(Secrets detection): OpenSSH Private Key (Validity: Cannot Check)  (Ignore with SHA: a0e1f407b0cdbb2d0484a6b5bb6e931135d3972b89bf79dce3ec1b50caed53bf) (1 occurrence)

The scanner spotted both secrets. Success!

ggshield also does the right thing of exiting with a non-zero exit code if it finds a potential vulnerability, so it’s ready to go for CI setups.

The limitations of secret scanners

It’s worth keeping in mind that there are two basic techniques for spotting secrets:

  1. Standard file formats, file names, and the like. An SSH private key, for example, has a very specific format, and was correctly identified based on that.
  2. Things that look like secrets, and specifically that look like good secrets, i.e. with lots of randomness or entropy. That’s how the “XW835S3d20 etc.” string was caught.

The second method is a heuristic. That means it might occasionally have false positives, spotting something that looks like a secret but isn’t. It also might miss secrets that are sufficiently not-random. For example, if I chose the rather worse password “12345” the ggshield scanner won’t catch that.

So as useful as secret scanners are, you should also take steps to prevent leaking secrets in the first place.

Read more...

from Planet Python
via read more

Using Python's pip to Manage Your Projects' Dependencies

The standard package manager for Python is pip. It allows you to install and manage packages that aren’t part of the Python standard library. If you’re looking for an introduction to pip, then you’ve come to the right place!

In this tutorial, you’ll learn how to:

  • Set up pip in your working environment
  • Fix common errors related to working with pip
  • Install and uninstall packages with pip
  • Manage projects’ dependencies using requirements files

You can do a lot with pip, but the Python community is very active and has created some neat alternatives to pip. You’ll learn about those later in this tutorial.

Getting Started With pip

So, what exactly does pip do? pip is a package manager for Python. That means it’s a tool that allows you to install and manage libraries and dependencies that aren’t distributed as part of the standard library. The name pip was introduced by Ian Bicking in 2008:

I’ve finished renaming pyinstall to its new name: pip. The name pip is [an] acronym and declaration: pip installs packages. (Source)

Package management is so important that Python’s installers have included pip since versions 3.4 and 2.7.9, for Python 3 and Python 2, respectively. Many Python projects use pip, which makes it an essential tool for every Pythonista.

The concept of a package manager might be familiar to you if you’re coming from another programming language. JavaScript uses npm for package management, Ruby uses gem, and the .NET platform uses NuGet. In Python, pip has become the standard package manager.

Finding pip on Your System

The Python 3 installer gives you the option to install pip when installing Python on your system. In fact, the option to install pip with Python is checked by default, so pip should be ready for you to use after installing Python.

You can verify that pip is available by looking for the pip3 executable on your system. Select your operating system below and use your platform-specific command accordingly:

C:\> where pip3

The where command on Windows will show you where you can find the executable of pip3. If Windows can’t find an executable named pip3, then you can also try looking for pip without the three (3) at the end.

$ which pip3

The which command on Linux systems and macOS shows you where the pip3 binary file is located.

On Windows and Unix systems, pip3 may be found in more than one location. This can happen when you have multiple Python versions installed. If you can’t find pip in any location on your system, then you may consider reinstalling pip.

Instead of running your system pip directly, you can also run it as a Python module. In the next section, you’ll learn how.

Running pip as a Module

When you run your system pip directly, the command itself doesn’t reveal which Python version pip belongs to. This unfortunately means that you could use pip to install a package into the site-packages of an old Python version without noticing. To prevent this from happening, you can run pip as a Python module:

$ python3 -m pip

Notice that you use python3 -m to run pip. The -m switch tells Python to run a module as an executable of the python3 interpreter. This way, you can ensure that your system default Python 3 version runs the pip command. If you want to learn more about this way of running pip, then you can read Brett Cannon’s insightful article about the advantages of using python3 -m pip.

Sometimes you may want to be more explicit and limit packages to a specific project. In situations like this, you should run pip inside a virtual environment.

Using pip in a Python Virtual Environment

To avoid installing packages directly into your system Python installation, you can use a virtual environment. A virtual environment provides an isolated Python interpreter for your project. Any packages that you use inside this environment will be independent of your system interpreter. This means that you can keep your project’s dependencies separate from other projects and the system at large.

Read the full article at https://realpython.com/what-is-pip/ »


[ 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 ]



from Real Python
read more

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...