So I recently ran into a framework (for a chat bot) that was very clever.
It used a combination of things to make it extremely dynamic. Most of these things I already know how to replicate. Yet there was something that really caught my eye, and made me really wonder.
How do you obtain the comment?
def foo():
'''My function comment'''
return 'foo!'
In this framework: It would pull the comment, and use it as it's help.
So for example we say !help foo
It would return My function comment
It really boggles my mind, since I always thought comments weren't kept in memory. So I have to assume it's using some kind of inspection on it's own file. I'm just very curious on how this works, and if anyone has any libraries that would help with this, please let me know.
Edit: for anyone wanting to look at the framework; here is the link
That's not a comment - comments are lines that start with #
This is a docstring.
You can access the docstring using foo.__doc__
The help function would thus be
def help(thing)
return thing.__doc__
When you type !help foo behind the scenes the framework calls help(foo).
You can access it with .__doc__
Related
I'm new to Python and this is my first question here. Hope any of you guys will be able to help me out.
I'm trying to call values inside an object from an external program. The object that I'm trying to access is given in a class (as i uderstand it), and the name of the class may change according to X, see below:
External programs object and class information
I want to be able to call information from Phase_6 in this case, however it could be Phase_12 in another case. I was considering making a function where i could have the _'Number' as an input. But I can't seem to find any information of how to do such.
I was thinking of something like using +str(X), as I do when plotting. But as it is probably not a string, it doesn't work out.
My proposed code
Ive read that bpy in Blender may be able to replace the name of the class that i want to return, however I'm not sure if it'll work, and I dont want to switch editor :)
Hope you guys can help me out,
Joachim
Found the answer, one could use getattr.
x = 6
result = getattr(g_o, 'phase_'+str(x)).Info.SumMsf.value
Thanks anyway - And I'll work on the pictures
Joachim
yesterday, I found a way to simulate something like type-safety in python 3 (and maybe in python 2 ;). For example by writing the following:
def do_stuff(amount: int, name: str, place: str = 'London') -> list:
you can tell your IDE to notify you if you want to set an argument which has not the expected type (giving a string where you would expect an integer). Python itself ignores them, which is totally fine for me.
However, now I want to provide it with exceptions which may be thrown during the process. How can I achieve this? Unfortunately, I don't even know what to search for. Can someone help me out? I want my IDE (PyCharm) to remind me, that in some cases the function I'm using may throw an exception and it would be a nice idea to wrap it in a try-except statement.
I'm only talking about methods written by myself, not external code and it's for documentation only. Unfortunately reStructuredText or epytext do document this, but don't help with the IDE-checks =Y
Thanks in advance
Kenneth
This does not appear to be supported. The proposal that added type hinting, PEP484, says this about exceptions:
No syntax for listing explicitly raised exceptions is proposed. Currently the only known use case for this feature is documentational, in which case the recommendation is to put this information in a docstring.
I've recently started working at a company doing work in Python, and in their code they have a class which defines a handful of functions that do nothing, and return nothing. Code that is pretty much exactly
...
...
def foo(self):
return
I'm really confused as to why anyone would do that, and my manager is not around for me to ask. Would one do this for the sake of abstraction for child classes? A signal that the function will be overridden in the future? The class I'm looking at in particular inherits from a base class that does not contain any of the functions that are returning nothing, so I know that at least this class isn't doing some kind of weird function overriding.
Sometimes, if a class is meant to be used interchangeably with another class in the API, it can make sense to provide functions that don't do much (or anything). Depending on the API though, I would typically expect these functions to return something like NotImplemented.
Or, maybe somebody didn't get enough sleep the night before and forgot what they were typing ... or got called away to a meeting without finishing what they were working on ...
Ultimately, nobody can know the actual reason without having a good knowledge of the code you're working with. Basically -- I'd wait for your boss or a co-worker to come around and ask.
If the functions have meaningful names, then it could be a skeleton for future intended functionality.
As a newbie to Python, I'm finding yields and generators and async functions extremely overwhelming (I've read all the SO questions on the topics and several other various references - still having a hard time connecting all the pieces). I'm used to the descriptive syntax of Objective-C, where everything just tells you what it's doing, rather than trying to connect all the pieces of distinct keywords that you don't know really know how they might work together.
I really liked Python because it was so easy to pick up - for basic things at least. But for more advanced things, the code just doesn't speak to you. It doesn't tell you what it's doing. (Ok maybe I'm just a little frustrated and inexperienced.)
Anyway, I want to make the following function fully async:
#ndb.tasklet
def get_new_statues(friends):
status_list = list()
for friend_dic in friends:
lastStatusDate = #some date
userKey = #some key
query = ndb.gql('SELECT * FROM Statuses WHERE ANCESTOR IS :1 AND date > :2', userKey, lastStatusDate)
qit = query.iter()
while (yield qit.has_next_async()):
status = qit.next()
status_list.append(status.to_dict())
raise ndb.Return(status_list)
I was a little impressed with myself when I wrote this, and was excited that I was able to convert all my code to async in just a couple hours. But I'm being told that the function above isn't async at all. But then in another question I'm being told that yes, what I'm doing is correct.
So what exactly is going on? Does the yield statement here make my code synchronous? How would I modify this to make it async?
(The questions I've asked seem all similar, but the problem is I'm getting more code back as answers rather than an explanation. I'm a human looking for words to understand that can help me make sense of code, not a machine looking for more code to help me understand more code. Everyone is just telling me how or what, no one is telling me why.)
Addendum: I guess the line that's throwing me off the most is: while (yield qit.has_next_async()): As a human reader, I read the words yield, which in your typical usage of the word means "if necessary let something else do something else" and I see the word async, which well means async. So I figured yield + async = magical formula for an asynchronous method, but apparently that's not the case?
Sounds like you don't understand what yield does.
While this may not be entirely accurate, you can generally think of "yield" like "return", except when you call this function again, it continues running from where it last yielded, rather than the beginning of the function.
Since qit.has_next_async() is asynchronous, this function is asynchronous. Every time you call this function, it'll return the value of qit.has_next_function(), and it'll get the next entity. When it's done it'll raise an exception with the result.
For one of my projects I have a python program built around the python cmd class. This allowed me to craft a mini language around sql statements that I was sending to a database. Besides making it far easier to connect with python, I could do things that sql can't do. This was very important for several projects. However, I now need to add in if blocks for greater control flow.
My current thinking is that I will just add two new commands to the language, IF and END. These set a variable which determines whether or not to skip a line. I would like to know if anyone else has done this with the cmd module, and if so, is there a standard method I'm missing? Google doesn't seem to reveal anything, and the cmd docs don't reveal anything either.
For an idea that's similar to what I'm doing, go here. Questions and comments welcome. :)
Hmm, a little more complicated than what I was thinking, though having python syntax would be nice. I debated building a mini language for quite some time before I finally did it. The problem primarily comes in from the external limitations. I have a bunch of "data", which is being generous, to turn into sql. This is based on other "data" that won't pass through. It's also unique to each specific "version" of the problem. Doing straight data to sql would have been my first inclination, but was not practical.
For the curious, I spent a great deal of time going over the mini languages chapter in the art of unix programming, found here.
If I had built the thing in pure python, I wouldn't have had the flexibility I absolutely needed for the problem set.
The limitations of making a "mini language" have become apparent.
Proper languages have a tree-like structure and more complex syntax than cmd can handle easily.
Sometimes it's actually easier to use Python directly than it is to invent your own DSL.
Currently, your DSL probably reads a script-like file of commands.
Because of the way cmd works, your little comments get a string argument, which must be parsed. Then the command gets executed. And, further, each command is a method of the cmd.Cmd subclass.
Here's what you can do.
Each do_foo( self, args ) method becomes a stand-alone callable object. It will follow the Command design pattern. It will do exactly what the method function does now. No less. Exactly the same.
class Foo( object ):
def __init__( self, global_context ):
self.context= global_context
def __call__( self, args ):
... The rest of do_foo ...
Additionally, your existing cmd.Cmd subclass probably maintains some internal state.
All of the self.this and self.that instance variables must be changed to reference
and explicit context object.
class Context( object ): pass
Change self.this or self.that to self.context.this or self.context.that
Now, you can create your context and your various commands.
ctx = Context()
foo= Foo(ctx)
Your script changes syntax slightly. From:
foo argstring
bar argstring
to:
from mylanguage import foo, bar
foo( "argstring" )
bar( "argstring" )
This does Exactly what the CLI does now. No more. No less. Exactly the same. Slightly different syntax.
Now your script is no longer in a DSL that's hard to expand. It's in Python.
Having done that, you can now use Python syntax if statements.
You have the Exact functionality currently implemented in cmd with better syntax.
After examining the problem set some more, I've come to the conclusion that I can leave the minilanguage alone. It has all the features I need, and I don't have the time to rebuild the project from the ground up. This has been an interesting problem and I'm no longer sure I would build another minilanguage if I encountered the same situation. OTOH, it works very well here, and I am loathe to give up the advantages it has conferred.