Why shouldn't one dynamically generate variable names in python?

亡梦爱人 提交于 2021-02-08 15:16:31

问题


Right now I am learning Python and struggling with a few concepts of OOP, one of that being how difficult it is (to me) to dynamically initialize class instances and assign them to a dynamically generated variable name and why I am reading that I shouldn't do that in the first place.

In most threads with a similar direction, the answer seems to be that it is un-Pythonic to do that.

For example generating variable names on fly in python

Could someone please elaborate?

Take the typical OOP learning case:

LOE = ["graham", "eric", "terry_G", "terry_J", "john", "carol"]
class Employee():
    def __init__(self, name, job="comedian"):
        self.name = name
        self.job = job

Why is it better to do this:

employees = []
for name in LOE:
    emp = Employee(name)
    employees.append(emp)

and then

for emp in employees:
    if emp.name == "eric":
        print(emp.job)

instead of this

for name in LOE:
    globals()[name] = Employee(name)

and

print(eric.job)

Thanks!


回答1:


If you dynamically generate variable names, you don't know what names exist, and you can't use them in code.

globals()[some_unknown_name] = Foo()

Well, now what? You can't safely do this:

eric.bar()

Because you don't know whether eric exists. You'll end up having to test for eric's existence using dictionaries/lists anyway:

if 'eric' in globals(): ...

So just store your objects in a dictionary or list to begin with:

people = {}
people['eric'] = Foo()

This way you can also safely iterate one data structure to access all your grouped objects without needing to sort them from other global variables.




回答2:


globals() gives you a dict which you can put names into. But you can equally make your own dict and put the names there.

So it comes down to the idea of "namespaces," that is the concept of isolating similar things into separate data structures.

You should do this:

employees = {}
employees['alice'] = ...
employees['bob'] = ...
employees['chuck'] = ...

Now if you have another part of your program where you describe parts of a drill, you can do this:

drill['chuck'] = ...

And you won't have a name collision with Chuck the person. If everything were global, you would have a problem. Chuck could even lose his job.



来源:https://stackoverflow.com/questions/50583955/why-shouldnt-one-dynamically-generate-variable-names-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!