4
\$\begingroup\$

The following code will be used to generate a random json object to be used as a RabbitMQ message body. The code works but I'm sure it can be improved in ways that I am not seeing, as I am a novice.

First and foremost, I want this to be idiomatic. After that, readability and reusability are my priorities. I'm not really concerned with speed or security for this test, but if you have comments on those subjects, by all means feel free to comment.

My code works fine but I'm sure it can be improved. What would you change?

import random


# Create random 9-digit ID
def create_clip_id():
    clip_id = random.randint(1111111, 9999999)
    return clip_id


# Create random list of detection types.
# Each item must be a dictionary in the form:
# {'DetectionType': 'object'}
# List can be 1, 2, or 3 items.
def create_detection_preferences():
    DetectionTypes = [{'DetectionType': 'person'}, {'DetectionType': 'pet'}, {'DetectionType': 'vehicle'}]
    prefs = random.sample(DetectionTypes, random.randrange(1,4))
    return prefs


# Generate the message body
def create_random_msg_body():
    msg_body = {
        'ClipID': create_clip_id(), 
        'ClipDateTime': '2022-08-23T00:41:21', # This doesn't matter. Just leave it as is.
        'ClipURL': '', # I will add this later
        'DetectionTypes': create_detection_preferences()
    }
    return msg_body


\$\endgroup\$
2
  • 1
    \$\begingroup\$ Please do not edit the question, especially the code, after an answer has been posted. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. What to do after the question has been answered. \$\endgroup\$
    – pacmaninbw
    Commented Aug 25, 2022 at 17:14
  • \$\begingroup\$ Besides what was suggested by Reinderien, take a look into Faker. It always helps me generate random data for testing purposes \$\endgroup\$ Commented Aug 25, 2022 at 17:22

1 Answer 1

4
\$\begingroup\$

I'm not very good at counting, but something tells me that 1111111 is not 9 digits.

DetectionTypes should be detection_types by PEP8.

Add PEP484 type hints.

randint is probably a better idea than randrange for this application, and you should use the length of the collection rather than hard-coding 4.

You need to move your function comments into docstrings.

Suggested

import random
from pprint import pprint
from typing import Any


def create_clip_id() -> int:
    """Create random 9-digit ID"""
    return random.randrange(int(1e9))


def create_detection_preferences() -> list[dict[str, str]]:
    """
    Create random list of detection types.
    Each item must be a dictionary in the form:
    {'DetectionType': 'object'}
    List can be 1, 2, or 3 items.
    """
    types = ('person', 'pet', 'vehicle')
    selected = random.sample(
        population=types,
        k=random.randint(1, len(types)),
    )
    return [
        {'DetectionType': type_name}
        for type_name in selected
    ]


def create_random_msg_body() -> dict[str, Any]:
    msg_body = {
        'ClipID': create_clip_id(),
        'ClipDateTime': '2022-08-23T00:41:21',
        'ClipURL': '',  # todo
        'DetectionTypes': create_detection_preferences(),
    }
    return msg_body


if __name__ == '__main__':
    pprint(create_random_msg_body())
\$\endgroup\$
2
  • \$\begingroup\$ Re: 9 digits. Whoops! That should be 7 digits. Thanks for this answer. I am not familiar with function annotations so this was a bit confusing at first but I think I get it now. Also, can you clarify what is happening in the return statement for create_detection_preferences()? How are you using type_name when it hasn't been previously defined? \$\endgroup\$
    – Johnny
    Commented Aug 25, 2022 at 17:32
  • 1
    \$\begingroup\$ That's a list comprehension. type_name is the iteration variable. \$\endgroup\$
    – Reinderien
    Commented Aug 25, 2022 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.