Search code examples
pythoncode-completion

(coding to get) Python code completion to choose from a list of allowable strings


Assume a simple function:

def example(formula="")
    ...

Where the argument "formula" should be one of 2400 possible chemical formulas. Would there be a way to get code completion for choosing one string from a list of 2400 strings?

First idea was to chose from a list of class attributes. However, I can not use the dir() method. These formula strings are often invalid for use as attribute names.

I don't see another method that would list a choice without using attributes of something.

Thanks


Solution

  • Use enums, which PyCharm for instance code completes just nicely, especially if you use type hinting.

    import enum
    
    class ChemFormula(enum.Enum):
        Chlorine = "cl2"
        Hydrogen = "h2"
        Water = "h2o"
    
    
    def example(formula: ChemFormula) -> None:
        ....