0

I'm wanting to go through a list of objects so that my PyCharm IDE knows what type each list item is:

For example, say I know that each item in a list is an class instance of type 'myClass' - how do I use this to cast my objects so that my ide can help with code completion?

for i in range(len(myList)):
    myClass(myList[i]).myClassProperty .....

I know how to do it in Delphi (something like the above) but not in python.

Thanks

4
  • 1
    ...what IDE? Some can do it via introspection of the code you're writing, or use docstrings and/or type annotations. Commented Mar 21, 2017 at 8:05
  • 1
    There's no Python way to do this, the concept of 'casting' doesn't exist. Maybe the IDE has some way to do it. Commented Mar 21, 2017 at 8:05
  • This will be specific to the IDE (so say which one you're using). I don't think there's a general Python solution. Except possibly type hints in Python 3.5 onwards? Commented Mar 21, 2017 at 8:07
  • See jetbrains.com/help/pycharm/2016.3/type-hinting-in-pycharm.html for PyCharm solution. Commented Mar 21, 2017 at 8:20

2 Answers 2

1

In PyCharm, you can use Type Hinting:

class Bar:
    def __init__(self,bar):
        self.bar = bar

    def do_bar(self):
        return self.bar

def foo(x):
    for el in x: # type: Bar
        el.do_bar()

bars = [Bar('hello'), Bar('World')]

foo(bars)

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Another possibility is to put :type x: list[Bar] in the docstring of foo.
0

You can't get code completion similar to Java or C++ in dynamically typed, interpreted language.There is no casting, because you don't need it in python. A function works for a given object if it has needed methods implemented, type is irrelevant to the language at this point. It is good practice though to leave some runtime checks using isinstance, if you expect your argument to be e.g. a dict. Otherwise you will end up with many difficult bugs.

As for code completion in python there are two solutions I find useful. The best IDEs around here are probably PyCharm https://www.jetbrains.com/pycharm/ and PyDev the Eclipse Plugin http://www.pydev.org/manual_101_install.html. They provide some code completion.

The other is interactive console Jupyter http://jupyter.org/. As you write your code, you could execute it in chunks (cells) and easily see object methods or fields, using not the type information, but the object itself existing in memory. This is very good for data analysis or playing with framework you don't know well.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.