TransWikia.com

How is "from" in python can copies

Stack Overflow Asked by joox on November 18, 2021

How is the (from) in python can take a copies variables from one file to another, and what happened if the variables is the same name ? Description my Question

2 Answers

That description is not quite right. Module variables are names bound to objects. When you

import somemodule

two things happen: 1) the module is imported into python, if it isn't imported already, and 2) a variable called somemodule is created and bound to that module.

When you

from somemodule import foo

Its similar. The module is imported but instead of binding somemodule to your module's namespace, a variable called foo is created and the object in somemodule.foo is bound to it. You added a reference to the object in somemodule.foo, but you didn't copy it.

When you reference foo, you get the same object that was in somemodule.foo. But if either of these variables are rebound to new objects, the other variable still holds a reference to the old object. Now the two variables reference different things.

Notice that this redefinition only happens if the variable is rebound (reassigned) to a new object. A list append doesn't rebind the variable. But something like foo = 1 does. And sometimes you just kinda have to know what happens. += on a list doesn't rebind a new object, but the same operation on an integer does. Beware augmented operations like that if you from x import y.

Its generally safe to from x import y functions, classes and other modules because its unlikely that those will be reassigned in the original module. Otherwise, buyer be ware.

Answered by tdelaney on November 18, 2021

In Python, when you do from module import variable, the variable "variable" in your program is defined to be however the variable is defined in the module so you can use it. However, this might cause existing variables and functions to be overwritten.

Answered by aidan0626 on November 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP