Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

oop

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!

like image 761
Robowraith Avatar asked May 29 '18 12:05

Robowraith


People also ask

Can you dynamically name variables in Python?

A dynamic variable name, which can likewise be known as a variable variable, is fundamentally a variable with a name that is the estimation of another variable. Although Python itself is a highly dynamic language, and almost everything in a Python code is an object, it is possible to create dynamic variables in Python.

Can you dynamically name a variable?

In programming, dynamic variable names don't have a specific name hard-coded in the script. They are named dynamically with string values from other sources. Dynamic variables are rarely used in JavaScript. But in some cases they are useful.

Why are variable name declaration not used in Python?

Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A Python variable is a name given to a memory location.

What Cannot be used as variable names in Python?

Rules for Python variables: A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )


2 Answers

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.

like image 110
deceze Avatar answered Sep 28 '22 01:09

deceze


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.

like image 34
John Zwinck Avatar answered Sep 28 '22 02:09

John Zwinck