Home > Software design >  Can't access global variables outside a function in Python
Can't access global variables outside a function in Python

Time:04-01

I know many people asked that, but I haven't found the solution to my problem, looking at others' issues.

I need to call all the variables created and edited inside the function after running. global way suggested by StackOver didn't work. The same piece of code outside the function works perfectly.

Why is that?

def createbestseller():
  pivot = pd.pivot_table(dataframe, 
                         index = ['customer_IDprovince'], 
                         columns = ['category'], 
                         aggfunc = 'size', 
                         fill_value = 0)
  pivot_flat = pd.DataFrame(pivot.to_records())
  pivot_flat.set_index('customer_IDprovince', inplace = True)
  bestseller_perprov = pd.concat([pivot_flat.index.to_series(),
                                  pivot_flat.idxmax(axis=1)],
                                 axis = 1).reset_index(drop = True)
  bestseller_perprov.rename(columns = {0:'best_seller'}, inplace = True)
  bestseller_perprov = pd.concat([geoprov, bestseller_perprov], axis = 1)
  bestseller_perprov.iloc[47,0] = 'Castellón'
  bestseller_perprov.rename(columns = {0:'province'}, inplace = True)

  fig10 = px.choropleth_mapbox(
    bestseller_perprov,
    geojson=gdf,
    featureidkey="properties.cod_prov",
    locations="customer_IDprovince",
    color="best_seller",
    color_continuous_scale="matter",
    zoom=3,
    hover_name= 'province',
    center={"lat": 40.4999, "lon": -3.673},
    labels={"best_seller": "Best Selling Category"},
    )

bestseller_perprov
>>> name 'bestseller_perprov' is not defined

CodePudding user response:


If you want to use *global* than you need to create a variable before calling the function. Like this:
def f():
    global bestseller_perprov
    bestseller_perprov = "Test"


bestseller_perprov = None
f()
print(bestseller_perprov)

Also you can create static class like this:

class Test:
    @classmethod
    def f(cls):
        cls.bestseller_perprov = "Test"


Test.f()
print(Test.bestseller_perprov)

Hope this helps.

CodePudding user response:

That's the cleanest way I found it working:

def myfunction():
  global x 
  x = 'apple'
  x = x   's'
  global y
  y = 'pear'
  y = y   's'

x = None
y = None
myfunction()

print(x)
  apples
print(y)
  pears
  • Related