Global variable not acting very globally - python

So I have the following module named examplemod:
def maybeglobal():
global test
test = [1, 2, 3]
I then import the module and run the function:
import examplemod
examplemod.maybeglobal()
When I try to reference the new (supposedly) global variable test, I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined
I'm running 2.6.6 and have been currently banging my head into a wall for about two hours now. Do I just not understand how global is supposed to work? Because I'm pretty sure this is exactly what global is for.
Also, before people get at me for using global variables, the whole purpose of the function I'm working on is to have the custom class object that a module function creates accessible to the user for manipulation.

It's global at the module level. So you need to do examplemod.test and you will get your expected answer.

Related

Why doesn't this simple Python script run?

I am writing a large program where I need to pass data/variables between functions. Note: I'm a hobbyist and OOP is out of my grasp, so just looking for a non-OOP answer!
I'm using functions to try and make the script modular and avoid having one long messy script. But the program uses a dataframe and lots of different variables which many of the functions will need to access. I don't want to specify every single variable in every function call so would like to be able to access global variables from individual functions. I can do this when the def function(): is in the same script, but I am running into a problem when I try and call global variables when importing a function from a script. Simple reprex:
from test_func import p_func
a = "yes!"
p_func()
calling p_func() from test_func.py
def p_func():
global a
print(a)
generates the error:
Traceback (most recent call last):
File "test.py", line 5, in <module>
p_func()
File "test_func.py", line 5, in p_func
print(a)
NameError: name 'a' is not defined
What am I missing?
You need to change your import line to be:
from test_func import p_func, a
Variables are imported from other modules the same way that functions are.
That said. This is really, really a bad idea as others above has said. Your best off putting all your variables into a single data structure of some sort

Python 3 Assume Module Namsepace

quick question regarding python namespaces. I am new to python, so this may be a novice question and have a simple answer, but I have searched and can't seem to find it.
My question is simply to know if there is a way to state a namespace so that you do not need to say the module name each time you access a class declared inside it.
For example:
>>> import fractions
>>> myFrac = fractions.Fraction("3/4")
>>> str(myFrac)
'3/4'
>>> myFrac = Fraction("3/4")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Fraction' is not defined
>>>
I would like to know if there is a way to avoid the need of typing the module name. I am also interested in whether or not doing so is the conventional to write code in python.
You can use from <module> import <class> to shorten your work
from fractions import Fraction
Edit:
Since this question is about namespaces, you're also allowed to do give fancier names
from animals import Dog as Scooby
and thereafter use the module name Scooby. Though this make it hard to track module usages later on.

I'm getting AttributeError when I call a method in other class

I'm very new to Python and I have a code like this:
class Configuration:
#staticmethod
def test():
return "Hello World"
When I call the method test from other python code like this:
import test
test.Configuration.test()
I get an error like this:
Traceback (most recent call last):
File "example.py", line 3, in <module>
test.Configuration.test()
AttributeError: 'module' object has no attribute 'test'
where I'm making the mistake?
Edit:
My directory structure:
root
--example.py
--test
----__init.py__
----Configuration.py
Python module names and the classes they contain are separate. You need use the full path:
import test
print test.Configuration.Configuration.test()
Your test package has a module named Configuration, and inside that module is your Configuration class.
Note that Python, unlike Java, lets you define methods outside classes too, no need to make this a static method. Nor do you need to use a separate file per class.
Try to rename your module to something other than 'test', since this is the name of a standard library module (http://docs.python.org/2/library/test.html) and probably you're importing that module instead of your own. Another option is to add the directory containing your test module into the PYTHONPATH environment variable, so that python may find it instead of the standard library module (but this is not advised as it shadows the standard module and you won't be able to import it later).
To check which file you're importing from, do:
import test
print test

Is it possible to import to the global scope from inside a function (Python)?

I am trying to import a module from inside a function and have it be available to my whole file the same way it would be if I imported outside any functions and before all the other code. The reason it is in a function is because I don't have much control over the structure of the script. Is this possible without resorting to things like hacking __builtin__ or passing what I need all around my code?
How about something like globals()["os"] = __import__("os")?
I guess this could be wrapped in a generic function if you wanted since the module name is a string.
Seeing your new comments, I want to emphasize that this sounds unnecessary. You're actually modifying the script more by importing within a function than by importing at the top of the script in the normal way. Still, in the spirit of answering the question asked, I'm leaving my previous answer.
I'm honestly not certain this is the correct way to do this, but a quick check confirms that if you declare the module name as global within the function before importing, it is imported into the global namespace.
>>> def import_re():
... global re
... import re
...
>>> re
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 're' is not defined
>>> import_re()
>>> re
<module 're' from '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.pyc'>
Don't do this unless you really have to -- and then write it in big red letters, so to speak.

Python: Help with UnboundLocalError: local variable referenced before assignment

I keep getting this error for a portion of my code.
Traceback (most recent call last):
File "./mang.py", line 1688, in <module>
files, tsize = logger()
File "./mang.py", line 1466, in logger
nl = sshfile(list, "nl")
UnboundLocalError: local variable 'sshfile' referenced before assignment
I haven't put the code up cause it goes back and forth between functions. I'm wondering if anyone could tell me why python is spitting this error? sshfile is not a variable it's a class.
You probably haven't imported the file which contains the definition of sshfile, or you need to qualify the class name with the package name. It depends on how you imported it.
What package does it come from? Where is it defined?
Update
For anyone else reading this, after a discussion in the comments it turned out that the problem was that the name sshfile had been used further down in the function as a variable name, like this:
class sshfile:
pass
def a():
f = sshfile() # UnboundLocalError here
sshfile = 0
a()
The solution is to not use a variable name that hides a class name that you need to use.

Categories