#🔒 Can access class attribute inside print but not in list comprehension

6 messages · Page 1 of 1 (latest)

spark sand
#

I have created a class to calculate FIFO based profits from a set of Mutual Fund (MF) transactions. Before I show the code, a small explanation:
When I invest ₹3000 in an MF, if the NAV is ₹100, then I get 3000/100 = 30 units. Let's say I make 2 investments of ₹3000, one at an NAV of ₹100 and another at an NAV of ₹150. I'll have a total of 50 units.
Now if I sell 40 units, to calculate the profit, I'll have to take the cost of first 30 units as ₹100/unit and cost of remaining 10 units as ₹150/unit. Consequently, my balance will be 10 units of ₹150 each.

Now this is the class I created:
https://hastebin.skyra.pw/ifohenuxer.prolog

Now I have a dataframe with all my MF transactions (in multiple MFs). So to calculate the profit for all, I did:

all_funds_fifo = []
for code in all_trx['amfi_code'].unique().tolist():
    cur_df = all_trx[all_trx['amfi_code']==code].copy(deep=True)
    fund_fifo = Fifo(cur_df)
    fund_fifo.calculate_profits()
    all_funds_fifo.append(fund_fifo)

Now here comes the weird part

if I write

for i, j in enumerate(all_funds_fifo):
    print(j.inv_df_fifo)

It prints out all the dataframes.

but if I write [j.inv_df_fifo for i, j in enumerate(all_funds_fifo)] it gives me an error saying

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[66], line 1
----> 1 [j.inv_df_fifo for i, j in enumerate(all_funds_fifo)]

Cell In[66], line 1, in <listcomp>(.0)
----> 1 [j.inv_df_fifo for i, j in enumerate(all_funds_fifo)]

AttributeError: 'Fifo' object has no attribute 'inv_df_fifo'

I have checked for typos multiple times and can't find anything. This is the weirdest issue I've every encountered. Can anyone help me with this

fringe fieldBOT
#

@spark sand

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.

spark sand
#

OK, it worked after I put self.inv_df_fifo = None inside __init__()

#

!close

fringe fieldBOT
#
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.