i can't get the printing of a dict. to work, seen alot exsample codes but none have worked
from UI import ask_info
def main():
mydict = {}
def add(mydict):
info=ask_info()
mydict=info
for i in mydict:
print(mydict[i])
def ask_info():
info1=input("enter the info")
info2=input("enter the info2")
informations=mydict(info1,info2)
return informations
the ask_info is in an different module, if i run this code the print is nothing also if write the dictionary into a file the file is empty. I also have tryed using a class module for this where i have refered to the class module in the "informations=class(info1,info2)" part
As far as I know, dictionaries in Python are not callable and don't work like that. Instead of mydict(info1,info2) you probably want something like mydict[info1] = info2.
Check this link to see how dictionaries work. If you are creating a new dictionary, you can do something like dict([(info1,info2)]) but it does not seem you are trying to do that.
Related
I'm calling a notebook like this:
dbutils.notebook.run(path, timeout, arguments)
where arguments is a dictionary containing many fields for the notebook's widgets.
I want to debug called notebook interactively: copy/pasting the widget parameters takes time and can cause hard-to-spot errors not done perfectly.
It would be nice to just take the arguments dictionary and use it directly. Perhaps copying it, then populating the widgets from the dictionary.
How can I do this, or something like it?
If we get some variables like this:
dbutils.widgets.text('myvar', '-1', '')
myvar = dbutils.widgets.get('myvar')
I can override them like this:
config = {'myvar': '42'}
import sys
module = sys.modules[__name__]
for k, v in config.items():
setattr(module, k, v)
Which means all the overriding happens in a cell I can later delete, leaving no edits in the real code.
Pass the values as a json like below in the widget let it be "Filters"
{"Type":"Fruit","Item":"Apple"]
To read the json you need to make use of json library
import json
filters = dbutils.widgets.get("Filters")
jsonfilter = json.loads(filters)
Now you can access individual items by
jsonfilter["Item"]
I am writing code that reads XML and creates a dictionary. I want to use that dictionary between modules, can I import that generated dictionary to another module?
I thought importing the module would be fine, however since the dictionary is only generated after running the module it is created in, this does not work. Is there any simple way to do this or do I need to write the dictionary to a file and read it again?
One method you could use is to include a return statement in the module that creates a dict. For instance,
def read_xml():
dict1 = create_dict_from_xml()
return dict1
you then could access that dictionary by writing in the other module dict1 = read_xml(). This will only work while the program is running. If you want to save the dict I would recommend using the pickle module. The documentation for that can be fount here. If I didn't answer your question let me know and possibly post some of your source code.
Hope this helped.
How do I implement a class browser in wxPython? Should I scan the whole code, or there is a function for this in wxPython?
Your question isn't entirely clear about what you want, but I'll make some assumptions and show you how to do one of the possible interpretations of what you're asking.
I'll assume you have a string with the contents of a Python script, or a fragment from your cut-and-paste repository, or whatever, and you just want to know the top-level classes defined in that string of source code.
You probably don't want to execute that code. For one thing, who knows what arbitrary strange code can do to your environment? For another, if you're building a class browser, you probably want it to work on code that's depends on other code you may not have access to, so you can't execute it.
So, you want to parse it. The easiest way to do that is to get Python to do it for you, using the ast module:
import ast
with open('mymodule.py') as f:
mycode = f.read()
myast = ast.parse(mycode)
for thing in myast.body:
if isinstance(thing, ast.ClassDef):
print('class {}({})'.format(thing.name,
', '.join(base.id for base in thing.bases)))
for subthing in thing.body:
if isinstance(subthing, ast.FunctionDef):
print(' def {}'.format(name))
When I run this against, say, the ast.py from Python 3.3's stdlib, I get this:
class NodeVisitor(object)
def visit
def generic_visit
class NodeTransformer(NodeVisitor)
def generic_visit
If that's not what you wanted, you'll have to explain what you do want. If, for example, you want all class definitions, even local ones within functions and methods… well, the names of those two classes just dumped out above should help.
I have the following code:
from suchandsuch import bot
class LaLaLa():
def __init__(self):
self.donenow = 0
print "LaLaLa() initialized."
return
def start(self):
pages = bot.cats_recursive('something')
for page in pages:
self.process_page(page)
When I try to run y = LaLaLa() and then y.start(), though, I get an error:
AttributeError: LaLaLa instance has no attribute 'cats_recursive'
This makes me suspect that Python is trying to call cats_recursive() not from suchandsuch's bot sub-module (as is defined at the beginning of the file), but rather from LaLaLa(), which of course doesn't have the cats_recursive() function. Is there a way to force a class instance to use an imported module, rather than just look inside itself?
Posters are correct that there is nothing wrong with the code you have posted.
It's the code you didn't post that is probably the problem. It is hinted at in your naming of cats_recursive. You haven't shown us that perhaps LaLaLa is defined in or imported into bot.py.
One way to replicate your error is:
# in suchandsuch/bot.py
class LaLaLa():
def __init__(self):
self.donenow = 0
print "LaLaLa() initialized."
# don't need a `return` here
def start(self):
pages = bot.cats_recursive('something')
for page in pages:
self.process_page(page)
bot = LaLaLa()
That's just one. Another is to have __init__.py in such and such something like:
bot = LaLaLa()
Like I said, the error is in your code structure.
print the id of the bot inside LaLaLa or captrue the error with pydb and I suspect you will see that bot is an instance of LaLaLa other than y (again check the id's)
You are doing fine. Most probably there is no cats_recursive() attribute in your module for real. Check syntax, check module content.
You might find the easiest way to do this would be to try to assign the cats_recursive() to the pages variable outside the class and then pass the variable to the start() function as a parameter. If this works then keep it that way, if it doesn't work then there's probably something wrong with the code elsewhere.
So I have a dictionary with a bunch of names that I use to call functions. It works fine, but I prefer to put it in my settings file. If I do so, though, I will get errors from the settings file saying that there are no functions by that name(even though I'm not calling them at the time). Any workarounds?
def callfunct(id, time):
#stuff here
def callotherfunct(id, time):
#stuff here
dict = {"blah blah": callfunct, "blah blah blah": callfunct, "otherblah": callotherfunct}
dict[str(nameid)](id, time)
Hope this makes sense. Also open to other ideas, but basically I have about 50 iterations of these definitions and unique names that are passed by nameid that need to call specific functions, so that's why I do it the way I do, so that I can add new names quickly. It would obviously be even quicker if I could get the dictionary into the settings file seamlessly as well.
If you try
def f_one(id, time):
pass
def f_two(id, time):
pass
d = {"blah blah":"f_one", "blah blah blah":"f_one", "otherblah","f_two"
locals()[d[str(nameid)]](id, time)
(replacing the dictionary initialization with just loading the config file with the string name of the functions you want to call), does that work?
If not, there needs to be a little more info: What does the config file look like, and how are you loading it?
I'm guessing the reason that the config file part isn't working is that you're trying to reference the functions directly from the config file, which shouldn't work. This is using whatever's stored in the config file and looking it up in the locals() dictionary (if you're in a function, you'll have to use globals() instead)
You could initialise the dictionary with the looked up function only when you attempt to access it:
d = {}
d.setdefault('func1', globals()['func1'])()