Exec not working as expected. Any clues?

If I try posting under Q&A I get 500 internal server error.

Sounds like one for stackoverflow, but they won’t have the context…

https://app.dataquest.io/m/347/working-with-missing-and-duplicate-data/1/introduction

My Code:

    for year in [2015, 2016, 2017] :
        exec( 'shape_' + str(year) + ' = happiness' + str(year) + '.shape' )

What I expected to happen:
shape_2015 would be set to happiness2015.shape

What actually happened:
You get a variable named str
strtype (<class ‘type’>)

1 Like

Hi @ananth.ch

In this line, you converted everything to type string. Thus when you try to use .shape, python does not interpret it as a method to be executed, but rather a string. Thus everything is of type str.

@Sahil could you help to look into this? Thanks!

Hope this clarifies!

Hi Ryan,
Could you give us the correct code - assuming the intent is clear?

Thanks

shape_2015 = happiness2015.shape
shape_2016 = happiness2016.shape
shape_2017 = happiness2017.shape

Very funny… You know I mean using exec. What if one had to set shape_2001 all the way to shape_2020. Anything that can be automated should be automated…

Hi @ananth.ch:

.shape is not a supported method of exec() as detailed in this article thus you will have to the use the old fashion way.

Before using any methods inside the exec() function one must keep in mind about what all functions do exec() support. To view this we may use dir() function.

List of supported functions:

['__builtins__', '__cached__', '__doc__', '__file__',
 '__loader__', '__name__', '__package__', '__spec__', 
'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 
'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 
'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial',
 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 
'hypot', 'inf', 'isclose', 'isfinite', 'isinf',
'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 
'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin',
 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

happiness2015 and so on are variables thus treating them as strings will not retrieve the value stored as intended. Thus, you cannot use a loop to iterate over and attempt to automate and extract and store each shape attribute in another variable

I’ve recategorised your topic for now.