0

I'm trying to def a functin but i can't call it:

  def test():
      fig = make_subplots(rows=1, cols=2, specs=[
      [{'type': 'scatter'}, {'type': 'table'}]]
                      , shared_xaxes=True,
                      horizontal_spacing=0.05, 
                      vertical_spacing=0.05,  
                      column_widths=[0.7, 0.3])
      pass

  test()

  fig.add_trace(go.Candlestick(x=df.index,
            open=df['Open'],
            high=df['High'],
            low=df['Low'],
            close=df['Close'],
            increasing_line_color = UP_CANDLE,
            decreasing_line_color = DW_CANDLE),row=1,col=1)

When I call it I retrieve the following error: NameError: name 'fig' is not defined If I remove the function, the code works perfectly.

1
  • Indentation of your code is incorrect. Commented Mar 26, 2022 at 1:17

1 Answer 1

1

Once your local variable fig is inside the function, nothing outside of the function test will have access to fig unless you return fig from the function – you can read about scope in python.

I would rewrite your function like this (and pass doesn't have any purpose in your function so I removed it):

def test():
    fig = make_subplots(
        rows=1, cols=2, 
        specs=[[{'type': 'scatter'}, {'type': 'table'}]], 
        shared_xaxes=True, 
        horizontal_spacing=0.05, 
        vertical_spacing=0.05,  
        column_widths=[0.7, 0.3]
    )
    return fig

Then you can set a variable equal to what your function returns:

fig = test()

And then you'll be able to access the .add_trace method of `fig

fig.add_trace(go.Candlestick(x=df.index,
        open=df['Open'],
        high=df['High'],
        low=df['Low'],
        close=df['Close'],
        increasing_line_color = UP_CANDLE,
        decreasing_line_color = DW_CANDLE),row=1,col=1)
Sign up to request clarification or add additional context in comments.

3 Comments

More compactly, test().add_trace(...)
Sure - that's the way I would probably write it myself - but I feel like this more expanded out version might be easier for the person who asked the question to understand
Agreed. That's why it belongs in a comment and not the answer

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.