Python Cross Module Variables - python

I realize there are other threads addressing this problem but as I am fairly new to 'Classes' and have already constructed my class structure ... I would like to find a method that I can integrate into my code. I'm sure this will NOT be a difficult one to answer!
First File: NameResult.py
from NameAssign import *
NameList = NameWorks()
print(NameList.InputNames(NameVar))
Second File: NameAssign.py
class NameWorks:
def __init__(self, NameVar = []):
self.NameVar = NameVar
def InputNames(self, NameVar):
global NameVar
NameVar = ['harry', 'betty', 'sam']
Result:
NameError: name 'NameVar' is not defined
All replies are much appreciated ...

NameVar is not defined in NameAssign; it only exists within NameAssign.NameWorks.InputNames() as a local variable. The easiest way to fix this is to define it in NameAssign at the global level.
Edit:
It turns out that this is what you want to do:
NameResult.py
import NameAssign
namelist = NameAssign.NameWorks(['harry', 'betty', 'sam'])
print namelist.InputNames() # or print(...) for Py3k
NameAssign.py
class NameWorks(object):
def __init__(self, names):
self.names = names
def InputNames(self):
return self.names

Related

I am trying to update a global variable using a function which is in an imported module. Both files are in the same folder

# zzz.py
def Put(mess):
global Dict
global Lot
print(mess)
Dict = {}
Lot.append(Dict)
# www.py
from zzz import Put
Dict={}
Lot=[Dict]
Put('abcde')
print(Lot)
I get the following error:
NameError: name 'Lot' is not defined
If I place the Put(mess) function in the www.py file it works just fine.
What am I doing wrong ?
Global variables are not able to do what you want (as mentioned in the comment of John Gordon), but you could use a class as a workaround, like this:
Define the class in a module and add the init function with your "global" variables.
class zzz_class():
def __init__(self):
self.Dict = {}
self.Lot = []
# zzz.py
def Put(self, mess):
print(mess)
self.Lot.append(self.Dict)
Then import the class and use the variables and functions from it.
# www.py
from zzz import zzz_class
z = zzz_class()
z.Dict={}
z.Lot=[z.Dict]
z.Put('abcde')
print(z.Lot)
abcde
[{}, {}]

Getting a NameError for a variable I have defined in my Class

I am trying to run some code that allows me to either call the name Student or Programmer from the class I called Master_programmer. Here is the code I used.
class Master_programmer:
capabilities = []
student = "SoloLearn Student"
programmer = "Programmer"
def Student(self):
return 'SoloLearn Student'
def Programmer(self):
return 'Programmer'
def __init__(self, name):
self.name = name
def add_capabilities(self, capability):
self.capabilities.append(capability)
m1 = Master_programmer(programmer)
print(m1.Student, m1.Programmer)
a.add_capabilities('Stay Inspired')
b.add_capabilities('Find Clients')
b.capability
After running the above code, I get the following error
Traceback (most recent call last):
File "./Playground/file0.py", line 21, in <module>
m1 = Master_programmer(programmer)
NameError: name 'programmer' is not defined
Now, my question is, how do I get my code to deliver the expected results? e.g when I request for the Name 'programmer' to be called up, I expect it to bring up Programmer and then allow me to add capabilities to the programmer like "Find Clients". And for Student it must be "Stay Inspired".
I guess the below code and its comments will answer your question.
class Master_programmer:
STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES = 'This is Static Var'
def __init__(self, name):
self.name = name
self.capabilities = []
self.student = "SoloLearn Student"
self.programmer = "Programmer"
def get_student(self):
return self.student
def get_programmer(self):
return self.programmer
def add_capabilities(self, capability):
self.capabilities.append(capability)
# Create instance for your class and name it coder (or whatever you like)
coder = Master_programmer('Replace me with student name')
# to call coder object's variable
# you need to call it by object name just like below
print('capabilities: ', coder.capabilities)
print(coder.programmer)
print(coder.student)
coder.add_capabilities('Stay Inspired')
coder.add_capabilities('Find Clients')
print(coder.get_student())
print(coder.get_programmer())
print('capabilities: ', coder.capabilities)
print()
# you can invoke Static variables usign directly class name
# you can invoke usign instance name as well but, it is not convention
print(Master_programmer.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
print()
# if you change Static member, it will get change for all of your instances
coder_2 = Master_programmer('Replace me with student name')
Master_programmer.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES = 'changed'
print()
# print static var using both ways
print(Master_programmer.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
print(coder.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
print(coder_2.STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES)
m1 = Master_programmer(programmer)
print(m1.Student, m1.Programmer)
Is calling the variable programmer if you wan to refer to programmer = "Programmer" in the Master_programmer class you need to use Master_programmer.programmer instead.
Though your code will later crash if you don't initialse a and b too since you need to define them too like normal variables e.g. a = Master_programmer("EEZi") to call them and/ or work with them
Thank you all for your answers. Here is the final code that I went with and it works really well. Many Thanks to you.
class Master_programmer:
STATIC_VARIABLE_ONE_FOR_EVERY_INSTANCES = 'This is Static Var'
def __init__(self, name):
self.name = name
self.capabilities = []
self.student = "SoloLearn Student"
self.programmer = "Programmer"
def get_student(self):
return self.student
def get_programmer(self):
return self.programmer
def add_capabilities(self, capability):
self.capabilities.append(capability)
coder = Master_programmer('EEZi')
coder.add_capabilities('Stay Inspired!')
coder.add_capabilities('Find Clients')
a = coder.get_student()
b = coder.get_programmer()
capabilities = coder.capabilities
for i in range(0,1):
print(a)
print("Listen here, just", coder.capabilities[0], "\n")
print(b)
print("Hustle hard and", coder.capabilities[1])

Python parent class modifiable by child class or dynamic attribute?

So I am not even sure if what I want to do is possible but I thought I would ask and find out.
I want to build a chef "databag" via python. This is pretty much just a python dictionary. There are other things that need to happen with this databag that are encapsulated in the Databag class.
Now for the meat of the question...
I want to add key/values to this dictionary but need to build it in a way that is easily extensible. NOTE: the autodict is a class that makes it so you can build a dictionary using dot notation.
Here is what I am trying to do:
databag = Databag(
LogGroup=Sub("xva-${environment}-${uniqueid}-mygroup"),
RunList=[
"mysetup::default",
"consul::client"
]
)
databag.Consul() <-- Trying to add consul key/values to databag
print(databag.to_dict())
print(databag.to_string_list())
So you can see how I add the "consul" key values to the already existing databag object.
Here are the class definitions. I know this is wrong which is why I am here to see if this is even possible.
Databag Class
class Databag(object):
def __init__(self,uniqueid=Ref("uniqueid"),environment=Ref("environment"),LogGroup=None,RunList=[]):
self.databag = autodict()
self.databag.uniqueid = uniqueid
self.databag.environment = environment
self.databag.log.group = LogGroup
self.runlist=RunList
def to_string_list(self):
return self.convert_databag_to_string(self.databag)
def to_dict(self):
return self.databag
def get_runlist(self):
return self.convert_to_runlist_string(self.runlist)
Consul Class
class Consul(Databag):
def __init__(self, LogGroup=None):
if LogGroup == None:
Databag.consul.log.group = Databag.log.group
else:
Databag.consul.log.group = LogGroup
As you can see the Consul class is supposed to access the databag dictionary of the Databag class and add the "consul" variables, almost like an attribute. However, I don't want to add a new function to the databag class every time otherwise that class will end up being very, very large.
I was able to get something like this to work with the following method. Although I am up for an suggestions to get this to work. I just read the help posted on this link:
http://www.qtrac.eu/pyclassmulti.html
EDIT: This method is a lot easier:
Note: This uses the exact same implementation of the old method.
consul.py
from classes.databag.utils import *
class Consul:
def Consul(self, LogGroup=None):
if LogGroup == None:
self.databag.consul.log.group = self.databag.log.group
else:
self.databag.consul.log.group = LogGroup
databag.py
from classes.databag.utils import autodict
from classes.databag import consul
class Databag(consul.Consul):
def __init__(self,uniqueid=Ref("uniqueid"),environment=Ref("environment"),LogGroup=None,RunList=[]):
self.databag = autodict()
self.databag.uniqueid = uniqueid
...
...
Folder Structure
/classes/
databag/
utils.py
databag.py
consul.py
testing.py
---- OLD METHOD -----
How I implemented it
from classes.databag.databag import *
databag = Databag(
LogGroup=Sub("xva-${environment}-${uniqueid}-traefik"),
RunList=[
"mysetup::default",
"consul::client"
]
)
databag.Consul()
print(databag.to_dict())
print(databag.to_string_list())
lib.py
def add_methods_from(*modules):
def decorator(Class):
for module in modules:
for method in getattr(module, "__methods__"):
setattr(Class, method.__name__, method)
return Class
return decorator
def register_method(methods):
def register_method(method):
methods.append(method)
return method
return register_method
databay.py
from classes.databag import lib, consul
#lib.add_methods_from(consul)
class Databag(object):
def __init__(self,uniqueid=Ref("uniqueid"),environment=Ref("environment"),LogGroup=None,RunList=[]):
self.databag = autodict()
self.databag.uniqueid = uniqueid
....
....
consul.py
from classes.databag import lib
__methods__ = []
register_method = lib.register_method(__methods__)
#register_method
def Consul(self, LogGroup=None):
if LogGroup == None:
self.databag.consul.log.group = self.databag.log.group
else:
self.databag.consul.log.group = LogGroup
Folder Structure
/classes/
/databag
lib.py
databag.py
consul.py
utils.py
/testing.py

Python Variable empty i don't know why

guys i have a problem with my variable.
When i instance my class my variable dossierProd and dossierModif is not empty but when i want use another function she is empty.
import glob
class OBDI:
dossierProd = ""
dossierModif = ""
listeFichierProd = []
listeFichierModif = []
def __init__(self, dossierP, dossierM):
dossierProd = dossierM
dossierModif = dossierM
def recupListeFichier(self):
HERE MY VARIaBLE dossierProd & dossierModif as empty
for fichier in glob.glob(str(self.dossierProd) + '*.csv'):
self.listeFichierProd.append(fichier.replace("\\", "/"))
for fichier in glob.glob(str(self.dossierModif) + '*.csv'):
self.listeFichierModif.append(fichier.replace("\\", "/"))
if len(self.listeFichierProd) != len(self.listeFichierModif):
print "toto
Have you got an idea why my variable is empty ?
Thx to your response.
Sorry for my bad english ;)
Oh thanks, this error is so stupid.
I'm to be accustomed to java
You haven't initialized dossierP and dossierM instance variables in __init__():
def __init__(self, dossierP, dossierM):
self.dossierProd = dossierM
self.dossierModif = dossierM
Watch self. here.
Also, since it appears that dossierProd and dossierModif variables make sense only for when you have an instance of a OBDI class, remove dossierProd = "" and dossierModif = "" lines.
Also, you probably don't want to share listeFichierProd and listeFichierModif lists between OBDI class instances - initialize lists in __init__():
def __init__(self, dossierP, dossierM):
self.dossierProd = dossierM
self.dossierModif = dossierM
self.listeFichierProd = []
self.listeFichierModif = []
and remove listeFichierProd = [] and listeFichierModif = [] lines.
Make sure you understand what is discussed in the following threads:
Instance variables vs. class variables in Python
python class instance variables and class variables
Hope that helps.

How to access a variable from a class of another module

I am a total python beginner and I have a variable created in a class of a file commandline_reader.py that I want to access from another script. I tried to do it by making the variable global, which doesn't work.
myscript.py:
from commandline_reader import Commandline_Reader
reader = Commandline_Reader('--get_serial_number')
reader.run()
print output
commandline_reader.py:
class Commandline_Reader:
def __init__(self,argString=''):
global output
output = []
def run(self):
# do stuff
a = 'somevariable'
output.append(a)
When I run myscript.py I always get a NameError: name 'output' is not defined. I've read that this is because global variables are only defined within a module. How do I correctly access the output variable in my script?
ouch. The whole reason object oriented programming takes place is to avoid the use of global variables. Make them instance variables to access them anywhere in the class.
class Commandline_Reader:
def __init__(self,argString=''):
self.output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a) #output is now part of the instance Commandline reader and can be accessed anywhere inside the class.
clr = Commandline_Reader(argstring='--get_serial_number')
clr.run()
print clr.output
>>>['somevariable']
Make output an instance attribute:
class Commandline_Reader:
def __init__(self,argString=''):
self.output = [] # note use of self here
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a) # and here
The access it via the instance:
print reader.output
Maybe class attribute is more appropriate for you?
class Commandline_Reader:
output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a)
Just return the Value from the run() Method
myscript.py:
from commandline_reader import Commandline_Reader
reader = Commandline_Reader('--get_serial_number')
output = reader.run()
print output
commandline_reader.py:
class Commandline_Reader:
def __init__(self,argString=''):
self.output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a)
return self.output

Categories

Resources