#๐Ÿ”’ How do i delegate a magic method from a constructor parameter to the class

15 messages ยท Page 1 of 1 (latest)

frosty bay
#

basically i am trying to golf this code

class A:
    def __init__(self, data: List):
        self.data = data
    def __iter__(self):
        return iter(self.data)

into something like this

class A:
    def __init__(self, data: List):
        self.data = data
        self.__iter__ = data.__iter__

but python doesn't recognise the magic method and says the object is not iterable. is there any way to do this?

placid steepleBOT
#

@frosty bay

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

unborn lark
#

not sure if it works precisely for your use case though...

novel elbow
#

I thought the issue might be that __iter__ is on the class not the object

#

!e

class A:
    def __init__(self, data: list):
        self.data = data
        type(self).__iter__ = data.__iter__

a = A([1, 2])
print(iter(a))

this seems to work?

placid steepleBOT
unborn lark
novel elbow
#

!e

class A:
    def __init__(self, data: list):
        self.data = data
        type(self).__iter__ = lambda self: iter(self.data)

a = A([1, 2])
print(iter(a))
placid steepleBOT
novel elbow
frosty bay
#

yea, not exactly what i was looking for but if that's the best you can do with python it's good, thanks

#

!close

placid steepleBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.