Categories
Python Answers

How to add keyboard input with timeout with Python?

Sometimes, we want to add keyboard input with timeout with Python.

In this article, we’ll look at how to add keyboard input with timeout with Python.

How to add keyboard input with timeout with Python?

To add keyboard input with timeout with Python, we can use the select.select method with sys.stdin.

For instance, we write:

import sys, select

print("You have 5 seconds to answer")

i, o, e = select.select([sys.stdin], [], [], 5)

if (i):
    print("You said", sys.stdin.readline().strip())
else:
    print("You said nothing")

We call select.select with [sys.stdin] and 5 to given users 5 seconds to enter some text.

If i is True, then the user entered something within the time limit and we can read the inputted value with sys.stdin.readline().strip().

Conclusion

To add keyboard input with timeout with Python, we can use the select.select method with sys.stdin.

Categories
Python Answers

How to find all occurrences of a substring with Python?

Sometimes, we want to find all occurrences of a substring with Python.

In this article, we’ll look at how to find all occurrences of a substring with Python.

How to find all occurrences of a substring with Python?

To find all occurrences of a substring with Python, we can use the re.finditer method.

For instance, we write:

import re

indexes = [m.start() for m in re.finditer('test', 'test test test test')]
print(indexes)

We call re.finditer method with the substring to search for and the string we’re searching for the substring in respectively.

Then we call m.start on each entry found to get the index of the start of each match.

Therefore, indexes is [0, 5, 10, 15].

Conclusion

To find all occurrences of a substring with Python, we can use the re.finditer method.

Categories
Python Answers

How to reverse or invert a dictionary mapping with Python?

Sometimes, we want to reverse or invert a dictionary mapping with Python.

In this article, we’ll look at how to reverse or invert a dictionary mapping with Python.

How to reverse or invert a dictionary mapping with Python?

To reverse or invert a dictionary mapping with Python, we can use the items method of the dictionary to get the items and then use dictionary comprehension to flip the keys and values.

For instance, we write:

my_map = {'a': 1, 'b': 2}
inv_map = {v: k for k, v in my_map.items()}
print(inv_map)

We call my_map.items to return the key and value of each entry as k and v respectively.

Then we flip them by putting v to the left of the colon and k after.

And then we assign the returned dictionary to inv_map.

Therefore, inv_map is {1: 'a', 2: 'b'}.

Conclusion

To reverse or invert a dictionary mapping with Python, we can use the items method of the dictionary to get the items and then use dictionary comprehension to flip the keys and values.

Categories
Python Answers

How to POST JSON data with Python Requests?

Sometimes, we want to POST JSON data with Python Requests.

In this article, we’ll look at how to POST JSON data with Python Requests.

How to POST JSON data with Python Requests?

To POST JSON data with Python Requests, we call the requests.post method.

For instance, we write:

import requests

r = requests.post('http://httpbin.org/post', json={"key": "value"})
print(r.status_code)
print(r.json())

We call requests.post with the URL to make request to and the json request payload.

The response object is the returned and assigned to r.

We get the status code from r.status_code and the response body from r.json.

r.status_code should be 200.

And r.json should return:

{'args': {}, 'data': '{"key": "value"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '16', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.26.0', 'X-Amzn-Trace-Id': 'Root=1-616c8c56-6e89c2ab7addbeee5064302c'}, 'json': {'key': 'value'}, 'origin': '35.197.57.70', 'url': 'http://httpbin.org/post'}

Conclusion

To POST JSON data with Python Requests, we call the requests.post method.

Categories
Python Answers

How to use getters and setters with Python?

Sometimes, we want to use getters and setters with Python.

In this article, we’ll look at how to use getters and setters with Python.

How to use getters and setters with Python?

To use getters and setters with Python, we can use the property, setter and deleter decorators.

deleter is called when the del keyword is used to remove an attribute from an object.

For instance, we write:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        print("getter of x called")
        return self._x

    @x.setter
    def x(self, value):
        print("setter of x called")
        self._x = value

    @x.deleter
    def x(self):
        print("deleter of x called")
        del self._x


c = C()
c.x = 'foo'
foo = c.x
del c.x

We have the C class with the x getter which has the property decorator applied to it and returns self._x.

The x setter has the x.setter called on it and sets self._x to value.

value is the value that we assign to x.

The x deleter has the x.deleter used on it and uses the del operator to remove the self._x property.

Then we instantiate C and assigns it to c.

And then we set c.x to 'foo', assigns c.x fo foo, and use del to remove the c.x attribute.

Therefore, we see:

setter of x called
getter of x called
deleter of x called

printed.

Conclusion

To use getters and setters with Python, we can use the property, setter and deleter decorators.

deleter is called when the del keyword is used to remove an attribute from an object.