Python Forum
How to avoid exec(), globals(), locals(), eval()
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to avoid exec(), globals(), locals(), eval()
#11
(Apr-21-2021, 03:23 PM)paul18fr Wrote: I'm doing my best to have a good practice Smile
Then can play a song at right moment The PEP 8 Song🎵
In this post an your other post your code look messy when look at it for having good practice in Python.
So i rewrite it would look like this and code works.
import numpy as np

# Make random numpy array
mat = np.random.random((10,1))
mat2 = np.random.random((10,1))
mat3 = np.random.random((10,1))

my_dict = {"new_dict": {'mat1': mat, 'mat2': mat2}}
# dict to add
basic_dict = {'mat': mat}
new_key = 'new_key'
if not new_key in my_dict:
    print(f"{new_key} is not in my_dictList -> added")
    my_dict.update({new_key: {}, })
    my_dict.update(basic_dict)
else:
    print(f"{new_key} is in my_dict")

# Test my_dict
get_mat2 = my_dict['new_dict']['mat2']
print(get_mat2)
print('-' * 25)
print(my_dict)
Output:
new_key is not in my_dictList -> added [[0.85424998] [0.75364254] [0.76795389] [0.43357187] [0.37357796] [0.71517631] [0.69691738] [0.43317861] [0.95802329] [0.26230435]] ------------------------- {'new_dict': {'mat1': array([[0.91394191], [0.8892786 ], [0.48059377], [0.92667453], [0.1901234 ], [0.3502345 ], [0.08907687], [0.38634954], [0.98999417], [0.02432816]]), 'mat2': array([[0.85424998], [0.75364254], [0.76795389], [0.43357187], [0.37357796], [0.71517631], [0.69691738], [0.43317861], [0.95802329], [0.26230435]])}, 'new_key': {}, 'mat': array([[0.91394191], [0.8892786 ], [0.48059377], [0.92667453], [0.1901234 ], [0.3502345 ], [0.08907687], [0.38634954], [0.98999417], [0.02432816]])}
buran likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  why globals() exits python when quit() is aliased as q abc12346 4 692 May-23-2023, 08:56 AM
Last Post: Gribouillis
  exec in a function paul18fr 6 3,387 Apr-19-2021, 11:10 AM
Last Post: paul18fr
  exec + subprocess = UnboundLocalError paul18fr 6 3,512 Feb-04-2021, 06:27 AM
Last Post: Gribouillis
  int, floats, eval menator01 2 2,446 Jun-26-2020, 09:03 PM
Last Post: menator01
  exec() in class, NameError niski1996 6 3,982 Apr-20-2020, 07:14 PM
Last Post: niski1996
  Is this use of exec pythonic? psolar 1 1,840 Feb-07-2020, 12:23 PM
Last Post: buran
  problem using exec to save local variables dkarl 0 1,801 Dec-01-2019, 08:52 AM
Last Post: dkarl
  common code, def a function vs exec() a string Skaperen 7 3,362 May-27-2019, 10:13 AM
Last Post: heiner55
  eval lambda function with restricted context Olivier 7 5,156 Mar-04-2019, 10:45 PM
Last Post: Olivier
  eval not working in code jamminjamie 0 2,214 Dec-27-2018, 05:24 PM
Last Post: jamminjamie

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020