skip to navigation
skip to content

Planet Python

Last update: August 11, 2022 07:41 AM UTC

August 10, 2022


TestDriven.io

Integrating Mailchimp with Django

This article looks at how to integrate Mailchimp with Django for newsletters and transactional emails.

August 10, 2022 10:28 PM UTC


The Python Coding Blog

Shallow and Deep Copy in Python and How to Use __copy__()

You need to make a copy of an object in a Python program. How difficult can it be? Not very. But you also need to know the difference between shallow and deep copy in Python and decide which one you need.

In this article, you’ll read about the difference between shallow and deep copy when used on simple data structures. Then, you’ll look at more complex structures, including when copying an object created from a class you define yourself. In this example in which I’ll be cloning myself (!), you’ll see some of the pitfalls of copying objects and how to look out for them and avoid them.

In this article, you’ll learn more about:

Yes, there’s also __deepcopy__(), but I’ll stop at __copy__() in this article.

What’s The Problem With Copying Objects?

Here’s a preview of the example you’ll write towards the end of this article. You’ll create a couple of simple classes to define a Person and a Car. Yes, I’m afraid it’s “person” and “car” again. You’ve seen these examples used very often in object-oriented programming tutorials. But it’s a bit different in this case, so bear with me, please.

If you want a tutorial about classes that doesn’t use the “same old classes” that every other tutorial does, you can read the chapter about Object-Oriented Programming in Python in The Python Coding Book:

# household.py

class Car:
    def __init__(self, make: str, model: str):
        self.make = make
        self.model = model
        self.mileage = 0

    def add_mileage(self, miles: float):
        self.mileage += miles

class Person:
    def __init__(self, firstname: str):
        self.firstname = firstname
        self.car = None

    def buy_car(self, car: Car):
        self.car = car

    def drive(self, miles: float):
        self.car.add_mileage(miles)

You’ll walk through this example in a bit more detail later. For now, Here, I’ll highlight that the Car module has make, model, and mileage attributes. The latter can be updated using the add_mileage() method.

Person has attributes firstname and car. You can assign an object of type Car to the Person using buy_car(), and you can get the person to go for a drive using drive(), which adds mileage to the car.

You can use these classes in a new script:

# cloning_stephen.py

from household import Car, Person

# Create a person who buys a car
stephen = Person("Stephen")
stephen.buy_car(
    Car("BMW", "Series 1")
)

# Log how many miles driven
stephen.drive(100)

print(f"Stephen's mileage is {stephen.car.mileage} miles")

The output from the print() line is:

Stephen's mileage is 100 miles

Next, you’ll clone Stephen (as if one of me is not enough already!)

# cloning_stephen.py

import copy

from household import Car, Person

# Create a person who buys a car
stephen = Person("Stephen")
stephen.buy_car(
    Car("BMW", "Series 1")
)

# Log how many miles driven
stephen.drive(100)

print(f"Stephen's mileage is {stephen.car.mileage} miles")

# Let's copy the Person instance
clone = copy.copy(stephen)

print(
    f"The clone's car is a {clone.car.make} {clone.car.model}"
)

print(f"The clone's mileage is {clone.car.mileage} miles")

# Let's check whether the two cars are exactly the same car
print(
    f"Stephen's car is clone's car: {stephen.car is clone.car}"
)

And here’s where the problem lies. Look at the output from this code:

Stephen's mileage is 100 miles
The clone's car is a BMW Series 1
The clone's mileage is 100 miles
Stephen's car is clone's car: True

The clone’s car is also a BMW Series 1, which makes sense. The clone has the same tastes and needs as Stephen! But, the clone’s car starts at 100 miles. Even though you’ve just created the clone and he’s not been on a drive yet.

The final line explains what’s happening. Stephen and the clone have the same car. Not just the same make and model, but the exact same car.

If the clone goes for a drive now, Stephen’s mileage will also change. Here’s what will happen if you add the following lines to the end of cloning_stephen.py:

# cloning_stephen.py

# ...

# Clone goes for a drive:
clone.drive(68)

print(f"Stephen's mileage is {stephen.car.mileage} miles")

The output is:

Stephen's mileage is 168 miles

Stephen’s mileage increased by 68 miles even though it’s the clone who went for a drive. That’s because they are using the same car! It’s unlikely this is the behaviour you want when you create a copy of a Person.

You’ll return to this example a bit later.

Making a Copy of Simple Data Structures

I’ll go through this section quickly as the fun starts in the next section. Let’s copy a list and a dictionary:

>>> trip_mileages = [10, 12, 3, 59]
>>> copied_list = trip_mileages.copy()
>>> copied_list
[10, 12, 3, 59]
>>> copied_list is trip_mileages
False

>>> trips = {
...     "Supermarket": 2,
...     "Holiday": 129,
... }
>>> copied_dict = trips.copy()
>>> copied_dict
{'Supermarket': 2, 'Holiday': 129}
>>> copied_dict is trips
False

Both lists and dictionaries have a .copy() method. This makes life easy to copy them to create a new object containing the same information.

What if you have a tuple?

>>> trip_mileages_tuple = 10, 12, 3, 59
>>> trip_mileages_tuple.copy()
Traceback (most recent call last):
  ...
AttributeError: 'tuple' object has no attribute 'copy'

Tuples don’t have a .copy() method. In this case, you can try to use the copy built-in module:

>>> trip_mileages_tuple = 10, 12, 3, 59

>>> import copy

>>> copied_tuple = copy.copy(trip_mileages_tuple)
>>> copied_tuple
(10, 12, 3, 59)
>>> copied_tuple is trip_mileages_tuple
True

You’ve been able to create a “copy” of a tuple, except it’s not a copy at all! As tuples are immutable, when you try to copy the tuple, you get a new reference to the same tuple.

You may be wondering whether this is also the case if you use copy.copy() with mutable types such as lists and dictionaries:

>>> trip_mileages = [10, 12, 3, 59]

>>> import copy

>>> copied_list = copy.copy(trip_mileages)
>>> copied_list
[10, 12, 3, 59]
>>> copied_list is trip_mileages
False

No, in this case, copy.copy(trip_mileages) gives the same output as trip_mileages.copy(). You’ll see later on what determines how copy.copy() behaves on any object. But first, let’s look at more complex data structures and find out about shallow and deep copies.

Making a Copy of Complex Data Structures

Consider a list of teams, where each team is a list of names. You create a copy of the list of teams:

>>> teams = [["Stephen", "Mary"], ["Kate", "Trevor"]]
>>> copied_teams = teams.copy()
>>> copied_teams
[['Stephen', 'Mary'], ['Kate', 'Trevor']]
>>> copied_teams is teams
False

So far, this is the same result as the one in the previous section. But, Martin joins Stephen and Mary’s team. You choose to add this to the copied list as you’d like to keep the original teams list unchanged:

>>> copied_teams[0].append("Martin")
>>> copied_teams
[['Stephen', 'Mary', 'Martin'], ['Kate', 'Trevor']]

>>> teams
[['Stephen', 'Mary', 'Martin'], ['Kate', 'Trevor']]

>>> copied_teams[0] is teams[0]
True

You add Martin to the first team in copied_teams. However, he was also added to the first team in teams, the original list, even though you didn’t append anything explicitly to it.

You can see why this happens in the last statement in which you’re checking whether the first list in copied_teams is the same object as the first list in teams. Yes, they are both the same object.

Creating Shallow and Deep Copies in Python

When you copied the list using teams.copy(), you created a shallow copy of the list. Let’s see what this means.

When you create a list, you’re creating a new object of type list which contains several items. However, the list actually contains references to other objects that are stored elsewhere. Therefore, teams[0] is a reference to another object, the list: ['Stephen', 'Mary']. Look again at the line you used to create the teams list initially:

>>> teams = [["Stephen", "Mary"], ["Kate", "Trevor"]]

This line creates three lists:

You can visualise this using the diagram below:

When you use teams.copy() or copy.copy(teams), you’re creating a new outer list. However, you’re not copying the inner lists. Instead, you use the same lists ['Stephen', 'Mary'] and ['Kate', 'Trevor'] you already have. Here’s a representation of what this looks like:

teams[0] and copied_teams[0] are two references pointing to the same list. You have two ways of referring to the same object.

So, when you add Martin to the copied_teams[0], you are adding Martin’s name to the only existing list which has the Stephen’s team members’ names.

Sometimes, this is not what you want. Instead, you want to create a copy of all the items inside objects.

Deep Copy

In this section, you’ll read about creating a deep copy of an object. But first, let’s recreate the example above using the functions in the built-in module copy.

copy.copy() creates a shallow copy, so you’ll get the same output as the one in the section above:

>>> import copy
>>> teams = [["Stephen", "Mary"], ["Kate", "Trevor"]]

>>> copied_teams = copy.copy(teams)

>>> copied_teams[0].append("Martin")
>>> copied_teams
[['Stephen', 'Mary', 'Martin'], ['Kate', 'Trevor']]
>>> teams
[['Stephen', 'Mary', 'Martin'], ['Kate', 'Trevor']]

>>> copied_teams[0] is teams[0]
True

Therefore for lists, copy.copy(teams) is the same as teams.copy().

Next, you can try using copy.deepcopy() instead:

>>> import copy
>>> teams = [["Stephen", "Mary"], ["Kate", "Trevor"]]

>>> deepcopied_teams = copy.deepcopy(teams)
>>> deepcopied_teams
[['Stephen', 'Mary'], ['Kate', 'Trevor']]

>>> deepcopied_teams[0].append("Martin")
>>> deepcopied_teams
[['Stephen', 'Mary', 'Martin'], ['Kate', 'Trevor']]
>>> teams
[['Stephen', 'Mary'], ['Kate', 'Trevor']]

>>> deepcopied_teams[0] is teams[0]
False

When you append "Martin" to deepcopied_teams, which is the deep copy you created from the original list, the new item does not appear when you display teams. And unlike the case with the shallow copy earlier, deepcopied_teams[0] is no longer the same object as teams[0].

When you create a deep copy, you’re copying the outer list, but you’re also creating copies of the inner lists. Therefore, the references in teams and those in deepcopied_teams point to different objects. The two copies created by deepcopy() are entirely separate from each other. Here’s how this representation looks now:

You can read more about shallow and deep copy in Python in the official documentation.

Copying Objects of Classes You’ve Defined Yourself

It’s time to create your own classes and explore what happens when you make copies of them. You’ve already come across the class definitions Car and Person at the beginning of this article. Let’s introduce these classes properly. You can define them in a script called household.py:

# household.py

class Car:
    def __init__(self, make: str, model: str):
        self.make = make
        self.model = model
        self.mileage = 0

    def add_mileage(self, miles: float):
        self.mileage += miles

class Person:
    def __init__(self, firstname: str):
        self.firstname = firstname
        self.car = None

    def buy_car(self, car: Car):
        self.car = car

    def drive(self, miles: float):
        self.car.add_mileage(miles)

You can initialise Car with a make and a model, both of which are strings. I’m using type hinting in this example to keep track of what the argument types are. A new car starts with a mileage of 0 miles (or kilometres, if you prefer).

And as the name implies, the method add_mileage() is used to add miles whenever the person drives the car.

A Person is initialised with a first name which is a string. The method buy_car() allows you to link an instance of the class Car to an instance of Person. The Car object is referenced using the attribute Person.car.

Whenever the person goes on a trip, you can call the drive() method which logs the additional miles onto the person’s car.

In a new script called cloning_stephen.py, you can test these classes:

# cloning_stephen.py

from household import Car, Person

# Create a person who buys a car
stephen = Person("Stephen")
stephen.buy_car(
    Car("BMW", "Series 1")
)

# Log how many miles driven
stephen.drive(100)

print(f"Stephen's mileage is {stephen.car.mileage} miles")

This is the same code you saw earlier. You create an instance of Person and call the buy_car() method for that instance. Stephen (I’m still talking about myself in the third person!) goes for a 100-mile drive. You log this by calling the drive() method. This updates the mileage attribute of the Car instance referenced in stephen.car. This code gives the following output:

Stephen's mileage is 100 miles

Copying An Object: The Default Case

Stephen is very busy these days! He decides to clone himself so he can get more things done. Let’s try this. You can copy the instance stephen in cloning_stephen.py using the built-in copy.copy():

# cloning_stephen.py

import copy

from household import Car, Person

# Create a person who buys a car
stephen = Person("Stephen")
stephen.buy_car(
    Car("BMW", "Series 1")
)

# Log how many miles driven
stephen.drive(100)

print(f"Stephen's mileage is {stephen.car.mileage} miles")

# Let's copy the Person instance
clone = copy.copy(stephen)

print(
    f"The clone's car is a {clone.car.make} {clone.car.model}"
)

print(f"The clone's mileage is {clone.car.mileage} miles")

# Let's check whether the two cars are exactly the same car
print(
    f"Stephen's car is clone's car: {stephen.car is clone.car}"
)

The outputs from this script, which you’ve already seen earlier, show the problem with this type of copy:

Stephen's mileage is 100 miles
The clone's car is a BMW Series 1
The clone's mileage is 100 miles
Stephen's car is clone's car: True

This is a shallow copy. Therefore, although stephen and clone are different instances of the class Person, they both share the same instance of Car. Stephen has managed to clone himself, but he has to share the same car with his clone. That’s not good, as Stephen and the clone can’t be efficient if they can’t go to different places.

If the clone goes for a drive, he’s using the same car Stephen uses. Therefore the extra mileage will also show up for Stephen:

# cloning_stephen.py

# ...

# Clone goes for a drive:
clone.drive(68)

print(f"Stephen's mileage is {stephen.car.mileage} miles")

This shows Stephen’s mileage has increased to 168 miles:

Stephen's mileage is 168 miles

Using copy.deepcopy()

What if you try to create a deep copy instead of a shallow one? After all, this trick worked with the example of the list of team members earlier. You can update cloning_stephen.py to use copy.deepcopy() instead of copy.copy():

# cloning_stephen.py

import copy

from household import Car, Person

# Create a person who buys a car
stephen = Person("Stephen")
stephen.buy_car(
    Car("BMW", "Series 1")
)

# Log how many miles driven
stephen.drive(100)

print(f"Stephen's mileage is {stephen.car.mileage} miles")

# Let's copy the Person instance
clone = copy.deepcopy(stephen)

print(
    f"The clone's car is a {clone.car.make} {clone.car.model}"
)

print(f"The clone's mileage is {clone.car.mileage} miles")

# Let's check whether the two cars are exactly the same car
print(
    f"Stephen's car is clone's car: {stephen.car is clone.car}"
)

When you run this script, you’ll now get the following output:

Stephen's mileage is 100 miles
The clone's car is a BMW Series 1
The clone's mileage is 100 miles
Stephen's car is clone's car: False

Stephen’s mileage is still 100 miles. There’s no reason why this should be different as Stephen drove 100 miles.

The clone’s car is a BMW Series 1, the same as Stephen’s car make and model. This is what you want since Stephen’s clone has the same car preferences as Stephen!

Let’s skip to the last line of the output. Stephen’s car is no longer the exact same car as the clone’s car. This is different from the result you got with the shallow copy above. The clone’s car is a different instance of Car. So there are two cars now; one belongs to Stephen and the other to the clone.

However, the clone’s car already has 100 miles on the odometer even though the clone hasn’t driven yet. When you create a deep copy of stephen, the program creates a new instance of Car. However, all of the original car attributes are also copied. This means the clone’s car starts with whatever mileage Stephen’s car has when you create the deep copy.

From now on, the two cars are separate, so when the clone drives the car, the additional mileage won’t show up in Stephen’s car:

# cloning_stephen.py

# ...

# Clone goes for a drive:
clone.drive(68)

print(f"Stephen's mileage is {stephen.car.mileage} miles")
print(f"The clone's mileage is {clone.car.mileage} miles")

The output shows that Stephen’s mileage is still 100 miles, but the clone’s mileage is now 168 miles even though his one and only only trip is 68 miles long:

...
Stephen's mileage is 100 miles
The clone's mileage is 168 miles

In the last section of this article, you’ll fix this to customise how an instance of Person should be copied.

Defining The __copy__ Dunder Method

You can override the default behaviour for copy.copy() and copy.deepcopy() for any class you define. In this article, I’ll only focus on defining the dunder method __copy__(), which determines what happens when you call copy.copy() for your object. There’s also a __deepcopy__() dunder method, aimed at creating deep copies, which is similar but provides a bit more functionality to deal with complex objects.

You can return to household.py where you define the class Person and add __copy__() to the class:

# household.py

class Car:
    def __init__(self, make: str, model: str):
        self.make = make
        self.model = model
        self.mileage = 0

    def add_mileage(self, miles: float):
        self.mileage += miles

class Person:
    def __init__(self, firstname: str):
        self.firstname = firstname
        self.car = None

    def buy_car(self, car: Car):
        self.car = car

    def drive(self, miles: float):
        self.car.add_mileage(miles)

    def __copy__(self):
        copy_instance = Person(self.firstname)
        copy_instance.buy_car(
            Car(
                make=self.car.make,
                model=self.car.model,
            )
        )
        return copy_instance

The __copy__() dunder method creates a new Person instance using the same first name of the instance you’re copying. It also creates a new Car instance using the make and model of the car you’re copying. You pass this new Car object as an argument in copy_instance.buy_car() and then return the new Person instance.

You can return to cloning_stephen.py, making sure you use copy.copy() to make a copy of stephen. This means that Person.__copy__() is used when creating the copy.

# cloning_stephen.py

import copy

from household import Car, Person

# Create a person who buys a car
stephen = Person("Stephen")
stephen.buy_car(
    Car("BMW", "Series 1")
)

# Log how many miles driven
stephen.drive(100)

print(f"Stephen's mileage is {stephen.car.mileage} miles")

# Let's copy the Person instance
clone = copy.copy(stephen)

print(
    f"The clone's car is a {clone.car.make} {clone.car.model}"
)

print(f"The clone's mileage is {clone.car.mileage} miles")

# Let's check whether the two cars are exactly the same car
print(
    f"Stephen's car is clone's car: {stephen.car is clone.car}"
)

Now, the output is:

Stephen's mileage is 100 miles
The clone's car is a BMW Series 1
The clone's mileage is 0 miles
Stephen's car is clone's car: False

The clone still has a different instance of Car but now, the car’s mileage starts at 0, as you’d expect! You’ve created a custom version of shallow copy by defining __copy__() for the class. In this case, you decided that when you copy a Person, the new instance has its own car which starts with 0 miles.

In more complex classes, you may want to define both __copy__() and __deepcopy__() if you want to distinguish between shallow and deep copy in your Python program.

Final Words

Here’s a summary of the key points you covered in this article:

You’re now ready to safely copy any object, knowing what to look out for if the object references other objects.

Appendix: You Cannot Copy An Immutable Object

Do you recall when you used copy.copy() on a tuple earlier in the article? Unlike when you copy lists and dictionaries, where you got a new instance containing the same values as the original, you got the same instance back when you try to copy a tuple.

Whenever you pass an immutable object to copy.copy(), it returns the object itself.

Further Reading

You can read more about Object-Oriented Programming here:


Get the latest blog updates

No spam promise. You’ll get an email when a new blog post is published


The post Shallow and Deep Copy in Python and How to Use __copy__() appeared first on The Python Coding Book.

August 10, 2022 04:20 PM UTC


"Paolo Amoroso's Journal"

The Python feed of my old blog Moonshots Beyond the Cloud has long been...

The Python feed of my old blog Moonshots Beyond the Cloud has long been aggregated by Planet Python. But I'm no longer going to update that blog, so I removed the old feed from Planet Python and submitted the Python feed of my new blog, Paolo Amoroso's Journal.

#Python #blogging

Discuss... | Reply by email...

August 10, 2022 02:14 PM UTC


Real Python

Sorting a Python Dictionary: Values, Keys, and More

You’ve got a dictionary, but you’d like to sort the key-value pairs. Perhaps you’ve tried passing a dictionary to the sorted() function but haven’t gotten the results you expected. In this tutorial, you’ll go over everything you need to know if you want to sort dictionaries in Python.

In this tutorial, you’ll:

  • Review how to use the sorted() function
  • Learn how to get dictionary views to iterate over
  • Understand how dictionaries are cast to lists during sorting
  • Learn how to specify a sort key to sort a dictionary by value, key, or nested attribute
  • Review dictionary comprehensions and the dict() constructor to rebuild your dictionaries
  • Consider alternative data structures for your key-value data

Along the way, you’ll also use the timeit module to time your code and get tangible results for comparing the different methods of sorting key-value data. You’ll also consider whether a sorted dictionary is really your best option, as it’s not a particularly common pattern.

To get the most out of this tutorial, you should know about dictionaries, lists, tuples, and functions. With that knowledge, you’ll be able to sort dictionaries by the end of this tutorial. Some exposure to higher-order functions, such as lambda functions, will also come in handy but isn’t a requirement.

Free Download: Click here to download the code that you’ll use to sort key-value pairs in this tutorial.

First up, you’ll learn some foundational knowledge before trying to sort a dictionary in Python.

Rediscovering Dictionary Order in Python

Before Python 3.6, dictionaries were inherently unordered. A Python dictionary is an implementation of the hash table, which is traditionally an unordered data structure.

As a side effect of the compact dictionary implementation in Python 3.6, dictionaries started to conserve insertion order. From 3.7, that insertion order has been guaranteed.

If you wanted to keep an ordered dictionary as a data structure before compact dictionaries, then you could use OrderedDict from the collections module. Similar to the modern compact dictionary, it also keeps insertion order, but neither type of dictionary sorts itself.

Another alternative for storing an ordered key-value pair data is to store the pairs as a list of tuples. As you’ll see later in the tutorial, using a list of tuples could be the best choice for your data.

An essential point to understand when sorting dictionaries is that even though they conserve insertion order, they’re not considered a sequence. A dictionary is like a set of key-value pairs, and sets are unordered.

Dictionaries also don’t have much reordering functionality. They’re not like lists, where you can insert elements at any position. In the next section, you’ll explore the consequences of this limitation further.

Understanding What Sorting A Dictionary Really Means

Because dictionaries don’t have much reordering functionality, when sorting a dictionary, it’s rarely done in-place. In fact, there are no methods for explicitly moving items in a dictionary.

If you wanted to sort a dictionary in-place, then you’d have to use the del keyword to delete an item from the dictionary and then add it again. Deleting and then adding again effectively moves the key-value pair to the end.

The OrderedDict class has a specific method to move an item to the end or the start, which may make OrderedDict preferable for keeping a sorted dictionary. However, it’s still not very common and isn’t very performant, to say the least.

The typical method for sorting dictionaries is to get a dictionary view, sort it, and then cast the resulting list back into a dictionary. So you effectively go from a dictionary to a list and back into a dictionary. Depending on your use case, you may not need to convert the list back into a dictionary.

Note: Sorted dictionaries aren’t a very common pattern. You’ll explore more about that topic later in the tutorial.

With those preliminaries out of the way, you’ll get to sorting dictionaries in the next section.

Sorting Dictionaries in Python

In this section, you’ll be putting together the components of sorting a dictionary so that, in the end, you can master the most common way of sorting a dictionary:

>>>
>>> people = {3: "Jim", 2: "Jack", 4: "Jane", 1: "Jill"}

>>> # Sort by key
>>> dict(sorted(people.items()))
{1: 'Jill', 2: 'Jack', 3: 'Jim', 4: 'Jane'}

>>> # Sort by value
>>> dict(sorted(people.items(), key=lambda item: item[1]))
{2: 'Jack', 4: 'Jane', 1: 'Jill', 3: 'Jim'}

Don’t worry if you don’t understand the snippets above—you’ll review it all step-by-step in the following sections. Along the way, you’ll learn how to use the sorted() function with sort keys, lambda functions, and dictionary constructors.

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


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

August 10, 2022 02:00 PM UTC


Python for Beginners

Save Numpy Array to Text File in Python

Numpy arrays are used extensively while data analysis in python. In this article, we will discuss how we can save a numpy array to a text file in python.

Save Numpy Array to Text File Using the str() Function

We can save a numpy array to a text file using the str() function and file handling. In this approach, we will first convert the numpy array to a string using the str() function. The str() function takes the numpy array as the input argument and returns its string representation.  After converting the numpy array to a string, we will save the string to a text file.

To save the numpy array into a text file, we will first open a file in append mode using the open() function. The open() function takes the file name as its first input argument and the literal “a” as the second input argument to denote that the file is opened in the append mode. After execution, it returns a file object that contains the text file.

After getting the file object, we will use the write() method to save the string containing the numpy array to the file. The write() method, when invoked on a file object, takes the string as its input argument and appends the string to the file. After writing the string to the file, don’t forget to close the file using the close() method.

The complete code to save a numpy array to a text file using the str() function is as follows.

import numpy as np

myFile = open('sample.txt', 'r+')
myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The array is:", myArray)
print("The content of the file before saving the array is:")
text = myFile.read()
print(text)
myFile.write(str(myArray))
myFile.close()
myFile = open('sample.txt', 'r')
print("The content of the file after saving the array is:")
text = myFile.read()
print(text)

Output:

The array is: [1 2 3 4 5 6 7 8 9]
The content of the file before saving the array is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.

The content of the file after saving the array is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.
[1 2 3 4 5 6 7 8 9]

Suggested Machine Learning Article: Regression in Machine Learning With Examples

Save Numpy Array to Text File using numpy.savetxt() function

Instead of using the str() function, we can use the numpy.savetxt() function to save a numpy array to a text file in python. In this approach, we first open the text file in the append mode using the open() function as discussed in the previous example. After opening the file, we will use the numpy.savetxt() function to save the array to the text file. Here, the numpy.savetxt() function takes the file object as its first input argument and the numpy array as its second input argument. After execution, it saves the numpy array to the text file. You can observe this in the following example.

import numpy as np

myFile = open('sample.txt', 'r+')
myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The array is:", myArray)
np.savetxt(myFile, myArray)
myFile.close()
myFile = open('sample.txt', 'r')
print("The content of the file after saving the array is:")
text = myFile.read()
print(text)

Output:

The array is: [1 2 3 4 5 6 7 8 9]
The content of the file after saving the array is:
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
4.000000000000000000e+00
5.000000000000000000e+00
6.000000000000000000e+00
7.000000000000000000e+00
8.000000000000000000e+00
9.000000000000000000e+00

After, execution of the savetxt() function, you must close the file object using the close() object. Otherwise, the changes will not be written to the file.

Conclusion

In this article, we have discussed two approaches to save a numpy array to a text file in python. To know more about Python programming, you can read this article on list comprehension in Python. You might also like this article on dictionary comprehension in python.

The post Save Numpy Array to Text File in Python appeared first on PythonForBeginners.com.

August 10, 2022 01:00 PM UTC


Mike Driscoll

How to Merge Dictionaries with Python (Video)

Learn three different ways to merge Python dictionaries with Mike Driscoll

You will learn three different ways to merge dictionaries:

The post How to Merge Dictionaries with Python (Video) appeared first on Mouse Vs Python.

August 10, 2022 12:30 PM UTC


IslandT

Rotate and scale image with Pygame

In this article, I will create a small python program using the pygame framework to scale up and rotate an image on the display screen. The image will keep on rotating counterclockwise at 0.1 degrees on each update!

The method which I used in this program to scale and rotate the image is:

rotate_image = pygame.transform.rotozoom(pawn0, original_rotation, 2)

The first parameter of the method is the surface of the normal image. The second parameter is the degree of rotation in the counterclockwise motion which is in float value. The third parameter is the scale of the resized image which is also in the float value! This method will return the rotating surface which will be used in the screen.blit method below.

Below is the whole program…

# Import and initialize the pygame library
import pygame
import pygame.gfxdraw

pygame.display.init()

# set the caption on the panel
pygame.display.set_caption("Draw Some Drawing")

# windows height and width
windowwidth = 600
windowheight = 600

# hat image load
pawn0 = pygame.image.load("pawn.png")
width, height = pawn0.get_size() # return width and height of the hat
# the initial position of the hat image
original_image_x = 260
original_image_y = 260
increment_rotation = 0.1
original_rotation = 0

# Print this line on output panel if the initialize process is successful
if(pygame.display.get_init() == True):
    print("Success initialize the game!")

# Initialize a window or screen for display
screen = pygame.display.set_mode([windowwidth, windowheight])

# the triangle color
tricolor = pygame.Color(0,0,0)

# Print the size of the game display window

print("The windows size is " + str(pygame.display.get_window_size()))

# Run the game until the user asks to quit
running = True
while running:

    # If the user clicks on the 'x' button on pygame display window then set running to false
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill the screen with white color
    screen.fill((255,255,255))
    original_rotation += increment_rotation # increase the angle at 0.1 degree
    rotate_image = pygame.transform.rotozoom(pawn0, original_rotation, 2) # rotates the image and makes it bigger
    screen.blit(rotate_image, (original_image_x, original_image_y))  # drawing the rotated image within screen surface

    pygame.display.flip() # refresh the screen

# Quit the game
pygame.display.quit()

And here is the outcome…

This image will keep on rotating!

Now here is an exercise for you all, make the image larger and then smaller again during each update!

August 10, 2022 08:41 AM UTC

August 09, 2022


Mike Driscoll

Adding Data to Empty DataFrames in pandas

One of the most popular 3rd party Python packages is called pandas. The pandas package "is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool, built on top of the Python programming language." It is used by data scientists and software engineers around the world.

In this tutorial, you will learn a little about creating different kinds of empty or partially empty DataFrames with pandas. Then you will learn a couple of different ways to add data to that DataFrame.

Specifically, you will learn about the following:

Creating an Empty DataFrame in pandas

Sometimes you just need to create an empty DataFrame, much like you sometimes need to create an empty Python dictionary or list.

Here is an example of creating a completely empty DataFrame with pandas:

>>> import pandas as pd
>>> df = pd.DataFrame()
>>> df
Empty DataFrame
Columns: []
Index: []

Of course, an empty DataFrame isn't especially useful. So let's add a little data to the DataFrame!

>>> import pandas as pd
>>> df = pd.DataFrame()
>>> df
Empty DataFrame
Columns: []
Index: []

>>> df["Name"] = ["Mike", "Steve", "Rodrigo"]
>>> df["Jobs"] = ["Engineer", "Core Dev", "Content Creator"]
>>> df
      Name             Jobs
0     Mike         Engineer
1    Steve         Core Dev
2  Rodrigo  Content Creator

This example demonstrates how you can specify columns in pandas and add data to those columns.

Now let's learn how to create an empty DataFrame that includes columns, but no data!

Creating an Empty DataFrame with Columns

This next example will show you how to create a pandas DataFrame that includes columns, but no indices or column data.

Let's take a look:

>>> import pandas as pd

>>> df = pd.DataFrame(columns=["Name", "Job"])
>>> df
Empty DataFrame
Columns: [Name, Job]
Index: []

# Add some data using append()
>>> df = df.append({"Name": "Mike", "Job": "Blogger"}, ignore_index=True)
>>> df
   Name      Job
0  Mike  Blogger
>>> df = df.append({"Name": "Luciano", "Job": "Author"}, ignore_index=True)
>>> df
      Name      Job
0     Mike  Blogger
1  Luciano   Author

Well, that was better than a completely empty DataFrame! In this example, you also learn how to use the DataFrame's append() method to add data to each column.

When you use append() it takes in a dictionary of column name and value. You also set ignore_index to True, which lets pandas update the index for you automatically.

Now let's look at how to create one more type of empty DataFrame with pandas!

Creating an Empty DataFrame with Columns and Indices

For this example, you will learn how to create a pandas DataFrame that has two columns and three named rows or indices.

Here's how it is done:

>>> import pandas as pd
>>> df = pd.DataFrame(columns = ["Name", "Job"], index = ["a", "b", "c"])
>>> df
  Name  Job
a  NaN  NaN
b  NaN  NaN
c  NaN  NaN

When you print out the DataFrame, you can see that the columns all contain NaN, which stands for "Not a Number". A NaN is kind of like a None in Python.

One way to add data to this DataFrame in pandas is to use the loc attribute:

>>> df.loc["a"] = ["Mike", "Engineer"]
>>> df
   Name       Job
a  Mike  Engineer
b   NaN       NaN
c   NaN       NaN
>>> df.loc["b"] = ["Steve", "Core Dev"]
>>> df
    Name       Job
a   Mike  Engineer
b  Steve  Core Dev
c    NaN       NaN
>>> df.loc["c"] = ["Rodrigo", "Content Creator"]
>>> df
      Name              Job
a     Mike         Engineer
b    Steve         Core Dev
c  Rodrigo  Content Creator

When you use the loc attribute, you use dictionary-like syntax to set a specific index to a list of values. The above example shows how to add three rows of data.

Wrapping Up

This tutorial doesn't even begin to scratch the surface of what you can do with pandas. But it isn't supposed to. That's what books are for. Here you learned how to create three different types of empty DataFrames.

To be specific, you learned the following:

Hopefully, you will find these examples useful in your pandas journey. Happy coding!

The post Adding Data to Empty DataFrames in pandas appeared first on Mouse Vs Python.

August 09, 2022 08:46 PM UTC


PyCoder’s Weekly

Issue #537 (Aug. 9, 2022)

#537 – AUGUST 9, 2022
View in Browser »

The PyCoder’s Weekly Logo


Finding and Fixing Python Code Bugs

Learn how to identify and fix logic errors, or bugs, in your Python code. You’ll use the built-in debugging tools in Python’s Integrated Development and Learning Environment to practice locating and resolving bugs in an example function.
REAL PYTHON course

Uncommon Uses of Python in Commonly Used Libraries

To learn more about writing maintainable Python, Eugene has been reading code from some of the more popular Python libraries. This blog post talks about some of the coding patterns he has encountered along the way.
EUGENE YAN

Scout APM: Built For Developers, By Developers

alt

Scout APM is a python monitoring tool designed to help developers find and fix performance issues quickly. With an intuitive user interface, Scout will tie bottlenecks to source code so you can quickly pinpoint and resolve performance abnormalities. Start your 14-day free trial today →
SCOUT APM sponsor

Create NBA Highlights With a Few Lines of Python

Learn how to build a play-by-play scraper to process video data from an NBA game. Use Tesseract OCR to determine clock and quarter information, then match it up with the play-by-play data to create highlights.
NOAM EPHRAT

Python 3.10.6 Released

PYTHON.ORG

Django 4.1 Released

DJANGO SOFTWARE FOUNDATION

Discussions

How to Say No to a GitHub Issue Feature Request?

HACKER NEWS

I Did Nothing Today, What Do I Say in Tomorrow’s Stand Up?

REDDIT

Python Jobs

Software Engineer, Los Angeles or Dallas (Los Angeles, CA, USA)

Causeway Capital Management LLC

Backend Software Engineer (Anywhere)

Catalpa

Backend Engineering Manager (Anywhere)

Close

Data Engineer, Data Bricks, Snowflake, Python, Remote (Oklahoma City, OK, USA)

Addison Group

Software Engineer in Test/SDET, Java, C, Python, Remote (Cary, NC, USA)

SAS Institute Inc

More Python Jobs >>>

Articles & Tutorials

Inspiring Kids to Learn Python

Is there someone in your life you’d like to inspire to learn Python? Mission Encodeable is a website designed to teach people to code, built by two high-school students. This week on the show, Anna and Harry Wake talk about creating their site and motivating people to start coding.
REAL PYTHON podcast

Supercharging A/B Testing at Uber

“While the statistical underpinnings of A/B testing are a century old, building a correct and reliable A/B testing platform and culture at a large scale is still a massive challenge.” This blog post from Uber describes why and how they rebuilt their A/B testing platform.
GITLIN, PUTTASWAMY, ET AL

Find Your Next Tech Job Through Hired

alt

Hired has 1000s of companies ranging from startups to Fortune 500s that are actively hiring developers, data scientists, mobile engineers, and more. It’s really simple: create a profile with your skills and preferences for hiring managers to reach you directly. Sign up today →
HIRED sponsor

Python Constants: Improve Your Code’s Maintainability

In this tutorial, you’ll learn how to properly define constants in Python. By coding a bunch of practical example, you’ll also learn how Python constants can improve your code’s readability, reusability, and maintainability.
REAL PYTHON

Choose the Right Python Concurrency API

How do you choose the right Python concurrency API? The standard library offers three choices. Learn the differences between the libraries and what problems are best solved by each.
JASON BROWNLEE

7 Things I’ve Learned Building a Modern TUI Framework

“I’ve be working on Textual for over a year now. Here’s a few things I’ve discovered (or re-discovered) regarding terminals in Python, and software development in general.”
WILL MCGUGAN

Simple Linear Regression Using Python

Learn how to do simple linear regression using the Python standard library, including how to prep your data set and a variety of statistical operations.
NSUKAMI PATRICK • Shared by Nsukami Patrick

Deepnote: A Better Data Science Notebook

Deepnote is a data notebook that’s built for collaboration and usability—Jupyter compatible, works magically in the cloud, and sharing is easy as sending a link. It’s also 100% free to get started. And you can run your first notebook in seconds.
DEEPNOTE sponsor

Using PyQtGraph to Create Interactive Plots

Learn how to create custom plots in PyQt6 with PyQtGraph, including building the graph, styling the lines and markers, axis labels, legends, and more.
JOHN LIM

Connect to a MySQL Database in Python

This article covers four different methods you can use to connect to a MySQL database in Python with SSL enabled.
PLANETSCALE.COM • Shared by Holly Guevara

Projects & Code

makepackage: Package Template Creation Tool

GITHUB.COM/NYGGUS

schemathesis: Open API and GraphQL Test Tool

GITHUB.COM/SCHEMATHESIS

lowbar: Simple Loading Bars for CLI Apps

GITHUB.COM/ANNIKAV9

Flet: Build Flutter Apps in Python

FLET.DEV

easycheck: Check Whether One or More Conditions Are Met

PYPI.ORG • Shared by Marcin Kozak

Events

Python North East

August 10, 2022
PYTHONNORTHEAST.COM

pyCologne User Group Treffen

August 10, 2022
PYCOLOGNE.DE

Weekly Real Python Office Hours Q&A (Virtual)

August 10, 2022
REALPYTHON.COM

Python Atlanta

August 11, 2022
MEETUP.COM

Python Miami

August 13 to August 14, 2022
PYTHONDEVELOPERSMIAMI.COM


Happy Pythoning!
This was PyCoder’s Weekly Issue #537.
View in Browser »

alt

[ Subscribe to 🐍 PyCoder’s Weekly 💌 – Get the best Python news, articles, and tutorials delivered to your inbox once a week >> Click here to learn more ]

August 09, 2022 07:30 PM UTC


IslandT

Detect the object using its own color in Pygame

In this pygame example, I will create a triangle and fill it up with the color of my choice. Next, I am going to create a small program that will detect that object using its own color as a hint.

Below is the entire python program which will use the pygame.mouse.get_pos() method to return the color of a pixel at a particular location on the display screen which will then serve as a hint whether I have clicked on that triangle or not!

# Import and initialize the pygame library
import pygame
import pygame.gfxdraw

pygame.display.init()

# set the caption on the panel
pygame.display.set_caption("Draw Some Drawing")

# windows height and width
windowwidth = 600
windowheight = 600

# Print this line on output panel if the initialize process is successful
if(pygame.display.get_init() == True):
    print("Success initialize the game!")

# Initialize a window or screen for display
screen = pygame.display.set_mode([windowwidth, windowheight])

# the triangle color
tricolor = pygame.Color(0,0,0)

# Print the x, y size of the game display window

print("The windows size is " + str(pygame.display.get_window_size()))

# Run the game until the user asks to quit
running = True
while running:

    # If the user clicks on the 'x' button on pygame display window then set running to false
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill the screen with blue color
    screen.fill((0,0,255))

    pygame.gfxdraw.filled_polygon(screen, ((200,300), (300, 300), (250, 60)), tricolor) # draw triangle filled with black color

    # check the left mouse button press state
    left_mouse_button_press_state = pygame.mouse.get_pressed(num_buttons=3)[0]

    if(left_mouse_button_press_state == True): # if the user has clicked the left mouse button...
        # get the pixel color at that position of the mouse click
        x, y = pygame.mouse.get_pos()

        if(screen.get_at((x, y)) == tricolor):
            print('In the triangle region!')
        else:
            print('Not in the triangle region!')

    pygame.display.flip() # refresh the screen

# Quit the game
pygame.display.quit()

If I have clicked on the above triangle the console will print out the below text…

In the next article I will start to create my next game project so stay tuned and if you have not yet subscribed to my blog please do so through either the RSS news feed at the top left panel of this blog or just click on the web notification button above!

August 09, 2022 02:18 PM UTC


Real Python

Exploring Special Function Parameters

Have you ever come across the forward slash (/) and asterisk (*) symbols in the documentation for your favorite libraries? These represent special parameters, which tell you what kinds of arguments you can use to call a given function. In Python, these parameters can help you ensure that your functions are used correctly.

Maybe you’re a regular at Real Python’s weekly Office Hours meetup, or perhaps you’re curious about what happens there. You’ll get a glimpse in this Code Conversation, which answers one participant’s question of how to interpret and apply special function parameters in writing and calling functions.

In this Code Conversation video course, you’ll learn how to:


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

August 09, 2022 02:00 PM UTC


Python Bytes

#296 pip: Constrain your excitement

<p><strong>Watch the live stream:</strong></p> <a href='https://www.youtube.com/watch?v=fdtDfeYmdDU' style='font-weight: bold;'>Watch on YouTube</a><br> <br> <p><strong>About the show</strong></p> <p>Sponsored by the <a href="https://pythonbytes.fm/irl"><strong>IRL Podcast from Mozilla</strong></a></p> <p><strong>Brian #1:</strong> <a href="https://luminousmen.com/post/pip-constraints-files"><strong>Pip constraints files</strong></a></p> <ul> <li>by luminousmen</li> <li>You can put some constraints on your dependencies with a <a href="https://pip.pypa.io/en/stable/user_guide/#constraints-files">constraints file</a>.</li> <li>“Constraints files are requirements files that only control which version of a requirement is installed, not whether it is installed or not. “</li> <li>Syntax is a subset of <code>requirements.txt</code> syntax <ul> <li>but all the restrictions seem reasonable, considering <ul> <li>must have a name</li> <li>can’t be editable</li> <li>can’t specify extras (that one is maybe slightly weird)</li> </ul></li> </ul></li> <li>You can put <code>--constraint constraints.txt</code> right at the top of your <code>requirements.txt</code> file</li> <li>or specify it on command line, <ul> <li><code>pip install --constraint constraints.txt -r requirements.txt</code></li> </ul></li> <li>Or, my favorite, stick it at the top of <code>requirements.in</code> file. <ul> <li>yes. <code>pip-compile</code> correctly handles constraints when generating <code>requirements.txt</code>.</li> </ul></li> <li>Example <ul> <li>requirements.in --constraint constraints.txt typer</li> <li>constraints.txt click&lt;8.1.3</li> <li>Output from <code>pip-compile requirements.in</code> <pre><code># # This file is autogenerated by pip-compile with python 3.10 # To update, run: # # pip-compile requirements.in # click==8.1.2 # via # -c constraints.txt # typer typer==0.6.1 # via -r requirements.in </code></pre></li> </ul></li> </ul> <p><strong>Michael #2:</strong> <a href="https://pypi.org/project/async-cache/"><strong>async-cache</strong></a></p> <ul> <li>A caching solution for asyncio</li> <li>Quite simple but looks effective and flexible too</li> <li>Example: <pre><code># TTL Cache from cache import AsyncTTL @AsyncTTL(time_to_live=60, maxsize=1024) async def func(*args, **kwargs): """ time_to_live : max time for which a cached result is valid maxsize : max number of results that are cached. if max limit is reached the oldest result is deleted. """ pass </code></pre></li> </ul> <p><strong>Brian #3:</strong> <a href="https://guicommits.com/organize-python-code-like-a-pro/"><strong>Organize Python code like a PRO</strong></a> </p> <ul> <li>Guilherme Latrova</li> <li>Yes, this is one author’s opinion. but… <ul> <li>lots of great advice</li> <li>nothing too weird</li> <li>no tool recommendations</li> </ul></li> <li>Recommendations of note <ul> <li>keep a <code>src</code> dir. <ul> <li>A cool and simple reason: it keeps your source code together in alphabetized IDEs.</li> </ul></li> <li>file/module names: plural except for config, main, core, or similar <ul> <li>slightly weird tangent that there are no files, there are modules. ok, whatever.</li> <li>Also talking about directories as main modules. odd. but ok.</li> </ul></li> <li>functions/methods should be verbs </li> <li>variables/constants should be nouns</li> <li>Class names should be singular, unless the class really represents a container</li> <li>The <code>__name__ == "__main__"</code> trick for modules.</li> <li>The <code>__main__.py</code> entry point trick for modules/packages so that <code>-m mymodule</code> does something.</li> </ul></li> - </ul> <p><strong>Michael #4:</strong> <a href="https://github.com/jaraco/keyring"><strong>keyring</strong></a></p> <ul> <li>via Trent</li> <li>The Python keyring library provides an easy way to access the system keyring service from python. It can be used in any application that needs safe password storage.</li> <li>It’s also helpful in that it allows you to write your own backends. Useful for testing.</li> <li>Basically create a dummy keychain that stores to a pytest temp_path fixture instead of cluttering the real keychain. </li> <li>You could potentially write a backend to interact with any service such as 1Password. </li> </ul> <p><strong>Extras</strong> </p> <p>Brian:</p> <ul> <li>I’m taking a class on FastAPI. The instructor is awesome!</li> <li>Also, editing some pytest course video.</li> </ul> <p>Michael:</p> <ul> <li><a href="https://twitter.com/btskinn/status/1555336931931815936"><strong>Gitlab, you alright?</strong></a>?</li> </ul> <p><strong>Joke:</strong> </p> <ul> <li><a href="https://github.com/wesbos/dad-jokes"><strong>from a dad-jokes repo</strong></a> <ul> <li><strong>Q:</strong> How do programming pirates pass method parameters?</li> <li><strong>A:</strong> Varrrrarrrgs.</li> <li><strong>Q:</strong> How do you get the code for the bank vault?</li> <li><strong>A:</strong> You checkout their branch.</li> <li>"Unfortunately these jokes only work if you git them."</li> </ul></li> <li><a href="https://twitter.com/pr0grammerhum0r/status/1552519242989305856?s=12&amp;t=edvc7bbtBYuatg7tNJkJ7g"><strong>Screw driver</strong></a></li> </ul>

August 09, 2022 08:00 AM UTC


Python⇒Speed

Finding performance problems: profiling or logging?

When your software is too slow in production, how can you figure out the source of the problem?

One common starting point to improving production observability is logging, and ideally trace-based logging (tracing for short). For example, the OpenTelemetry standard and the libraries and backend services that work with it can help you collect metrics, logs, and traces. Tracing—both within and across processes—is the most general of these, immensely useful for identifying and debugging problems, including performance problems.

But there’s another approach to finding performance problems, using sampling-based profiling in production. While profiling is typically used offline during development, you can also use it in production to find performance bottlenecks, with a new generation of continuous profiling tools.

So what’s the difference between trace-based logging and profiling? Which should you use—do you need only one, or both? What’s the fastest way to find performance problems in production?

To jump ahead to our conclusion: trace-based logging and profiling actually give you different information. Once your software is complex enough, you will likely want both.

In this article you’ll learn:

Read more...

August 09, 2022 12:00 AM UTC


scikit-learn

scikit-learn Sprint in Salta, Argentina

Author: Author IconJuan Martín Loyola

In September of 2022, the SciPy Latin America conference will take place in Salta, Argentina. As part of the event, we are organizing a scikit-learn sprint for the people attending. The main idea is to introduce the participants to the open source world and help them make their first contribution. The sprint event is in-person.

SciPy logo

Schedule

Repository

For more information in Spanish about the Sprint and how to prepare for it, check this repository.

August 09, 2022 12:00 AM UTC

August 08, 2022


Real Python

Python News: What's New From July 2022

In July 2022, Python reached for the stars, playing a key role in processing data from the James Webb Space Telescope. After two years of virtual conferences, EuroPython 2022 took place in Dublin, Ireland. Anaconda celebrated its tenth birthday, and Flask achieved a major milestone on GitHub.

Two new pre-release versions of Python 3.11 were released, with 3.11.0b5 representing the final beta version. Meanwhile, the Python Package Index (PyPI) introduced a two-factor authentication requirement for maintainers of critical projects. Finally, RStudio is changing its name and has released Shiny for Python.

Extra, extra! Read all about the exciting Python news from the past month!

Join Now: Click here to join the Real Python Newsletter and you'll never miss another Python tutorial, course update, or post.

Python Goes to Space

Well, perhaps it’s more accurate to say that Python brought space down to Earth. The James Webb Space Telescope (JWST) made headlines worldwide when NASA and U.S. President Joe Biden unveiled its first images. The full gallery is visually spectacular and scientifically groundbreaking, as it’s full of the deepest infrared images of the universe yet.

This work was made possible by Python. As Dr. Patrick Kavanagh, researcher and Mid-Infrared Instrument (MIRI) software developer for the Dublin Institute for Advanced Studies, said in his talk at EuroPython 2022:

Ninety percent—or more, probably—of the analysis tools, the simulators, and so on were developed in Python […] and use Python. (Source)

For example, the JWST Science Calibration Pipeline runs on Python with some C plugins for speed. Webb’s images are processed as NumPy arrays, and data scientists at the Space Telescope Science Institute rely on SciPy and Jupyter notebooks, as well as the institute’s own AstroConda channel.

If you’d like to try your hand at working with astronomical data, then you’re in luck! Webb’s data is freely available, and you can prepare to get out of this world in three steps:

  1. Create a virtualenv or conda environment.
  2. Activate your environment.
  3. Install the jwst package using pip.

Now you’re just about ready to play. But before you blast off, you’ll need to download raw data from Barbara A. Mikulski Archive for Space Telescopes (MAST). There’s a ton of data, and it can be complicated to get what you want. Luckily, AstroExploring has a how-to blog and video to help you out.

To learn more about Python’s role in this new frontier, check out Python and the James Webb Space Telescope from the Talk Python to Me podcast. Be sure to share your astronomical discoveries in the comments below!

Dublin Hosts EuroPython 2022

Read the full article at https://realpython.com/python-news-july-2022/ »


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

August 08, 2022 02:00 PM UTC


Python Insider

Python 3.11.0rc1 is now available


This is the first release candidate of Python 3.11

https://www.python.org/downloads/release/python-3110rc1/

This release, **3.11.0rc1**, is the penultimate release preview.  Entering the release candidate phase, only reviewed code changes which are clear bug fixes are allowed between this release candidate and the final release. The second candidate and the last planned release preview is currently planned for Monday, 2022-09-05 while the official release is planned for Monday, 2022-10-03.

There will be no ABI changes from this point forward in the 3.11 series and the goal is that there will be as few code changes as possible.

Call to action

Core developers: all eyes on the docs now

* Are all your changes properly documented?

* Did you notice other changes you know of to have insufficient documentation?

Community members

We strongly encourage maintainers of third-party Python projects to prepare their projects for 3.11 compatibilities during this phase. As always, report any issues to the Python bug tracker.

Please keep in mind that this is a preview release and its use is **not** recommended for production environments.

Major new features of the 3.11 series, compared to 3.10

Among the new major new features and changes so far:

  • PEP 657 – Include Fine-Grained Error Locations in Tracebacks
  • PEP 654 – Exception Groups and except*
  • PEP 673 – Self Type
  • PEP 646 – Variadic Generics
  • PEP 680 – tomllib: Support for Parsing TOML in the Standard Library
  • PEP 675 – Arbitrary Literal String Type
  • PEP 655 – Marking individual TypedDict items as required or potentially-missing
  • bpo-46752 – Introduce task groups to asyncio
  • PEP 681 – Data Class Transforms
  • bpo-433030– Atomic grouping ((?>…)) and possessive quantifiers (*+, ++, ?+, {m,n}+) are now supported in regular expressions.
  • The Faster Cpython Project is already yielding some exciting results. Python 3.11 is up to 10-60% faster than Python 3.10. On average, we measured a 1.22x speedup on the standard benchmark suite. See Faster CPython for details.
  • (Hey, fellow core developer, if a feature you find important is missing from this list, let Pablo know.)

The next pre-release of Python 3.11 will be 3.11.0rc2, currently scheduled for  Monday, 2022-09-05.

More resources

And now for something completely different

A quark star is a hypothetical type of compact, exotic star, where extremely high core temperature and pressure have forced nuclear particles to form quark matter, a continuous state of matter consisting of free quarks. 

Some massive stars collapse to form neutron stars at the end of their life cycle, as has been both observed and explained theoretically. Under the extreme temperatures and pressures inside neutron stars, the neutrons are normally kept apart by degeneracy pressure, stabilizing the star and hindering further gravitational collapse. However, it is hypothesized that under even more extreme temperature and pressure, the degeneracy pressure of the neutrons is overcome, and the neutrons are forced to merge and dissolve into their constituent quarks, creating an ultra-dense phase of quark matter based on densely packed quarks. In this state, a new equilibrium is supposed to emerge, as a new degeneracy pressure between the quarks, as well as repulsive electromagnetic forces, will occur and hinder total gravitational collapse.

If these ideas are correct, quark stars might occur, and be observable, somewhere in the universe. Theoretically, such a scenario is seen as scientifically plausible, but it has been impossible to prove both observationally and experimentally because the very extreme conditions needed for stabilizing quark matter cannot be created in any laboratory nor observed directly in nature. The stability of quark matter, and hence the existence of quark stars, is for these reasons among the unsolved problems in physics.

We hope you enjoy the 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.

August 08, 2022 01:17 PM UTC


Python for Beginners

Check if a String is Empty or Whitespace in Python

Strings in Python are used for handling text data. While doing operations on text data, we may need to remove empty strings or whitespaces. When we print an empty string or whitespaces, we cannot differentiate between the two. In this article, we will discuss different ways to check if a string is empty or whitespace in Python. This will help you to differentiate between an empty string and whitespace.

Check if a String is Empty or Whitespace in Python Using the Equality Operator

To check if a string is empty using the equality operator, we can just compare the string with another empty string. If the result is True, the input string is empty. Otherwise not.

input_string=""
print("The input string is:",input_string)
if input_string=="":
    print("Input string is an empty string.")

Output:

The input string is: 
Input string is an empty string.

To check whether the string contains only whitespace characters, you can compare it with an empty string. If the result is False, the string will be containing whitespace characters. You can observe this in the following example.

input_string=" "
print("The input string is:",input_string)
if input_string=="":
    print("Input string is an empty string.")
else:
    print("Input string is a whitespace character.")

Output:

The input string is:  
Input string is a whitespace character.

Here, an input string that contains characters other than whitespaces will also return False as shown below.

input_string="Aditya"
print("The input string is:",input_string)
if input_string=="":
    print("Input string is an empty string.")
else:
    print("Input string is a whitespace character.")

Output:

The input string is: Aditya
Input string is a whitespace character.

In the above example, you can see that we have used the string “Aditya”. However, the program tells us that the string contains only whitespaces. Hence, the program is logically incorrect. Therefore, you can use this approach only when you are sure that the input string will either be an empty string or will contain only whitespace characters.

Using len() Function to Check if a String is Empty or Whitespace in Python

The len() function is used to find the length of an iterable object such as a list, string, tuple, etc. It takes the iterable object as its input argument and returns the length of the iterable object.

To check if a string is empty or whitespace using the len() function in Python, we will use the following steps.

You can observe this in the following example.

input_string=""
print("The input string is:",input_string)
str_len=len(input_string)
if str_len==0:
    print("Input string is an empty string.")
else:
    print("Input string is a whitespace character.")

Output:

The input string is: 
Input string is an empty string.

Again, if an input string contains characters other than whitespaces, the program will give wrong results as shown below.

input_string = "Aditya"
print("The input string is:", input_string)
str_len = len(input_string)
if str_len == 0:
    print("Input string is an empty string.")
else:
    print("Input string is a whitespace character.")

Output:

The input string is: Aditya
Input string is a whitespace character.

Again, you can see that we have used the string “Aditya”. However, the program tells us that the string contains only whitespaces. Hence, the program is logically incorrect. Therefore, you can use this approach only when you are sure that the input string will either be an empty string or will contain only whitespace characters.

Using the not Operator to Find if a String is Empty or Whitespace in Python

We can also use the not operator to check if a string is empty or whitespace in Python. 

In Python, all the iterable objects like strings, lists, and tuples evaluate to False when they are empty. Therefore, an empty string evaluates to False. 

To check if a string is empty or whitespace using the not operator, we will use the not operator on the input string. If the string is empty, the string will evaluate False. Then, the not operator will convert the result to True. 

Hence, if the output is True, we will say that the string is empty. Otherwise, we will say that the string contains whitespaces. You can observe this in the following example.

input_string = ""
print("The input string is:", input_string)
if not input_string:
    print("Input string is an empty string.")
else:
    print("Input string is a whitespace character.")

Output:

The input string is: 
Input string is an empty string.

Again, if the input string contains characters other than whitespaces, the program will say that the string contains only whitespaces. Therefore, you can use this approach only when you are sure that the input string will either be an empty string or will contain only whitespace characters.

Using For Loop to Check if a String is Empty or Whitespace in Python

There are six whitespace characters in python namely space “ ”, tab “\t”, newline “\n”, vertical tab ”\v”, carriage return “\r”, and  “\f” feed. We can use a list of these whitespace characters and a for loop to check if a string is empty or whitespace in python. For this, we will use the following steps.

You can observe the entire process in the following example.

input_string = "    "
whitespaces = [" ", "\t", "\n", "\v", "\r", "\f"]
print("The input string is:", input_string)
isWhiteSpace = True

if input_string == "":
    print("Input string is an empty string.")
else:
    for character in input_string:
        if character in whitespaces:
            continue
        else:
            isWhiteSpace = False
            break
if isWhiteSpace:
    print("The string contains only whitespace characters.")
else:
    print("The string contains characters other than whitespaces.")

Output:

The input string is: 
The string contains only whitespace characters.

Using List Comprehension to Find if a String is Empty or Whitespace in Python

List comprehension is used to create a list from an existing iterable object. However, we can use the all() function and list comprehension to check if an input string is empty or whitespace in Python. 

The all() function takes an iterable object as its input argument. It returns True if all the elements of the iterable object evaluate to True. Otherwise, it returns False.

To check if a string is empty or whitespace using list comprehension in Python, we will use the following steps.

You can observe the entire process in the following example.

input_string = "    "
whitespaces = [" ", "\t", "\n", "\v", "\r", "\f"]
print("The input string is:", input_string)
if input_string == "":
    print("Input string is an empty string.")
else:
    myList = [True for character in input_string if character in whitespaces]
    output = all(myList)
    if output:
        print("The string contains only whitespace characters.")
    else:
        print("The string contains characters other than whitespaces.")

Output:

The input string is: 
The string contains only whitespace characters.

Check if a String is Empty or Whitespace in Python Using the strip() Method

The strip() method is used to remove leading or trailing spaces from a string. When invoked() on a string, removes the leading and trailing spaces from the string. After execution, it returns the modified string.

To check if a string is empty or whitespace in Python, we will use the following steps.

You can observe the entire process in the following example.

input_string = "   . "
print("The input string is:", input_string)
if input_string == "":
    print("Input string is an empty string.")
else:
    newStr = input_string.strip()
    if newStr == "":
        print("The string contains only whitespace characters.")
    else:
        print("The string contains characters other than whitespaces.")

Output:

The input string is:    . 
The string contains characters other than whitespaces.

This approach works well even with the strings that contain characters other than whitespaces. Hence, you can use this approach in every situation.

Check if a String is Empty or Whitespace in Python Using the isspace() Method

The isspace() method is used to check if a string contains only whitespace characters. When invoked on a string, the isspace() method returns True if the string consists of only whitespace characters. Otherwise, it returns False.

To check if a string is empty or whitespace in Python using the isspace() method, we will use the following steps.

You can observe this in the following example.

input_string = "  A "
print("The input string is:", input_string)
if input_string == "":
    print("Input string is an empty string.")
elif input_string.isspace():
    print("The string contains only whitespace characters.")
else:
    print("The string contains characters other than whitespaces.")

Output:

The input string is:   A 
The string contains characters other than whitespaces.

Again, this approach works well even with the strings that contain characters other than whitespaces. Hence, you can use this approach in every situation.

Check if a String is Empty or Whitespace in Python Using Regular Expressions

Regular expressions are used to efficiently manipulate strings in python. We can also use regular expressions to check if a given string is empty or whitespace. For this, we will use the search() function.

The search() function takes a string pattern as its first input argument and a string as its second input argument. After execution, it returns a match object. If the substrings in the input string given as the second input argument to the search() function match the pattern given as the first input argument, the match object is not None. If the pattern does not exist in the string, the match object will be None.

To check if a given string is empty or whitespace character using the search() function, we will use the following steps.

You can observe this in the following example.

from re import search

input_string = "   "
pattern = "\\S"
print("The input string is:", input_string)
if input_string == "":
    print("Input string is an empty string.")
else:
    match_object = search(pattern, input_string)
    if match_object is None:
        print("The string contains only whitespace characters.")
    else:
        print("The string contains characters other than whitespaces.")

Output:

The input string is:    
The string contains only whitespace characters.

Conclusion

In this article, we have discussed different ways to check if a string is empty or whitespace in Python. Out of all three approaches, the approach using equality operator, not operator, and the len() function are logically incorrect. They can be used only when we are sure that the input string will either be empty strings or will consist of only whitespace characters.

The approaches using the strip() method, the isspace() method, and the re.search() function are robust. These approaches can be used in all cases. Therefore, I suggest you use these approaches to check if a given string is empty or whitespace in Python.

To learn more about programming, you can read this article on data modeling tools. You might also like this article on regression in machine learning. You can also have a look at this article on data analyst vs data scientist that compares the salaries, education, and job responsibilities of a data analyst and a data scientist.

The post Check if a String is Empty or Whitespace in Python appeared first on PythonForBeginners.com.

August 08, 2022 01:00 PM UTC


Mike Driscoll

PyDev of the Week: Wolf Vollprecht

This week we welcome Wolf Vollprecht (@wuoulf) as our PyDev of the Week! Wolf is a core maintainer of mamba, a Fast Cross-Platform Package Manager as well as xtensor, a C++ library meant for numerical analysis with multi-dimensional array expressions.

You can see some of what Wolf has been working on over on GitHub. Let's take a few moments to get to know Wolf better!

Can you tell us a little about yourself (hobbies, education, etc):

I am Wolf, and currently the CTO of QuantStack. I started programming on a TI 83-Plus, using Basic, and then continued to learn PHP to work in a web agency. When I started university, I participated in the Ubuntu App Challenge (that was back in 2012). For that I worked on a little GTK based Markdown editor (called Uberwriter, now Apostrophe), and that was the first time I started to use Python seriously. Later I worked on a little robot called Beachbot that draws pictures in the sand, then I did a master in Robotics. I had a vision of working for an open source company and also contributed to xtensor, a C++ library with Python bindings, and one of the first QuantStack projects. That led to me joining QuantStack 5 years ago.

Why did you start using Python?

I started using Python to work on Uberwriter! I very much like the language and the powerful expressiveness. After Uberwriter, I dabbled in some other personal projects, for example “SilverFlask”, a CMS based on Flask and SQLAlchemy, which was heavily inspired by PHPs SilverStripe. SilverFlask never went anywhere, but I learned a lot about abstract base classes and meta classes in Python which still helps me to this day. Later I was working on a Python to C++ compiler called PyJet, based on expression graphs, which also taught me a lot about Python and how hard it is to capture the dynamic nature of the language.

What other programming languages do you know and which is your favorite?

I work a lot with C++, but I do not like it too much. It’s quite verbose, and a pretty old school language (although one can do very fast and complicated things with it). Especially error messages are not great when templates are involved!
I also know Javascript quite well, and also do not like it much. It’s not a very “well thought out” language, and it doesn’t support operator overloading. What I like about Javascript is that it has very powerful Just-In-Time compilation engines.
There are some up-and-coming programming languages that look like an interesting cross-over of “compiled” language & Python — for example Nim and Zig. My dream language would be compileable, but also interpretable (so that one can run macros at compile time _in the language itself_). I think Zig is getting close to that. There is also a new ahead-of-time Python compiler called LPython that seems promising (but still quite early!).

What projects are you working on now?

I am currently working on the definitive package management solution across all platforms. This project is called “mamba” and is a package manager that uses “conda” packages. Mamba works on all platforms (Windows, macOS and Linux). I am also part of the largest community that provides these packages, the conda-forge community. We’re proud to have more than 4000 individual contributors that are providing packages for 6 different platforms: Windows, 3 Linux versions (Intel, Arm and PowerPC), as well as macOS (intel and Apple Silicon).
Most conda-forge packages are Python and data science related. However, we also have a large collection of packages for the R programming language, as well as many packages in C and C++, Go and Rust. We’re really trying to bring everyone together in a single package management system!

I am also working on two packages in the “mamba-ecosystem”: one is boa, a package builder and the other one is quetz, a package server. Both are pure Python packages. Quetz is using FastAPI and that has worked pretty nicely for us.

Which Python libraries are your favorite (core or 3rd party)?

Very good question. I could use the occasion to advertise some of the Python libraries we work on at QuantStack: ipywidgets, ipycanvas, ipyleaflet, bqplot — all these help to make powerful user interfaces in Jupyter notebooks. JupyterLab and Voila are also great, of course!

In general, I really like our usage of “rich" and “prompt_toolkit" in boa, it helps a lot with nice terminal user interfaces. There are many well thought out Python libraries!

How did you end up working on mamba?

Back in the days, conda was really slow (that was before they added some optimisations that helped). Conda-forge was growing faster and faster. And I had this crazy idea to build out all the robotics packages of the ROS ecosystem (this is still ongoing in the robostack project). There are many ROS packages in any given environment and it seemed infeasible to make it work with the limitations of conda.

Thus I started to toy around with libsolv to see if it would be faster (as an alternative SAT solver implementation, as that was the really slow part. Michael Schröder from openSUSE implemented most necessary pieces in libsolv itself, and the rest is history!

What do you think Python does best in the data science field?

I think the what makes Python strong, in general but also in data science, is that it is a great glue language between high level dynamic code (Python) and low-level FORTRAn, C or C++ code. It is really straightforward to write your own high-speed Python extensions in C++ using pybind11, or in Rust using pyo3. This has enabled many of the popular data science libraries such as NumPy, Pandas, the scikit-learn and scikit-image libraries, Tensorflow, PyTorch, …

Is there anything else you’d like to say?

We’ve recently started to think seriously about Webassembly! We’ve worked on JupyterLite (a really great tool to run Python in the browser, e.g. for interactive documentation!). also we are trying to prepare conda-forge for Webassembly packages. That is really exciting work and is happening in the “emscripten-forge” organization on Github.

Thanks for doing the interview, Wolf!

The post PyDev of the Week: Wolf Vollprecht appeared first on Mouse Vs Python.

August 08, 2022 12:30 PM UTC

August 07, 2022


PyCharm

The PyCharm 2022.2.1 Release Candidate Is Now Available!

We’re working closely with your feedback on the PyCharm 2022.2 version that was released last week. Thank you for sharing with us! If you encounter an issue in PyCharm 2022.2, please reach out to our support team. We are actively fixing regressions, and will be delivering a minor bug-fix release soon.

You can get the new build from our page, via the free Toolbox App, or by using snaps for Ubuntu. 

Today, the release candidate for the first minor update is available. Here are the major fixes:

We’re working on fixes for the following recent regressions with local and remote interpreters – stay tuned:

If you encounter any bugs or have feedback to share, please submit it to our issue tracker, via Twitter, or in the comments section of this blog post.

August 07, 2022 08:22 AM UTC

August 06, 2022


Test and Code

192: Learn to code through game development with PursuedPyBear - Piper Thunstrom

The first game I remember coding, or at least copying from a magazine, was in Basic. It was Lunar Lander.

Learning to code a game is a way that a lot of people get started and excited about programming.

Of course, I don't recommend Basic. Now we've got Python. And one of the game engines available for Python is PursuedPyBear, a project started by Piper Thunstrom.

Piper joins us this episode and we talk about PursuedPyBear, learning to code, and learning CS concepts with game development.

PursuedPyBear, ppb, is a game framework great for learning with, with goals of being fun, education friendly, an example of idiomatic Python, hardware library agnostic, and built on event driven and object oriented concepts.

Special Guest: Piper Thunstrom.

Sponsored By:

Links:

<p>The first game I remember coding, or at least copying from a magazine, was in Basic. It was Lunar Lander. </p> <p>Learning to code a game is a way that a lot of people get started and excited about programming. </p> <p>Of course, I don&#39;t recommend Basic. Now we&#39;ve got Python. And one of the game engines available for Python is PursuedPyBear, a project started by Piper Thunstrom. </p> <p>Piper joins us this episode and we talk about PursuedPyBear, learning to code, and learning CS concepts with game development. </p> <p>PursuedPyBear, ppb, is a game framework great for learning with, with goals of being fun, education friendly, an example of idiomatic Python, hardware library agnostic, and built on event driven and object oriented concepts.</p><p>Special Guest: Piper Thunstrom.</p><p>Sponsored By:</p><ul><li><a href="http://rollbar.com/testandcode" rel="nofollow">Rollbar</a>: <a href="http://rollbar.com/testandcode" rel="nofollow">With Rollbar, developers deploy better software faster.</a></li></ul><p>Links:</p><ul><li><a href="https://ppb.dev/" title="PursuedPyBear | Unbearably Fun Game Development" rel="nofollow">PursuedPyBear | Unbearably Fun Game Development</a></li><li><a href="https://piper.thunstrom.dev/" title="Piper's Blog" rel="nofollow">Piper's Blog</a></li><li><a href="https://www.youtube.com/watch?v=bbKED0o3uVU" title="Making Games With PPB - PyTexas" rel="nofollow">Making Games With PPB - PyTexas</a></li><li><a href="https://pathunstrom.itch.io/shooter-game" title="Shooter Game by Piper Thunstrom" rel="nofollow">Shooter Game by Piper Thunstrom</a></li><li><a href="https://github.com/pathunstrom/shootergame" title="shootergame on GitHub" rel="nofollow">shootergame on GitHub</a></li><li><a href="https://beeware.org/project/projects/tools/briefcase/" title="Briefcase— BeeWare" rel="nofollow">Briefcase— BeeWare</a></li><li><a href="https://github.com/pathunstrom/game-blink" title="game-blink: A tiny emergent behavior toy." rel="nofollow">game-blink: A tiny emergent behavior toy.</a></li><li><a href="https://en.wikipedia.org/wiki/Combat_(Atari_2600)" title="Combat (Atari 2600)" rel="nofollow">Combat (Atari 2600)</a> &mdash; The tank game I didn't remember the name of.</li><li><a href="https://en.wikipedia.org/wiki/Lunar_Lander_(video_game_genre)" title="Lunar Lander" rel="nofollow">Lunar Lander</a></li></ul>

August 06, 2022 11:15 PM UTC


IslandT

Move the image across the screen with Pygame

In this chapter, I am going to show you a simple python program that will move the image across the screen by clicking and then dragging it within the screen. While the image is in the dragging state I will make it semi-opaque. The game plan here is to set a few flags and basically make the image follow our mouse cursor.

Below is the entire code, why don’t you try it yourself?

# Import and initialize the pygame library
import pygame
pygame.display.init()

# set the caption on the panel
pygame.display.set_caption("Draw Some Drawing")

# windows height and width
windowwidth = 600
windowheight = 600

# Print this line on output panel if the initialize process is successful
if(pygame.display.get_init() == True):
    print("Success initialize the game!")

# Initialize a window or screen for display
screen = pygame.display.set_mode([windowwidth, windowheight])

# Print the x, y size of the game display window

print("The windows size is " + str(pygame.display.get_window_size()))

circle_center_x = 300 # set the circle initial coordinates, set its radius as well
circle_center_y = 300
circle_radius = 60

# set the mouse press coordinates
mouse_press = False
mouse_coordinate_x = 0
mouse_coordinate_y = 0

# hat image load
pawn0 = pygame.image.load("pawn.png")
width, height = pawn0.get_size() # return width and height of the hat
# the initial position of the hat image
original_image_x = circle_center_x-width/2
original_image_y = circle_center_y-circle_radius-height

# Run the game until the user asks to quit
running = True
while running:

    # If the user clicks on the 'x' button on pygame display window then set running to false
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill the rectangles with blue color
    screen.fill((0,0,255))

    # check the left mouse button press state
    left_mouse_button_press_state = pygame.mouse.get_pressed(num_buttons=3)[0]

    if (left_mouse_button_press_state == True and mouse_press == False):
        mouse_coordinate_x, mouse_coordinate_y = pygame.mouse.get_pos()
        if (mouse_coordinate_x >= original_image_x and mouse_coordinate_x <= original_image_x + width and mouse_coordinate_y >= original_image_y and mouse_coordinate_y <= original_image_y + height):
            mouse_press = True
    elif (left_mouse_button_press_state == True and mouse_press == True):
        original_image_x, original_image_y = pygame.mouse.get_pos()
        pawn0.set_alpha(100)
    elif (left_mouse_button_press_state == False and mouse_press == True):
        mouse_press = False
        original_image_x, original_image_y = pygame.mouse.get_pos()
        pawn0.set_alpha(255)

    pygame.draw.circle(screen, pygame.Color(255,255,255), (circle_center_y, circle_center_y), circle_radius) # Draw white circle at the middle of screen

    screen.blit(pawn0, (original_image_x, original_image_y)) # drawing the hat

    pygame.display.flip() # refresh the display screen

# Quit the game
pygame.display.quit()

Here are a few outcomes, you can do it better by slightly adjusting the mathematical part of the equation!

Now it is time for me to get back to continue research on Pygame!

August 06, 2022 12:27 PM UTC

August 05, 2022


Python for Beginners

Remove a Character From a String in Python

We use strings in Python to manipulate text data. While analyzing text data we might need to remove some characters from our data. In this article, we will discuss different ways to remove a character from a string in Python.

Remove a Character From a String in Python Using For Loop

We use a for loop to iterate through the elements of an iterable object. We will use the following approach to remove a character from a string using the for loop in Python.

After execution of the for loop, we will get the output string in the variable newStr. You can observe this in the following example.

input_string = "Adcictcya"
char_to_remove = "c"
newStr = ""
for character in input_string:
    if character != char_to_remove:
        newStr += character

print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

Here, you can see that we have removed the character ‘c‘ from the input string ‘Adcictcya‘ to produce the output string ‘Aditya‘.

Using List Comprehension to Remove a Character From a String in Python

Instead of using a for loop, we can use list comprehension to remove a character from an input string in Python. For this, we will use the following approach.

input_string = "Adcictcya"
char_to_remove = "c"
myList = [character for character in input_string if character != char_to_remove]
newStr = ""
for character in myList:
    newStr += character

print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

After creating myList, we can use the join() method instead of the for loop to create the output string. 

The join() method, when invoked on a separator string, takes an iterable object as its input argument. After execution, it returns a string in which all the elements of the iterable object are separated by the separator. 

We will use the following approach to remove a character from a string in python using the list comprehension and the join() method. 

You can observe this in the following example.

input_string = "Adcictcya"
char_to_remove = "c"
myList = [character for character in input_string if character != char_to_remove]
separator = ""
newStr = separator.join(myList)

print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

Remove a Character From a String in Python Using the split() Method

The split() method is used to split a string into substrings. When invoked on a string, it takes a character as its input argument. After execution, it returns a list of substrings of the original string split at the given character.

To remove a character from a string in Python using the split() method, we will use the following steps.

After execution of the for loop, we will get the required output string in the variable myStr. You can observe this in the following example.

input_string = "Adcictcya"
char_to_remove = "c"
myList = input_string.split(char_to_remove)
newStr = ""
for element in myList:
    newStr += element

print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

Instead of using the for loop and string concatenation to create the output string from myList, we can use the join() method as follows.

You can observe the entire process in the following example.

input_string = "Adcictcya"
char_to_remove = "c"
myList = input_string.split(char_to_remove)
separator = ""
newStr = separator.join(myList)

print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

Using the filter() Function to Remove a Character From a String in Python

The filter() function is used to filter the elements of an iterable object based on a condition. The filter() function takes another function as its first input argument and an iterable object as its second input argument. The function given as the first input argument must take the elements of the iterable object as its input and return True or False for each element.

After execution, the filter() function returns an iterator containing all the elements of the iterable object given in the input argument for which the function given in the first input argument returns True. 

To remove a character from a given string using the filter function, we will use the following steps.

After execution of the for loop, we will get the required output string in the variable newStr. You can observe this in the following example.

def myFun(character):
    char_to_remove = "c"
    return character != char_to_remove


input_string = "Adcictcya"
char_to_remove = "c"
filter_object = filter(myFun, input_string)
myList = list(filter_object)
newStr = ""
for element in myList:
    newStr += element

print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

You can also use the join() method to create the output string using the following steps.

You can observe the entire process in the following example.

def myFun(character):
    char_to_remove = "c"
    return character != char_to_remove


input_string = "Adcictcya"
char_to_remove = "c"
filter_object = filter(myFun, input_string)
myList = list(filter_object)
separator = ""
newStr = separator.join(myList)

print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

Instead of using myFun, you can use a lambda expression with the filter() function as shown below.

input_string = "Adcictcya"
char_to_remove = "c"
filter_object = filter(lambda character:character!=char_to_remove, input_string)
myList = list(filter_object)
separator = ""
newStr = separator.join(myList)

print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

Here, the lambda expression does the same task as myFun did in the previous code.

Remove a Character From a String in Python Using the replace() Method

The replace() method is used to replace one character with another in a string. You can also remove a character from a string using the replace() method. When invoked on a string, the replace() method takes the character that needs to be replaced as its first argument and the new character as its second input argument. After execution, it returns the modified string.

To remove a character from a string using the replace() method, we will invoke the replace() method on the original string. Here, will pass the character that needs to be removed as the first input argument and an empty string as the second input argument to the replace() method. 

After execution, the replace() method will return the output string. You can observe this in the following example.

input_string = "Adcictcya"
char_to_remove = "c"
newStr = input_string.replace(char_to_remove, "")

print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

Using the translate() Method to Remove a Character From a String in Python

The translate() method is also used to replace characters in a string. The translate() method, when invoked on a string, takes a translation table as its input argument. After execution, it returns the modified string.

To remove a character from a given string, we will first make a translation table. For this, we can use the maketrans() method. 

The maketrans() method, when invoked on a string, takes a string of characters as its first argument and another string containing the same number of characters as its first argument in its second input argument. After execution, it returns a translation table.

After execution of the for loop, we will get the required output string in the variable newStr. You can observe this in the following example.

input_string = "Adcictcya"
char_to_remove = "c"
translation_table = input_string.maketrans(char_to_remove, " ")
tempStr = input_string.translate(translation_table)
myList = tempStr.split()
newStr = ""
for element in myList:
    newStr += element
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

Instead of using a for loop and string concatenation, you can use the join() method to create the output string from myList. For this, you can use the following steps.

You can observe the entire process in the following example.

input_string = "Adcictcya"
char_to_remove = "c"
translation_table = input_string.maketrans(char_to_remove, " ")
tempStr = input_string.translate(translation_table)
myList = tempStr.split()
separator=""
newStr = separator.join(myList)
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

The approach using the translate() method only works for the strings that do not contain whitespace characters. So, you must not use this approach in case the input string has a whitespace character in it. 

Remove a Character From a String in Python Using Regular Expressions

Regular expressions provide us with various functions for string manipulation in Python. You can also remove a character from a string in Python using regular expressions. For this, we will use the sub() function.

The sub() function is used to replace characters in a string. It takes three input arguments. The first input argument is the character that needs to be replaced. The second argument is the replacement character. Lastly, the third input argument is the original string. After execution, the sub() function returns the new string.

To remove a character from a string using the sub() function, we will use the following step.

You can observe this in the following example.

import re

input_string = "Adcictcya"
char_to_remove = "c"
newStr = re.sub(char_to_remove, "", input_string)
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)

Output:

The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya

Conclusion

In this article, we have discussed different ways to remove a character from a string in Python. Out of all these approaches, the approach using the re.sub() function and the replace() method are the most efficient. Hence, you should use these two approaches to remove a character from a string in Python.

To learn more about python programming, you can read this article on how to remove all occurrences of a character from a list or string in Python. You might also like this article on regression in machine learning. You might also have a look at this article on data analyst vs data scientist.

Stay tuned for more informative articles. Happy Learning!

The post Remove a Character From a String in Python appeared first on PythonForBeginners.com.

August 05, 2022 01:00 PM UTC


Real Python

The Real Python Podcast – Episode #120: Inspiring Young People to Learn Python With Mission Encodeable

Is there someone in your life you'd like to inspire to learn Python? Mission Encodeable is a website designed to teach people to code, built by two high-school students. This week on the show, Anna and Harry Wake talk about creating their site and motivating people to start coding.


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

August 05, 2022 12:00 PM UTC


PyBites

The importance of setting boundaries

Listen here:

This week we talk about boundaries (again), specially at work.

How can it be that 12 hour days are becoming the norm?

This has to stop!

And it’s insidious, because the extra work always seems to sneak in!

First we look at where we think this is coming from.

Then we offer some practical tips we’ve learned over the years that will have you better manage this.

Books we’re reading:
– The missing Readme
– Robust Python (type hints)
– The Insider’s Guide to Culture Change
– They are part of our Podcast reading list.

If you struggle with boundaries, get a copy of our Productivity course, you won’t regret it because implementing what you learn there will save you at least 1-2 hours daily!

And to combine these type of career skills with highly specialized Python + dev skills, come talk to us how our approach / coaching can turn you into a well rounded developer faster.

August 05, 2022 10:49 AM UTC

August 04, 2022


Python Engineering at Microsoft

Python in Visual Studio Code – August 2022 Release

We’re excited to announce that the August 2022 release of the Python and Jupyter extensions for Visual Studio Code are now available!

This release includes the following improvements:

If you’re interested, you can check the full list of improvements in our changelogs for the Python, Jupyter and Pylance extensions.

Automatic debug configurations for web apps

To simplify the process of setting up VS Code to run and/or debug your web applications, this release includes new automatic debug configurations for projects that use Flask, Django or FastAPI.

When you open the Run and Debug view in VS Code (Ctrl + Shift + D or ⌘+ ⇧ + D) and there is no debugger configuration (i.e., no launch.json file) on your workspace, you will see an “show all automatic debug configurations” option. If your project is a web application that follows the format expected by Flask, Django or FastAPI, once you click on that option you will be able to see debug configurations that were dynamically created to execute and debug your project. Now you can just select it to start catching all the bugs!

Debugging a FastAPI application by selecting an dynamically created debug configuration for FastAPI. Theme: Pink-Cat-Book

Improvements to the Getting Started Experience

The Python extension walkthrough has been improved to more easily guide users to installing Python when needed, and selecting it in VS Code. When Python is not installed on a Windows machine, selecting the “Install Python” button from the walkthrough will open the Python app in the Microsoft Store. When on Linux or macOS, the displayed installation instructions will be automatically run in the terminal.

Another improvement related to the getting started experience is that notifications for selecting the interpreter are now only shown when an interpreter is required (e.g. when running or debugging a file, or a tool such as a linter or formatter), and no longer on start-up. Other notification prompts have also been improved to be more precise about errors and suggested changes.

Python extension walkthrough with a create Python file button.

Python interpreter display on the status bar

We introduced a new User setting called “python.interpreter.infoVisibility”, which controls when the selected interpreter information is displayed in the status bar. You can set "python.interpreter.infoVisibility": “always” on your User settings (Preferences > Command Palette… > Open User Settings (JSON)) to always display it regardless of what file is opened. By default, it’s only displayed when Python-related files are open on the editor ("python.interpreter.infoVisibility": “onPythonRelated”). If you’d like to hide it completely, set "python.interpreter.infoVisibility": “never”.

A warning status was also added to indicate situations when the selected interpreter is invalid:

A warning icon and a different background color is displayed on the status bar when the selected Python interpreter is invalid.

Python Tools extension template

With all the work we have been doing to enable formatting and linting with Black, pylint, and isort to work behind the Language Server Protocol, we realized how simple we could make it to create an extension for mostly any Python linter or formatter without the need to require TypeScript knowledge (which is the language VS Code and its extensions are written in).

To that end, our team has created a template that allows you to create a VS Code extension for your favorite Python linter or formatter by changing mostly Python code (unless you’re planning to add more settings or custom logic to it – then you’ll need to work with a bit of TypeScript).

To try it out, you can follow the instructions in the repository. If at the end you’d like to publish your new extension (and maintain it, after all with great power comes great responsibility), you can follow the steps on the “Publishing Extensions” documentation.

And If you have any feedback on this new template, please file an issue on the GitHub repo!

Remove all unused imports

Pylance now offers a code action for removing all unused imports when there is more than one library that is being imported but not used or called anywhere in the code. To try it out, open a Python file with such statements and trigger the code action called “Remove all unused imports”: Code action for removing all unused imports displayed when more than one library is imported but not used in the code.Theme: Pink-Cat-Book

You can also configure VS Code to run all available “fix all” code actions when you save your Python files by adding the following configuration to your User settings:

"[python]": {
    "editor.codeActionsOnSave": {
        "source.fixAll": true
    }
}

Double click to accept Type Hints

In the July release, we have added support for variable types and return types inlay hints when using Pylance. In this release, we’re introducing support to accepting the suggested annotations to your code. You can now double click on a hint to add the suggestion to your code:

Adding type suggestions given by Pylance on the editor by double clicking on them.

To learn more about Inlay Type hints and for some tips on how you can best leverage this feature, check out Jay Miller’s explanatory video and blog post on how to “Make Inlay Type Hints in Python Appear/Disappear”.

Copy images to clipboard from Jupyter Notebooks

The new release of the Jupyter extension allows you to copy images from Jupyter notebooks output cells to the clipboard so you can more easily share them outside of VS Code!

To try it out, make sure you change the output presentation to png, by clicking on the icon on the left side of the image you’re trying to copy:

Selecting image/png as the rendered for a Jupyter notebook output image.

Then hover over the image and select the copy button that shows up to the right:

Copy icon displayed on the right of the Jupyter notebook image output

And now you can paste it into your e-mails, documents, reports and even Paint!

Go to most recently failed cell

Another improvement introduced in the latest Jupyter extension release is the ability to navigate to the most recently failed cell. When you run all your cells and one fails, you can click on the “Go To” button on the top of the editor and you will be taken to the one that halted the group execution.

Go to failed cell button displayed on the Jupyter Notebook toolbar.

Other Changes and Enhancements

We have also added small enhancements and fixed issues requested by users that should improve your experience working with Python and Jupyter Notebooks in Visual Studio Code. Some notable changes include:

We would also like to extend special thanks to this month’s contributors:

Try out these new improvements by downloading the Python extension and the Jupyter extension from the Marketplace, or install them directly from the extensions view in Visual Studio Code (Ctrl + Shift + X or ⌘ + ⇧ + X). You can learn more about Python support in Visual Studio Code in the documentation. If you run into any problems or have suggestions, please file an issue on the Python VS Code GitHub page.

 

The post Python in Visual Studio Code – August 2022 Release appeared first on Python.

August 04, 2022 08:56 PM UTC