I am opening and reading in a json file called, say, my_file.json located at ..\config\my_file.json in a python file called run_test.py. Ultimately, I would like to turn the JSON object into a python dictionary and do other stuff with it in python. I am running the below code from my terminal to execute the class:
python -c "from run_test import Update; x = Update('my_file.json'); print(x.why())"
This returns:
Traceback (most recent call last): File "<string>", line 1, in <module> TypeError: why() missing 1 required positional argument: 'file_details'
I can't figure out why I'm getting this error. When I run (with return f in the body of read_file):
python -c "from run_test import Update; x = Update('my_file.json'); print(x.read_file())
This prints the dictionary I need. However, I would like to pass it to why so I can do other stuff with that dictionary. Yet, when I pass f to why, I get the above error. Why?
Here is the class I'm using:
import json
class Update:
def __init__(self, config_file_name):
self.config_file_name = config_file_name
def why(self, file_details):
return file_details
def read_file(self):
f = json.load(open('..\config\\' + self.config_file_name))
self.why(f)
Related
I'm going crazy trying to perform simple editing while creating a Python class constructor. I can create the simple class and constructor variable but once I try to change the names of the variable I get a KeyError.
The class is below:
class Collect:
def __init__(self, **kwargs):
self.foo = kwargs["foo"]
And the script where I instantiate the class and print out its attributes is below:
import mapper as m
payload = m.Collect(foo="Hello")
print(payload.foo)
Now this works just fine, but if I change "foo" to "bar" I get a KeyError Like below:
class Collect:
def __init__(self, **kwargs):
self.bar = kwargs["bar"]
and then running:
import mapper as m
payload = m.Collect(bar="Hello")
print(payload.bar)
will throw the following error:
Traceback (most recent call last): File "<stdin>", line 1, in
<module> File
"/path/to/mapper.py",
line 8, in __init__
self.bar = kwargs["bar"] KeyError: 'foo'
And the print function will throw the error below:
Traceback (most recent call last): File "<stdin>", line 1, in
<module> AttributeError: 'Collect' object has no attribute 'bar'
The weird thing is that if I hit save and then close VSCode and reopen, the new class with bar will work just fine. And, also even if I don't close VSCode the class will instantiate and the print statement will run just fine when I switch to Debug mode and run it. But when I try to highlight it and run a selection it throws that error.
How can I just test if the code works using the run selection operations and not relying on running in debug mode with breakpoints or having to close and reopen VSCode?
The solution was to reload my Python session. The VSCode reload extension makes this easy.
I have created a simple function for reporting current values of variables in some engineering scripts, by passing the variable name in an eval() function. The argument is passed as string then the eval() reads it and reports back the value with some additional info. The function works properly in a single script. However when i am importing the same function from a module i get back an error saying that the variable has is not defined.
I have trying setting it up as a global variable but still get the same problem
def report(name,units = '-',comment ='NC'):
if type(eval(name)) == str:
print('{0:<12}= {1:^10} {2:^5} {3}'.format(name,eval(name),units,comment))
else:
print('{0:<12}= {1:8.3f} {2:^5} {3}'.format(name,eval(name),units,comment))
While trying to use the function from the imported module i get the following
>>>from reporting import*
>>> from shapes import*
>>> Iyy = rec_Iyy(40,60)
>>> report('Iyy')
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
File "C:\Users\vousvoukisi\OneDrive\11.Python\03_myScripts\design_mod\reporting.py", line 8, in report
if type(eval(name)) == str:
File "<string>", line 1, in <module>
NameError: name 'Iyy' is not defined
## while i would expect the outcome to be :
>>> %Run reporting.py
Iyy = 720000.000 - NC
I'm trying to import a module (module_name.py) that I've created using __import__()
but am seeing the following error:
Traceback (most recent call last):
File "test.py", line 80, in <module>
testImportMethod()
File "test.py", line 68, in testImportMethod
m = __import__("module_name")
File "/dir/module_name.py", line 147
def insert_model(model: MyModel):
^
SyntaxError: invalid syntax
module_name.py has the following code:
class MyModel(object):
property1 = None
property2 = None
class ThingDAO(object):
#staticmethod
def get_thing_by_id(id):
...
#staticmethod
def insert_model(model: MyModel):
...
Why does the import process have a problem with typed parameters?
It's not the import process that has problems with typed parameters. The problem is that typed parameters were added in Python 3.5 (PEP 484) and raise such SyntaxErrors for example on Python 2.7.
Likely (given the SyntaxError) you're using an older version of Python and to make it work you either have to install and use a newer Python version or use on of the workarounds mentioned in the PEP, for example:
class MyModel(object):
property1 = None
property2 = None
class ThingDAO(object):
#staticmethod
def get_thing_by_id(id):
pass
#staticmethod
def insert_model(model):
# type: (MyModel) -> None
pass
The code below is used as part of a SimpleXMLRPCServer to receive commands from a Java client I've written. The Java client will just call this execute function and pass in a function name from the CameraAssembler class.
from nsCamera.CameraAssembler import CameraAssembler
class MyFunctions:
ca = None
def initialize(self):
# Create Camera object
self.ca = CameraAssembler(commname=COMM, boardname=BOARD, sensorname=SENSOR, verbose=True)
return True
def execute(self, code):
func = getattr(self.ca,code)
output = func()
return output
myfuncs = MyFunctions()
myfuncs.initialize()
output = myfuncs.execute('arm()')
print(output)
Output:
Traceback (most recent call last):
File "pyTestServer.py", line 31, in <module>
output = myfuncs.execute("arm()")
File "pyTestServer.py", line 21, in execute
func = getattr(MyFunctions.ca,code)
AttributeError: CameraAssembler instance has no attribute 'arm()'
Your parentheses are in the wrong place. The attribute is not called arm(), it's called arm; you need to call the result of getting that attribute.
output = myfuncs.execute('arm')()
(Note, this code isn't particularly idiomatic. In particular, I can't see why you're setting ca as a class attribute, rather than an instance one. Also, initialisation usually goes in an __init__ method, which is called automatically on instantiation.)
I'm new-ish to Python and I'm having trouble achieving a result that I want. I'm opening a text file called urldata.txt which contains URLs that I need to break down by scheme, server, and path.
I have retrieved the data from the file:
urls = open("urldata.txt").read()
print(urls)
this returns:
http://www.google.com
https://twitter.com/search?q=%23ASUcis355
https://github.com/asu-cis-355/course-info
I want to break these URLs into 3 pieces each so that when I enter
urls.scheme()
urls.server()
urls.path()
It will return me the scheme of each URL when I enter
urls.scheme()
'http','https','https'
Then it will return the server when I enter
urls.server()
'google.com'
'twitter.com'
'github.com'
Finally, it will return the path when I enter
urls.path()
'/'
'/search?q=%23ASUcis355'
'/asu-cis-355/course-info'
I have defined a class to do this; however, I receive an error saying 'scheme() missing 1 required positional argument: 'self' Below is my class and the def parts to it that I have created.
class urls:
def __init__(self,url):
self.urls=urls
def scheme(self):
return urls.split("://")[0]
def server(self):
return urls.split("/")[2]
def path(self):
return urls.split(".com/")[1]
Any help at all is greatly appreciated!
This exists already. It's called urlparse:
from urllib.parse import urlparse
d = urlparse('https://twitter.com/search?q=%23ASUcis355')
print(d)
Output:
ParseResult(scheme='https', netloc='twitter.com', path='/search', params='', query='q=%23ASUcis355', fragment='')
If you attempt to call a class definition (what urls' is) without creating an instance of this class in Python3 then you get this error
>>> urls.scheme()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: scheme() missing 1 required positional argument: 'self'
>>>
But if you create an instance of urls and then use that instance this works as intended
>>> url_instance = urls("http://www.google.com")
>>> url_instance.scheme()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in scheme
AttributeError: type object 'urls' has no attribute 'split'
Note that this fixes your current error but your code isn't correct as is. I'll leave you to figure out what's happening with this error.
The difference between a class definition (or type) and an instance of the class has some interesting nuance but generally speaking
class Thing:
pass
is a class definition and
thing_instance = Thing()
Is an instance of the class.