Categories
Python Answers

How to programmatically set an attribute with Python?

Sometimes, we want to programmatically set an attribute with Python.

In this article, we’ll look at how to programmatically set an attribute with Python.

How to programmatically set an attribute with Python?

To programmatically set an attribute with Python, we call setattr.

For instance, we write

setattr(x, attr, 'magic')

to call the setattr function to set the x‘s attr attribute to 'magic' where attr is a string with the attribute name.

Conclusion

To programmatically set an attribute with Python, we call setattr.

Categories
Python Answers

How to get the first item from an iterable that matches a condition with Python?

Sometimes, we want to get the first item from an iterable that matches a condition with Python.

In this article, we’ll look at how to get the first item from an iterable that matches a condition with Python.

How to get the first item from an iterable that matches a condition with Python?

To get the first item from an iterable that matches a condition with Python, we can use the next function.

For instance, we write

next((x for x in the_iterable if x > 3), default_value)

to call next with x for x in the_iterable if x > 3 to get the first item in the the_iterable iterable that is bigger than 3.

If it’s not found, we return default_value.

Conclusion

To get the first item from an iterable that matches a condition with Python, we can use the next function.

Categories
Python Answers

How to use numpy array in shared memory for multiprocessing with Python?

Sometimes, we want to use numpy array in shared memory for multiprocessing with Python.

In this article, we’ll look at how to use numpy array in shared memory for multiprocessing with Python.

How to use numpy array in shared memory for multiprocessing with Python?

To use numpy array in shared memory for multiprocessing with Python, we can just hold the array in a global variable.

For instance, we write

import multiprocessing
import numpy as np

data_array = None

def job_handler(num):
    return id(data_array), np.sum(data_array)


def launch_jobs(data, num_jobs=5, num_worker=4):
    global data_array
    data_array = data

    pool = multiprocessing.Pool(num_worker)
    return pool.map(job_handler, range(num_jobs))


mem_ids, sumvals = zip(*launch_jobs(np.random.rand(10)))

print(np.all(np.asarray(mem_ids) == id(data_array)))

to create the data_array global variable to hold the numpy array.

Then we assign it to a value in launch_jobs.

And then we call launch_jobs with np.random.rand(10) to set that as the value of data_array.

We start the threads with

pool = multiprocessing.Pool(num_worker)
return pool.map(job_handler, range(num_jobs))

in launch_jobs.

We use job_handler with to run code for each thread.

This works if the script is run in a POSIX compliant OS.

Conclusion

To use numpy array in shared memory for multiprocessing with Python, we can just hold the array in a global variable.

Categories
Python Answers

How to format a floating number to fixed width in Python?

Sometimes, we want to format a floating number to fixed width in Python.

In this article, we’ll look at how to format a floating number to fixed width in Python.

How to format a floating number to fixed width in Python?

To format a floating number to fixed width in Python, we can use the string format method.

For instance, we write

numbers = [23.23, 0.1233, 1.0, 4.223, 9887.2]                                                                                                                                                   
                                                                                                                                                                                                
for x in numbers:                                                                                                                                                                               
    print("{:10.4f}".format(x)) 

to call format with the numbers x in the numbers list.

We format each number in the list to 4 decimal places with "{:10.4f}".

Conclusion

To format a floating number to fixed width in Python, we can use the string format method.

Categories
Python Answers

How to read specific lines from a file by line number with Python?

Sometimes, we want to read specific lines from a file by line number with Python.

In this article, we’ll look at how to read specific lines from a file by line number with Python.

How to read specific lines from a file by line number with Python?

To read specific lines from a file by line number with Python, we can use the enumerate function.

For instance, we write

with open("file.txt") as fp:
    for i, line in enumerate(fp):
        if i == 25:
            # ...
        elif i == 29:
            # ...
        elif i > 29:
            break

to open the file.txt file with open.

And then we loop through the lines with the index and line with enumerate.

line has the content of each line and i is the line‘s index.

Then we can use if statements to check the index of the line and do what we want.

Conclusion

To read specific lines from a file by line number with Python, we can use the enumerate function.