Home > Software engineering >  Python function return dict, how to write the documentation
Python function return dict, how to write the documentation

Time:08-30

I have a function which returning dict:

def getCard(deckListIn) -> dict:
    thisCard = deckListIn.pop() # pop one off the top of the deck and return
    return thisCard

thisCard is a dict like this:

thisCard = {
    'rank': rank,
    'suit': suit,
    'value': thisValue   1
}

How to write the function documentation so when I code like below, the editor (like VScode) will show up the hint [rank, suit, value] when I using dot operator?

currentCard = getCard(cardDesk)
print(currentCard.rank)

Now it is behave like this

CodePudding user response:

If I understand your question correctly - your code editor is displaying that information from the function's docstring: https://peps.python.org/pep-0257/#multi-line-docstrings

CodePudding user response:

This access only works, if you model your Dict as a python class (it has nothing to do with the IDE). For dicts, you must use currentCard.get('rank') or currentCard['rank'].

Example with class model:

class Card:
    value = 0

    def __init__(self, this_value):
        self.value = this_value   1
      

Access via Card.value or c.value if c = Card(1)

CodePudding user response:

What you need is to make your dict a class

class Card:
    def __init__(self,rank,suit,value):
        self.rank = rank
        self.suit = suit
        self.value = value

def getCard(deckListIn: list[Card]) -> Card:
    thisCard = deckListIn.pop()
    return thisCard

Be careful that now deckListIn should contains Cards and not dictionaries.

Note: I wrote list[Card]. This will work only for Python>=3.10. Otherwise you should use List[Card] after from typing import List, or simply remove that type hinting.

To create a Card from a dict

my_dict = {'rank':1, 'suit':2, 'value':3}

my_card = Card(**my_dict)
  • Related