Passing a variable through a class Python - python

I am trying to print to pass the endpoint variable to the __init__ function within the RUN() class. However it is giving me an error. AttributeError: module 'configs' has no attribute 'endpoint'. The endpoint document is saved in the file1.py and it is called in file2.py. How would I be able to pass endpoint as a param.
file1
endpoint = 'hello'
file2
import file1
class RUN():
def __init__(self, endpoint= file1.endpoint):
print("Initialized")
run_websocket = RUN()

The code is absolutely correct. Try deleting the cache of your IDE or build and dist folders, etc. then run again.

Related

How do I access the variable inside a class method from another python file?

I have two python files main.py and conftest.py. I want to access a variable of a method of the class Test declared in main.py from a function declared in conftest.py.
I have tried a bit, but I know it's wrong as I get a syntax error in the first place. Is there any way to do this?
main.py
class Test():
def test_setup(self):
#make new directory for downloads
new_dir = r"D:\Selenium\Insights\timestamp}".format(timestamp=datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
# print(new_dir)
if not os.path.exists(new_dir):
os.makedirs(new_dir)
saved_dir=new_dir
conftest.py
from main import Test
def newfunc():
dir=Test.test_setup()
print(dir.saved_dir)
There are some errors in your code, but essentially, to access to the variable saved_dir you have to define it as an attribute of the class Test, and after that instantiate an object of that class.
In your code saved_dir is a local variable of the method test_setup so is not visible outside of that context.
I show you the 2 possible correct files:
File main.py
from datetime import datetime
import os
class Test():
def __init__(self):
self.new_dir = ""
self.saved_dir = ""
def test_setup(self):
#make new directory for downloads
#new_dir = r"D:\Selenium\Insights\timestamp}".format(timestamp=datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
timestamp=datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
self.new_dir = "/home/frank/Selenium/Insights/timestamp/" + timestamp
# print(new_dir)
if not os.path.exists(self.new_dir):
os.makedirs(self.new_dir)
self.saved_dir = self.new_dir
def get_saved_dir(self):
return self.saved_dir
Pay attention: don't use directly the previous code because in main.py I have adjusted the value of new_dir according to my environment (see /home/frank/Selenium/Insights/timestamp/ instead of your D:\Selenium\Insights\timestamp).
File conftest.py:
from main import Test
def newfunc():
test_class = Test()
test_class.test_setup()
print(test_class.get_saved_dir())
newfunc()
If you want to access to the attribute saved_dir directly without the use of method get_saved_dir() (not very object oriented) the file conftest.py becomes:
from main import Test
def newfunc():
test_class = Test()
test_class.test_setup()
# access directly to attribute saved_dir (not properly Object Oriented)
print(test_class.saved_dir)
newfunc()
Variable must be declared as belonging to the class
class Test():
def __init__(self):
self.new_dir = ""
self.saved_dir = ""
def test_setup(self):
#make new directory for downloads
self.new_dir = r"D:\Selenium\Insights\timestamp}".format(timestamp=datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
# print(self.new_dir)
if not os.path.exists(self.new_dir):
os.makedirs(self.new_dir)
self.saved_dir=self.new_dir
Then calling it
def newfunc():
dir=Test().test_setup()
print(dir.saved_dir)

how to test a Python class that requires command line argument?

I have a python class that requires a command line argument:
class SomeClass:
request = sys.argv[1] + ".json"
def __init__(self_:
self.req = request
i'd run someClass.py on the commandline i.e. python someClass 1234, which would set the json to 1234.json.
I want a second class, testClass.py, to be able to test methods inside of the main class. But first, i just want to make sure its connected by printing variables:
from someClass import SomeClass
i = SomeClass()
print(i.req)
if i run python testClass.py (without any input), i get a missing input error,
error: the following arguments are required: input
so if i run python testClass.py 1234, i get
none
i just want to know how to pull the class in and make sure its provided with an argument so i can test individual components inside of it.
Just overwrite request in every test that needs it:
import unittest
from x import SomeClass
class TestClass(unittest.TestCase):
def setUp(self):
SomeClass.request = ''
In general, don't make classes which set themselves up. Make the class take parameters which are not defaulted.
You can always make higher level code which supplies default values.
Don't make your class depend on sys.argv in the first place.
class SomeClass:
def __init__(self, base):
self.req = base + ".json"
Then
from someClass import SomeClass
i = SomeClass(sys.argv[1]) # or any other value
print(i.req)

Passing args as part of unittests to test pyspark script

I have a python script which currently takes a command line argument 'path to the json file' and carries out some cleaning up on the data.
I am writing some unit tests where I am trying to pass path to the json file as an arg. It currently comes up with an error when no arg is passed but when it is passed i get the error:
AttributeError: 'module' object has no attribute 'data' which is data.json.
I want to have three separate unit tests each having a different json file to be passed as an argument.
My code is as follows:
import unittest
import sys
import argparse
class TestTransform(unittest.TestCase):
def test_transform(self,input_filename):
target = __import__("cleaning.py")
transform = target
transform.ARGS(input_filename)
self.assertTrue('Pass')
if __name__ == '__main__':
unittest.main()
If I understood your problem correctly here is what I normally do in this case. I override the setUpClass method and make all the inputs to this class attributes that can be accessed by the tests:
class TestTransform():
#classmethod
def setUpClass(self, file_name):
self.input_filename = file_name
#Some other initialization code here
def test_transform(self):
target = __import__("cleaning.py")
transform = target
transform.ARGS(self.input_filename)
self.assertTrue('Pass')
If you then want to make different tests with different input values you can create other classes by subclassing the TestTransform class (and of course the unittest.TestCase):
class Test1(TestTransform, unittest.TestCase):
#classmethod
def setUpClass(self):
input_filename = 'MyFileName'
#Here call the setUpClass from the TestTransform class
TestTransform.setUpClass(input_filename)

How Pylint determine Instance has variable or not

I have written simple file and run Pylint on this code code. Does anyone have idea How Pylint determine that Class sample does not have second variable.
Purpose: I would like to write simple script which will read sample
file(python code) and check which instance variable is accessed and
set by Instance. Ex if I write in main time.initial_time than my script able to detect that initial_time has been accessed by time Instance. it will be run at the run time. I mean, it will be part of existing flow
Real Purpose
To filter out unused member variable of class which is used thousands places and more than 100 variable
Sample file
"""testing pylint code"""
#!/usr/bin/env py
class Sample(object):
"""create sample class"""
def __init__(self):
"""seting variable"""
self.intial_time = 0
def main():
"""main functionality"""
time = Sample()
print time.second
if __name__ == " __main__":
main()
Pylint Error:
************* Module class_instance
R: 3, 0: Too few public methods (0/2) (too-few-public-methods)
E: 12,10: Instance of 'Sample' has no 'second' member (no-member)

Access instance in other modules

I have a class instance I want to access in other modules. This class loads config values using configParser to update an class instance __dict__ attribute as per this post:
I want to access this instance in other module. The instance is only created in the main.py file where it has access to the required parameters, which come via command line arguments.
I have three files: main.py, config.py and file.py. I don't know the best way to access the instance in the file.py. I only have access to it in main.py and not other modules.
I've looked at the following answers, here and here but they don't fully answer my scenario.
#config.py
class Configuration():
def __init__(self, *import_sections):
#use configParser, get config for relevant sections, update self.__dict__
#main.py
from config import Configuration
conf = Configuration('general', 'dev')
# other lines of code use conf instance ... e.g. config.log_path in log setup
#file.py
#I want to use config instance like this:
class File():
def __init__(self, conf.feed_path):
# other code here...
Options considered:
Initialise Configuration in config.py module
In config.py after class definition I could add:
conf = Configuration('general', 'dev')
and in file.py and main.py:
from config import conf
but the general and dev variables are only found in main.py so doesn't look like it will work.
Make Configuration class a function
I could make it a function and create a module-level dictionary and import data into other modules:
#config.py
conf = {}
def set_config(*import_section):
# use configParser, update conf dictionary
conf.update(...)
This would mean referring to it as config.conf['log_path'] for example. I'd prefer conf.log_path as it's used multiple times.
Pass via other instances
I could pass the conf instance as parameters via other class instances from main.py, even if the intermediate instances don't use it. Seems very messy.
Other options?
Can I use Configuration as an instance somehow?
By changing your Configuration class into a Borg, you are guaranteed to get a common state from wherever you want. You can either provide initialization through a specific __init__:
#config.py
class Configuration:
__shared_state = {}
def __init__(self, *import_sections):
self.__dict__ = self.__shared_state
if not import_sections: # we are not initializing this time
return
#your old code verbatim
initialization is donne as usual with a c = config.Configuration('general','dev') and any call to conf = config.Configuration() will get the state that c created.
or you can provide an initialization method to avoid tampering with the shared state in the __init__:
#config.py
class Configuration:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
def import(self, *import_sections):
#your old __init__
that way there is only one meaning to the __init__ method, which is cleaner.
In both cases, you can get the shared state, once initialized, from anywhere in your code by using config.Configuration().

Categories