from moduleName import * - python

In a main *.py, the statement
from myModule import a,b,c
imports the module 'myModule', and creates references in the current namespace to the given objects. Or in other words, you can now use a and b and c in your program. But you need to use, for example:
print(myModule.a)
Now, I need to use the statement:
from myModule import *
and I need to access, in my main *.py file, at the values of some variables declared in 'myModule', for example:
print(a)
I tried to use globals() to declare global variables but then they are not imported in the current namespace.
Does anyone know hoe to solve this??
Thanks

Question isn't clear but you can import modules with any moniker you want with:
import thing as t
And to access:
t.thingFunction.(foo)

Related

Importing with dot notation

Can someone explain this to me?
When you import Tkinter.Messagebox what actually does this mean (Dot Notation)?
I know that you can import Tkinter but when you import Tkinter.Messagebox what actually is this? Is it a class inside a class?
I am new to Python and dot notation confuses me sometimes.
When you're putting that dot in your imports, you're referring to something inside the package/file you're importing from.
what you import can be a class, package or a file, each time you put a dot you ask something that is inside the instance before it.
parent/
__init__.py
file.py
one/
__init__.py
anotherfile.py
two/
__init__.py
three/
__init__.py
for example you have this, when you pass import parent.file you're actually importing another python module that may contain classes and variables, so to refer to a specific variable or class inside that file you do from parent.file import class for example.
this may go further, import a packaging inside another package or a class inside a file inside a package etc (like import parent.one.anotherfile)
For more info read Python documentation about this.
import a.b imports b into the namespace a, you can access it by a.b . Be aware that this only works if b is a module. (e.g. import urllib.request in Python 3)
from a import b however imports b into the current namespace, accessible by b. This works for classes, functions etc.
Be careful when using from - import:
from math import sqrt
from cmath import sqrt
Both statements import the function sqrt into the current namespace, however, the second import statement overrides the first one.

Can I access a module object if it has only been imported via "from module import *"?

I have files that define global variables which I would like to use outside of the files, e.g. "func.py" containing:
def init():
global a
a = 5
If I import via "from x import *", then accessing the module's global variables like this does not work:
from func import *
init()
a
func.a
as neither a nor func are defined. "func" is listed in sys.modules.keys(), however.
I know "from x import *" is not exactly best practice, but how can I access the module's variables or the module object when using it?
I haven't found a way to do this other than importing the module "properly" as well.
import func
from func import *
init()
func.a
This question is very closely related. This one implies that since modules are imported fully with either command, there is no real performance difference either. This suggestion to use a separate file/container with global variables for larger projects is worth mentioning, too.
And obviously, don't use "from x import *" outside of live troubleshooting if you can't help it.

Why can't Python's import work like C's #include?

I've literally been trying to understand Python imports for about a year now, and I've all but given up programming in Python because it just seems too obfuscated. I come from a C background, and I assumed that import worked like #include, yet if I try to import something, I invariably get errors.
If I have two files like this:
foo.py:
a = 1
bar.py:
import foo
print foo.a
input()
WHY do I need to reference the module name? Why not just be able to write import foo, print a? What is the point of this confusion? Why not just run the code and have stuff defined for you as if you wrote it in one big file? Why can't it work like C's #include directive where it basically copies and pastes your code? I don't have import problems in C.
To do what you want, you can use (not recommended, read further for explanation):
from foo import *
This will import everything to your current namespace, and you will be able to call print a.
However, the issue with this approach is the following. Consider the case when you have two modules, moduleA and moduleB, each having a function named GetSomeValue().
When you do:
from moduleA import *
from moduleB import *
you have a namespace resolution issue*, because what function are you actually calling with GetSomeValue(), the moduleA.GetSomeValue() or the moduleB.GetSomeValue()?
In addition to this, you can use the Import As feature:
from moduleA import GetSomeValue as AGetSomeValue
from moduleB import GetSomeValue as BGetSomeValue
Or
import moduleA.GetSomeValue as AGetSomeValue
import moduleB.GetSomeValue as BGetSomeValue
This approach resolves the conflict manually.
I am sure you can appreciate from these examples the need for explicit referencing.
* Python has its namespace resolution mechanisms, this is just a simplification for the purpose of the explanation.
Imagine you have your a function in your module which chooses some object from a list:
def choice(somelist):
...
Now imagine further that, either in that function or elsewhere in your module, you are using randint from the random library:
a = randint(1, x)
Therefore we
import random
You suggestion, that this does what is now accessed by from random import *, means that we now have two different functions called choice, as random includes one too. Only one will be accessible, but you have introduced ambiguity as to what choice() actually refers to elsewhere in your code.
This is why it is bad practice to import everything; either import what you need:
from random import randint
...
a = randint(1, x)
or the whole module:
import random
...
a = random.randint(1, x)
This has two benefits:
You minimise the risks of overlapping names (now and in future additions to your imported modules); and
When someone else reads your code, they can easily see where external functions come from.
There are a few good reasons. The module provides a sort of namespace for the objects in it, which allows you to use simple names without fear of collisions -- coming from a C background you have surely seen libraries with long, ugly function names to avoid colliding with anybody else.
Also, modules themselves are also objects. When a module is imported in more than one place in a python program, each actually gets the same reference. That way, changing foo.a changes it for everybody, not just the local module. This is in contrast to C where including a header is basically a copy+paste operation into the source file (obviously you can still share variables, but the mechanism is a bit different).
As mentioned, you can say from foo import * or better from foo import a, but understand that the underlying behavior is actually different, because you are taking a and binding it to your local module.
If you use something often, you can always use the from syntax to import it directly, or you can rename the module to something shorter, for example
import itertools as it
When you do import foo, a new module is created inside the current namespace named foo.
So, to use anything inside foo; you have to address it via the module.
However, if you use from from foo import something, you don't have use to prepend the module name, since it will load something from the module and assign to it the name something. (Not a recommended practice)
import importlib
# works like C's #include, you always call it with include(<path>, __name__)
def include(file, module_name):
spec = importlib.util.spec_from_file_location(module_name, file)
mod = importlib.util.module_from_spec(spec)
# spec.loader.exec_module(mod)
o = spec.loader.get_code(module_name)
exec(o, globals())
For example:
#### file a.py ####
a = 1
#### file b.py ####
b = 2
if __name__ == "__main__":
print("Hi, this is b.py")
#### file main.py ####
# assuming you have `include` in scope
include("a.py", __name__)
print(a)
include("b.py", __name__)
print(b)
the output will be:
1
Hi, this is b.py
2

Multiple Files handling with Codependency - Python

I just finished the tutorial for making a rogue-like-game and I'm on my way to implement freatures.
The problem is, the whole game is a single file with 1k+ lines.
As you can see:
http://roguebasin.roguelikedevelopment.org/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod,_part_13_code
I want to divide it in different files/folders to handle the implements better.Maybe a file for each aspect of the game like map/player/npcs/items... but at least divide in Classes/Functions/Main.
The problem is, when I put this in the Main.py:
from Classes import *
from Functions import *
I get
NameError: name 'libtcod' is not defined
Which is a Module used in Main.
Then I tried to import the Main.py in the Classes.py and Functions.py
And get the
NameError: global name 'MAP_WIDTH' is not defined
MAP_WIDTH is a global variable in Main.py
I also tried to import the whole Main.py in Classes.py and Functions.py
But I get:
NameError: name 'Fighter' is not defined
Fighter is a Class inside Classes.py
Can anyone help me sort this out so I can start implement freatures.
EDIT: One simple example is:
Main.py
from Functions import *
def plus_one(ab):
return ab +1
a = 1
b = 2
c = add_things()
print plus_one(c)
Functions.py
from Main import *
def add_things():
global a,b
return a + b
It's a simple example, but in the project it get a lot of mutual dependecy between classes/functions and the main file.
There are many issues with your code and your planned program architecture. Please read my comment on your post. You need to shore up your knowledge of object oriented programming.
First, it is highly recommended to never use from Classes import *. You should use import Classes. Then to access functions or constants from the module you would use Classes.function_name or Classes.constant. See for more info on how to properly import in Python: http://effbot.org/zone/import-confusion.htm
Second, global variables are not recommended in Python. But if you do need them, you need to remember that in python a global variable means global to a module, not your entire program. Global variables in Python are a strange beast. If you need to read a global variable nothing special is required. However if you want to modify a global variable from within a function, then you must use the global keyword.
Thirdly, what you are doing is called a circle dependancy. Module A, imports Module B and Module B imports Module A. You can define shared functions, classes etc. in a third Module C. Then both A and B can import Module C. You can also defined your constants like MAP_WIDTH in module C and access them from A or B with C.MAP_WIDTH provided you have an import C.

Python imports across modules and global variables

I have a question which seems to be rather fundamental but I can't seem to find any help on this anywhere.
file_a.py >>
from xyz import XYZ
class A:
.
.
.
file_b.py >>
import file_a
from file_a import A
class B(A):
def __init__(self):
A.__init__(self)
def someMethod(self):
XYZ.doSomething()
XYZ.doSomething() fails saying NameError: name 'XYZ' is not defined
Even standard imports like 'import sys' done from file_a does not seem to render it usable in file_b. I assumed that should work. Is my understanding wrong? If yes, then is there a way to have common imports and global variables across files? (If it is of nay help, I've been a C++ and java programmer and am now starting to use python. )
Is my understanding wrong?
Yes, because the line from file_a import A import only class A into the namespace of file_b. The namespace of file_a is left alone. If it were not like this, there would be little sense in having both syntax:
import modulename
from modulename import something
as if your thinking was right, then after the second form you would always be able to use modulename.someotherthing.
If yes, then is there a way to have common imports and global variables across files?
Yes, with the star * operator:
from modulename import *
but this brings the issue of namespace pollution, for example from file_a import * will import in file_b also all the imports done in file_a. You will eventually lose control of your imports and this will bite you at some time... trust me on this!
When for some reason from module import * is needed, a workaround to namespace pollution is to define in module the variable __all__, which whitelists what should be imported with the star operator.
HTH!
When you import a module, all the variables defined in that module are available in its namespace. Hence, if XYZ is available in file_a module, when you import file_a you can access XYZ as file_a.XYZ.
The general idea here is that your namespace shouldn't be cluttered with the contents of other namespaces.
Yes, your understanding is wrong. Each module is its own namespace, and only things you explicitly import within that file are available in that namespace.
Contrary to other answers, it is not particularly Pythonic to refer to file_a.XYZ, although this will work. Instead, you should import XYZ and sys at the top of file_b.
import file_a
from file_a import A
I think the problem is: you do not import XYZ really!
from fila_a import *
can solve your problem,but it is not a good way~~~
you can write this in file_b:
from file_a import XYZ
It is done?

Categories

Resources