0

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

3
  • Code completion is a feature of your editor or coding environment. Could you specify which one you are using? Commented Oct 19, 2017 at 11:14
  • My target is Jupyter, but I also use PyCharm. I guess both start by looking the _dir_(). Commented Oct 19, 2017 at 11:16
  • Sorry, my question was not clear. I would be happy for argument code completion. But I would also be happy with class attributes code completion. This explain my comment on _dir_(). I don't know the analogue for picking arguments possible values. Commented Oct 19, 2017 at 11:21

2 Answers 2

1

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:
    ....
Sign up to request clarification or add additional context in comments.

3 Comments

enums don't need commas. In fact, they'll turn the values into tuples, which is undesired
Thanks a lot for such a simple solution. I tested it on a simple example in Jupyter, and this will be useful. I just don't see the need for enum.Enum as it also works without in Jupyter. Only one drawback: I need to create valid attributes automatically for the 2400 formulas in my database and this is not so obvious.
I've fixed the commas.
0

Are you trying to get a random string from a list of strings?

 from random import choice

 formulas = ['f1', 'f2']
 formula = choice(formulas)
 example(formula = formula)

If not, then simply indexing (formulas[int]) should do the trick.

2 Comments

I don't need a random choice. I need the stuff to get completion useful in my case. I don't understand your suggestion.
Yeah I figured, seems like you found an answer :)

Your Answer

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