Review my code: Post code you would like the community to review

SimoneSimone Administrator admin
edited August 2017 in Review my code

Why should you post code to be reviewed?

Because you will be tapping into the knowledge of a whole community of developers who are also using the API, and may have already faced the issues you are dealing with now.
And you might end up making some friends in the process!

How to help others help you?
• Post annotated code.
• Indicate why you wish it reviewed (e.g.: are you trying to fix a bug? Would you like general feedback? Are you getting different results from expected?)
• Provide as much detail as you can!

Why should you review somebody else’s code?

You will be flexing your coding muscles, get to see what fellow developers are doing and – who knows? – might come up with solutions for your own code in looking at code by others!

How to effectively review someone’s code:
IBM has compiled best-practices for code reviewing. You can see the list below, and on Proven practices for more effective, efficient peer code review you can find each point below expanded on (please note that we are just using this as a source of information, not endorsing any of their products).

  1. Review fewer than 200–400 lines of code at a time.
  2. Aim for an inspection rate of fewer than 300–500 LOC per hour.
  3. Take enough time for a proper, slow review, but not more than 60–90 minutes.
  4. Be sure that authors annotate source code before the review begins.
  5. Establish quantifiable goals for code review and capture metrics so you can improve your processes.
  6. Use checklists, because they substantially improve results for both authors and reviewers (see a checklist below).
  7. Verify that the defects are actually fixed.
  8. Foster a good code review culture in which finding defects is viewed positively.
  9. Beware of the Big Brother effect.
  10. Review at least part of the code, even if you can't do all of it, to benefit from The Ego Effect.

And here is a checklist by Karl E. Wiegers from Liberty University, US, to help you on your code reviewing:
Generic checklist for code reviews

Disclaimer: Oxford Dictionaries accepts no responsibility for any code posted here. Please exert care and discretion when downloading any content for reviewing.

Tagged:

Comments

  • I've written a program in Python to look up words using the dictionary API and show sentences using the word. If the user misspells the word, the program attempts to suggest a replacement. I consider myself an advanced novice at Python so I'm looking for general comments and suggestions.
    ---Python 3.6.1 code follows---

    for more information on how to install requests

    http://docs.python-requests.org/en/master/user/install/#install

    import requests

    read json formated data

    import json

    look for words in a list that might match the word you are looking for

    assign a closeness value to the match

    from difflib import get_close_matches

    TODO: replace with your own Oxford Dictionary app_id and app_key

    https://developer.oxforddictionaries.com/documentation

    app_id = ''
    app_key = ''

    language = 'en'

    def define_word(word_id):
    doc='''
    Request an entry from the Oxford Dictionary API for the word (a string) provided
    '''

    word_id = word_id.lower()
    url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' + language + '/' + word_id + '/definitions'
    
    r = requests.get(url, headers = {'app_id': app_id, 'app_key': app_key})
    #print(len(r.text))
    #print("code {}\n".format(r.status_code))
    #print("text \n" + r.text)
    #print("json \n" + json.dumps(r.json()))
    

    status_code 200 means the request returned some text in JSON format

    if r.status_code != 200:
        # if the request failed, if may be a spelling error. Search for a possible replacement
        word_id = search_word(word_id)
        # if the search_word routine return a type(bool) then it failed to find a replacement
        if type(word_id) == bool:
            return False
        else:
            # if the search_word routine retuned a word, try to define it (recursive call)
            return define_word(word_id)
    

    unpack the JSON formated results

    d = {}
    d = json.loads(r.text)
    #print(d)
    print(f"\n{word_id}:")
    for r in range(len(d['results'])):
        for l in range(len(d['results'][r]['lexicalEntries'])):
            for e in range(len(d['results'][r]['lexicalEntries'][l]['entries'])):
                for s in range(len(d['results'][r]['lexicalEntries'][l]['entries'][e]['senses'])):
                    print(f" {d['results'][r]['lexicalEntries'][l]['lexicalCategory']}:\n",
                        f"   {d['results'][r]['lexicalEntries'][l]['entries'][e]['senses'][s]['definitions'][0]}")
                    try:
                        if len(d['results'][r]['lexicalEntries'][l]['entries'][e]['senses'][s]['subsenses']) > 0:
                            for u in range(len(d['results'][r]['lexicalEntries'][l]['entries'][e]['senses'][s]['subsenses'])):
                                print(f"    {d['results'][r]['lexicalEntries'][l]['entries'][e]['senses'][s]['subsenses'][u]['definitions'][0]}")
                    except:
                        pass
    print()
    return True
    

    def word_sentence(word_id):
    doc='''
    Request sentences from the Oxford Dictionary API for the word (a string) provided
    '''

    word_id = word_id.lower()
    url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' + language + '/' + word_id + '/sentences'
    
    r = requests.get(url, headers = {'app_id': app_id, 'app_key': app_key})
    #print(len(r.text))
    #print("code {}\n".format(r.status_code))
    #print("text \n" + r.text)
    #print("json \n" + json.dumps(r.json()))
    

    Finding a sentence should never have a problem with the word existing as it

    is only called if the define_word routine worked. [belts and suspenders]

    if r.status_code != 200:
        print(f"{word_id} not found in Oxford Dictionary")
        word_id = search_word(word_id)
        if type(word_id) == bool:
            return
        else:
            return word_sentence(word_id)
    

    unpack the JSON formated results

    d = {}
    d = json.loads(r.text)
    #print(d)
    print(f"\n{word_id}:")
    for r in range(len(d['results'])):
        for l in range(len(d['results'][r]['lexicalEntries'])):
            for e in range(len(d['results'][r]['lexicalEntries'][l]['sentences'])):
                print(f" {d['results'][r]['lexicalEntries'][l]['sentences'][e]['text']}\n")
    print()
    

    def search_word(word_id):
    doc='''
    Request a list of word from the Oxford Dictionary API that might be the
    correct spelling for the word (a string) provided. This uses the fuzzy logic search.
    '''
    global word

    The Oxford Dictionary fuzzy logic search returns a list of possible matches

    for the word that is supplied (the misspelled word). The list does not appear

    to be in an order.

    The module get_close_matches gives each word in the list returned from the dictionary

    a weighing as to its likelyhood of being the correct spelling for the word provided.

    This routine returns only the best match.

    word_id = word_id.lower()
    url = 'https://od-api.oxforddictionaries.com:443/api/v1/search/' + language + '?q=' + word_id + '&prefix=false&limit=100'
    
    r = requests.get(url, headers = {'app_id': app_id, 'app_key': app_key})
    #print(len(r.text))
    #print("code {}\n".format(r.status_code))
    #print("text \n" + r.text)
    #print("json \n" + json.dumps(r.json()))
    
    if r.status_code != 200:
        #print(f"{word_id} not found in Oxford Dictionary")
        return False
    
    d = {}
    d = json.loads(r.text)
    #print(d)
    word_list=[]
    word_guess=''
    print(f"\n{word_id}:")
    for r in range(len(d['results'])):
        print(f" {d['results'][r]['word']}")
        word_list.append(d['results'][r]['word'])
        word_guess=get_close_matches(word_id, word_list)
    if len(word_guess) > 0:
        yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " % word_guess[0])
        if yn.upper() == "Y":
            word=word_guess[0]
            return word_guess[0]
        elif yn.upper() == "N":
            return False
        else:
            return False
    else:
        print(f"Can't find a possible match for {word_id}")
        return False
    

    while True:
    word = input("\nEnter word (Q to stop (Quit and Stop are in the dictionary): ")
    if word.upper() == 'Q': break
    OK=define_word(word)
    if OK:
    sentence=input(f'Use {word} in a sentence? (Y/N) ')
    if sentence.lower()[0]=='y':
    word_sentence(word)

  • SimoneSimone Administrator admin

    Hi @JackHomeyer,
    thanks for this, sounds really interesting.
    Let me find others working on similar projects with Python so you can get some meaningful comments - bear with me! :)

  • Hi @JackHomeyer,
    Thank you for share your code with us, it sounds very interesting. Congratulations!.

    I would suggest to store the app_key and app_id as environment variables (security reason).

    In order to make your code more readable I would use format to concatenate your longest strings instead of + operator.

    Regarding to r.status_code != 200, a request different to 200 doesn’t mean that the word was not found, it could be a redirect (300). I would use a different check like r.status_code >= 400.

    I would remove the unused prints and I would use a logger instead of prints with different log levels such as info, warn and error.

    I would avoid define global variables in a function ambit. I would suggest to define it after the imports. But, You should consider that a global variable is a memory storage shared for several parts of your program, so I would avoid to update the value of global variables. As far as I can read in your code, I would highly recommend you to use a main function to execute there the loop and save the variables for general purpose.

    You could follow PEP8 conventions to make your code more readable.

    I hope that you find my comments useful.

    Best regards!

Sign In or Register to comment.