studioj
studioj

Reputation: 1400

How to trick autocomplete in Python for functions returning objects with dynamic attributes

class A(object):
    def __init__(self):
        self.b = 5
        self.c = 0

class B(A):
    def __init__(self):
        self.e = 10
        self.d = 11

def jojo(li):
    return li[1]

def lala():
    a = [A(), B()]
    b = jojo(a)
    return b

lala()

How can I make PyCharm's (or any IDE's) autocomplete functionality to suggest me b, c, d and e as attributes for lala(). can i define a custom list somewhere?

Upvotes: 0

Views: 1405

Answers (2)

studioj
studioj

Reputation: 1400

For PYTHON 2

class A(object):
    def __init__(self):
        self.b = 5
        self.c = 0

class B(A):
    def __init__(self):
        self.e = 10
        self.d = 11

def jojo(li):
    return li[1]

def lala():
    # type: () -> B
    a = [A(), B()]
    b = jojo(a)
    return b

lala()

Union doesn't work so only 1 class can be passed

Upvotes: 0

Piotr Dawidiuk
Piotr Dawidiuk

Reputation: 3092

Solution for Python 3

You can just use Union type if it's possible to list all possibilities.

I have added C class because it's not in A and B class hierarchy so the example will be more clear and holistic.

from typing import Union


class A(object):
    def __init__(self):
        self.b = 5
        self.c = 0

class B(A):
    def __init__(self):
        self.e = 10
        self.d = 11

class C:
    def __init__(self):
        self.f = 12

def jojo(li):
    return li[1]

def lala() -> Union[A, B, C]:
    a = [A(), B(), C()]
    b = jojo(a)
    return b

lala()

enter image description here

Upvotes: 1

Related Questions