Upgrade from Python 2 to Python 3 in Abaqus 2024

Are you in trouble running your Python scripts in the latest Abaqus release? Probably yes. Maybe you already knew, but we have to upgrade from Python 2 to Python 3 in Abaqus 2024.

From Abaqus 2024, the Python version in CAE is 3.10! This is a long awaited update (from Python 2.7 to 3.10) that increases even more the possibilities of FEA and pushes the simulation workflow to new limits.

From now on, we can take advantage of lots of Python 3.10 features that were not available in Python 2.7 like: f-strings, dataclasses, pattern matching, data typing, better error messages, easier debugging, performance improvements and so on.

But… as someone said: “with great power comes great responsibility”

This important update may require that you update your ‘old’ Python scripts. Although it sounds like a big hustle, in most cases the changes will be minimal if necessary at all. 

Let’s dive into the implications of this update and how to deal and take advantage of it!

1. From Python 2 to Python 3

Abaqus 2024 has introduced a big update in terms of the Python environment. From now on, Abaqus leaves Python 2.7 aside and Python 3.10 rises!

From the practical point of view, one of the first questions that pops up with this update is:

“Can I use my Python 2.7 scripts and plug-ins as before?”

I recommend you try your scripts in Abaqus 2024 and evaluate whether they still work or not. Even though the update sounds like a huge change, actually is not, and many of your scripts may still work fine. But…

“What if my old Python 2.7 scripts do not work in Abaqus 2024?”

In that case, you will have to upgrade them

You count on 2 main options to upgrade your Python scripts.

  1. Upgrade them automatically.
  2. Upgrade them manually.

1.1. Upgrade your scripts automatically

Abaqus provides a conversion tool that automatically upgrades your scripts from Python 2.7 to Python 3. This utility (abqPy2to3) can be executed from Abaqus/CAE or from the command line.

In Abaqus/CAE

Go to Plug-ins → Abaqus → Upgrade Scripts…

Upgrade Python scripts in Abaqus 2024 plugin

We can upgrade scripts in batch from a directory or select a single file. For instance, in the picture, I’m upgrading a script from Abaqus 2019 to Abaqus 2024, and I will keep a backup of the original file. Before upgrading, we can “Preview changes” on the web browser:

Upgrade Python scripts preview changes diff

In my case, the only lines that changed, address an issue with the zip function. In Python 3.10, the zip function does not return a list, instead it returns an ‘iterable‘ object. That’s why the upgrader utility made that change in my script, converting the iterable into a list explicitly.

Once we have checked the changes, we can click on “Upgrade Script” and that’s it!

Note: an auxiliary window with the log information pops up with the details of the process and the name of the backup file.

In my opinion, running this auto upgrader with the preview is the best way to understand the most relevant changes in our Python scripts

From the command line

Open a command line and execute the following command:

				
					>> abaqus python -m abqPy2to3 <files/directories>
				
			

Notice ‘abaqus‘ command depends on your Abaqus 2024 setup (e.g. abq2024, abq24…). This command accepts either a list of files or a list of directories (relative or absolute paths). In the latter case, it will traverse recursively all the subfolders looking for Python files (with ‘py’ extension).

Find more details about this command in the documentation.

1.2. Upgrade your scripts manually

In very rare cases, the automatic upgrading utility may not work as expected. For instance, in complex scripts that involve other modules or libraries. These Python programs will require some manual intervention from the user. 

From my experience, the most common changes upgrading scripts from Python 2 to Python 3.10 are the following:

  • The print statement is deprecated in favor of print as a function.
				
					# Python 2 accepts both forms
print 'Hello World!'   # print statement
print('Hello World!')  # print function


# Python 3 only accepts print as a function
print('Hello World!')
				
			
  • Functions such as zip or dict.keys and dict.values return iterable objects instead of lists. So, watch out because in some cases you will need to convert them to lists explicitly.
				
					# Some data
px = [0.0, 0.5, 1.0]
py = [0.2, 0.6, 1.0]


# === Python 2 ===
points = zip(px, py)  # List: [(0.0, 0.2), (0.5, 0.6), (1.0, 1.0)]
p1 = points[0]        # Index list
p1, p2, p3 = points   # Unpacking list
for x, y in points:   # Iterate through the list
    pass


# === Python 3 ===
points = zip(px, py)  # Iterable: [(0.0, 0.2), (0.5, 0.6), (1.0, 1.0)]
# p1 = points[0]      # Indexing is NOT allowed in iterables
p1 = list(points)[0]  # Workaround: convert to list
# p1, p2, p3 = points      # Unpacking iterable is NOT allowed
p1, p2, p3 = list(points)  # Workaround: convert to list
for x, y in points:   # Iterating is allowed in iterables
    pass

 
				
			
  • Integer division in Python 3 is represented with //. A regular division between integers (a/b) always results in a float! Look at the first example in the snippet below.
				
					# === Python 2 ===
print(8/3)    # Output: 2
print(8./3)   # Output: 2.66666666666667
print(8.//3)  # Output: 2.0

# === Python 3 ===
print(8/3)    # Output: 2.66666666666667
print(8./3)   # Output: 2.66666666666667
print(8.//3)  # Output: 2.0
				
			

There are a few more subtle changes from Python 2. You can find more examples of these changes in the 3DS Learning Resources.

2. Take advantage of Python 3 in Abaqus 2024

If we compare Python 3.10 with Python 2.7, we find several new features that will make our scripts even more functional and readable!

Let’s comment on these new features:

F-strings

From Python 3.6, we can use the so-called f-strings.

F-strings facilitates including variables into a string through the { } placeholders. Soon you’ll forget the format method.

Check out the power and flexibility of f-strings in the snippet below (more use cases here).

				
					# Example 1 - Basic usage
name = 'Peter'
hello = f'Hello {name}!'
print(hello)
# Output: Hello Peter!

# Example 2 - Format floats
from math import pi
print(f'pi = {pi:f.6}')
# Output: pi = 3.141596

# Example 3 - Inline operations
some_numbers = [2, 4, 8, 16]
print(f'The list contains {len(some_numbers)} items')
# Output: The list contains 4 items

# Example 4 - Debugging variables quick
var1 = 10
var2 = 4
var3 = False
var4 = -1e6
print(f'{var1 = }')
print(f'{var1 + var2 = }')
print(f'{var3 = }, {var4 = :g}')
# Output: var1 = 10
#         var1 + var2 = 14
#         var3 = False, var4 = -1e+06

# Example 5 - Some tricks with strings
title = 'Results'
print(f'{title:20}:')
print(f'{title:^20}:')
print(f'{title:-^20}:')
# Output: Results             :
#               Results       :
#         ------Results-------:

# ---End of file---
				
			

Type hinting

This topic sounds a bit troublesome for Python users, since Python is a dynamically typed language. Does it mean that we have to specify the data types from now on?

Not really. We don’t have to, but we have this option now.

And why shall we declare the types of our variables or the arguments and output of a function?

There are a few reasons to declaring data types (type hinting):

  1. Debugging. Catching some errors becomes easier.
  2. Readability and documentation. If we read the data types required by a function, it”ll be easier to understand the requirements of that function and track down potential bugs.
  3. Improve IDE and linting. If you are coding in PyCharm, VS Code or similar, the IDE will be more helpful and responsive when using type hinting.
  4. Think before writing. Type hints force you to think about your program, in advance: the data types involved, functional aspects (overloaded methods, multiple return types), etc.

Using type hints is highly recommended in medium-sized/large projects where understanding the data flow is critical and potentially save lots of time in the debugging stage.

Note that type hinting has no effects in the Python interpreter. Type hints behave as comments for the interpreter, and there is no gain in computational efficiency or anything like that.

We could say a lot more about this subject… You can find more details about type hints here.

				
					# Type hinting in a function
def myfunction(x: int) -> str:
    return f"Message: {x + 5}"


# Type hinting of a variable
var: int = 10

print(myfunction(var))
# Output: Message: 15
				
			

Dataclasses

If you are into Object Oriented Programming (OOP) by implementing and using your own classes, you’ll love dataclasses.

A Data Class is just that, a class devoted to represent: Data.

Dataclasses provide specific functionalities that streamline the creation of objects such as: default values, direct representation of data (__repr__), attributes initialization, data protection (frozen), and even more. In the snippet below, you can see some of the main features into play (more examples here).

				
					# Import required (decorator)
from dataclasses import dataclass

# Declaration of the dataclass
@dataclass
class importedPart:
    file: str
    dims: int = 3   # default value is 3 (3D)
    info: str = ""  # default value is empty

# Create object
mypart = importedPart(R"C:\CAD\bolt_M3x40.stp", 3, "Bolt M3x40")

print(mypart)
# Output: importedPart(file='C:\\CAD\\bolt_M3x40.stp', dims=3, info='Bolt M3x40')
				
			

Structural Pattern Matching

This is a game-changer if you need to use some sort of switch-case statements. Until now, we had use if-else statements in Python until… Python 3.10!

Structural pattern matching comes to address this gap in Python and it really does! 

We can simply use it to implement some simple menu-like options:

				
					# Option written by the user
option = 'new'

# Structural pattern matching
match option:
    case 'new':
        print('Creating new file')
    case 'save':
        print('Saving current file')
    case other:
        print('Unknown command: {other}')

# Output: Creating new file

				
			

And more sophisticated options too:

				
					# Option written by the user
option = 'open bolted_joint_4x3_M12'

# Structural pattern matching
match option.split():
    case ['new', filename]:
        print(f'Creating new file: {filename}')
    case ['open', filename]:
        print(f'Opening file: {filename}')
    case ['quit'|'close']:  # Matches ['quit',] or ['close',]
        print('Bye bye!')
    case _:  # Matches anything else
        print(f'Unknown command: {option!r}')

# Output: Opening file: bolted_joint_4x3_M12

				
			

Structural pattern matching goes much further by using classes as the matching pattern, variable number of arguments. inline conditions and a lot more (see more cases here). 

3. Conclusions

As we have seen, the introduction of Python 3.10 in Abaqus 2024 involves some important changes in our Python scripts. We have to test and upgrade them if necessary.

However, this update brings many more advantages to the development of modern Python scripts for Abaqus which can now import modern packages like pandas, pytorch, etc. [I am now writing another post about this]

What is more important, this update consolidates Python as the ‘de facto’ programming language for Finite Element Analysis at a global scale across all industries.

If you have any issues with Python 3.10 or upgrading your scripts, please text me:

 

contact@tecnodigitalschool.com

By the way, the “Abaqus Scripting with Python” course is already updated with scripts in Python 3.10 as well, check it out!

I hope that you find these tips useful!

Leave a Comment

Scroll to Top