This question already has answers here:
Finding the source code for built-in Python functions?
(8 answers)
Closed 2 years ago.
I just want to take a look builtin function code. Because I'm a beginner on Python and I think some source code can give me very useful instruction. I made some test code as follows and I did 'Ctrl+click' on 'join' with PyCharm IDE.
zip_command = "zip -r {0} {1}".format(target, ' '.join(source))
And then cursor points builtin.py module's join function, but there is empty code. There is only an explanation. How does this operate? Where is the real code?
def join(self, ab=None, pq=None, rs=None): # real signature unknown; restored from __doc__
"""
Concatenate any number of strings.
The string whose method is called is inserted in between each given string.
The result is returned as a new string.
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
"""
pass
'builtin.py' path is : C:\Users\admin.PyCharmCE2019.3\system\python_stubs\542861396\builtins.py
str.join() is implemented in C, specifically in unicodeobject.c at unicode_join.
"How can I find the source code for builtin functions and objects" doesn't have a great answer. See Finding the source code for built-in Python functions? for some overviews of how CPython is laid out. While some of Python's standard library is written in Python (this sits in lib/), you'll find that builtins and some performance-sensitive components of the standard library have a C implementation. The former resides in objects/, and the latter in modules/.
Related
This question already has answers here:
What does the "at" (#) symbol do in Python?
(14 answers)
Closed 4 years ago.
I'm trying to understand what does this operator #, uses in python.
I saw something about matrix multipication , but this is sure not the case,I'll give an example:
#property
def num_reserved_ids(self):
return 0
Or:
#registry.register_problem()
class LibrispeechNoisy(Librispeech):
Last one:
#registry.register_hparams
def transformer_librispeech_tpu_v1():
"""HParams for training ASR model on Librispeech on TPU v1."""
hparams = transformer_librispeech_v1()
update_hparams_for_tpu(hparams)
Registry is another file that is used in the program.register_hparams is a function inside.
Don't know what "property" is, but even registry that I know what it is, I can't understand the purpose of the operator :#, I'm a bit slow, sorry for that :/ ..
If anyone wants to look for some more code you can check tensor2tensor library:
https://github.com/tensorflow/tensor2tensor/tree/master/tensor2tensor
I think what you are looking for is called PythonDecorators
Here is the Wiki For Python Decorators
A Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (and possibly classes in a future version). This supports more readable applications of the DecoratorPattern but also other uses as well.
The best way to understand them is from Corey Schafer's Video on Python Decorators
This question already has answers here:
New operators in Python
(4 answers)
Closed 5 years ago.
So I am developing a class for vectorial calculations, and I overwrote the __mul__(self, b) function to do a Scalarproduct. Now whenever I write A * B it calculates as I want it to. So I would like to do the same with an x for the Crossproduct. Sadly there is no default x operator in python, it would probably just annoy you. But is there a way to create your own operator which ONLY works for my own class, but can otherwise be used in a code aswell (as a variable definition I mean)? Or maybe define *** as an operator?
Instead of just define an operator, you can write your own interpreter for your own language inside python. Basically, you need to create 4 modules
parser
environment
eval
repl
Then you can program with your own language within python.
read Peter Novig's article for a detailed example of a python LISP interpreter
This question already has answers here:
Understanding the dot notation in python
(2 answers)
Closed 5 years ago.
I am struggling to explain the use of the dot. I thought it might be another way of multiplying variables but get an error when I try run such a code.
I can't explain what it is doing exactly, take this code for example:
import random
for i in range(100):
value = random.randint(1, 10)
print(value)
I understand what the code does but in line 3 I am confused by random.randint what is the dot doing here? randint is not defined or imported so how does the program know what is being asked of it?
An brief explanation of the above code would be nice but a good explanation of the use of the dot in python would be appreciated.
You use dot for 3 main reasons:
Accessing members of a module: a module is simply a python file, and members can be variables, functions, classes and so on.
Accessing modules within a package: a package is a directory containing a__init__ module. Some packages are nested and contain inner packages. You have to reach the innermost and then the module. For both you use dot syntax.
And at last, accessing members of a class, for example method (functions) fields (variables) and so on.
In your above code random is a Python module and you are accessing its function randint.
In Python, the dot operator is used to access attributes of objects.
In your example, think of the module imported "random" as an object which has various functions like randint, shuffle, etc
So, when you say "random.randint()", you are accessing the function "randint" from the module "random"
The dot here is used to resolve scope. The randint() function is inside the random module. The dot here tells the interpreter where to look for the named function/ data member.
Apart from this, the dot is also used to access functions and data members from an object reference.
For example:
op = object.function()
Here, the function() is being accessed using the reference of object.
Also you can access inner modules using . like this:
import module.submodule
More information here: https://www.codecademy.com/en/forum_questions/5170307264a7402d9a0012f5
random is a package and randint() is its method. Dot notation here works just like it does in any other language. It's used to access the
randint property of random module.
This question already has answers here:
What's the difference between a method and a function?
(41 answers)
Closed 7 years ago.
I am a little confused about functions in Python, and how they are classified. For one, we have functions like print(), that simply encode some instructions and act on input. But also, we have functions like 'str'.capitalize(), that can only act when they have an "executor" attached to them. This might not be a well-informed question, but what are the differences between these forms, and how are they classified?
print() is a function in python3 (in python2 it was a statement), and capitalize() is a method.
Please take a look at this answer to clear things up a little bit.
Python is a multi paradigm language that you can write structural and object oriented. Python has built-in functions and built-in classes; for example when you use sequence of characters between two quotation mark (') you instantiate string class.This instance called object. Objects may contain functions or/and other objects. you can access internal functions or object with DOT.
Python is object oriented. This means we have "objects", which basically enclose their own data, and have their own methods. a String is an example of an object. Another example would be if you have a Person object. You can't just do walk(), you have to do Miles.walk(). You could try walk(Miles). But not everything can walk, so we make the function walk() specific to Person objects.
So yes, Python creators could have made capitalize('str') legal, but they decided to make the capitalize function specific to String objects.
print() is a built in function, you can check that like below..
>>> type(print)
<class 'builtin_function_or_method'>
>>> hasattr(print, '__call__')
True
But capitalize() is method of a str class, you can only use this by using string objects.
>>> hasattr('string', 'capitalize')
True
This question already has answers here:
How do I execute a string containing Python code in Python?
(14 answers)
Closed 9 years ago.
I want to do following. Script has some python code as a string (saved in a variable) and is it possible to run that code ?
Well, I know one way, writing that string to a file & running it, but I don't want that. Without creating any extra file, is it possible to run it ?
Here is a example :
let's assume my python file has following content
#this is a main python file
content = ''' print 'hello!'
print 'this is from sub python code' '''
print 'from main python'
The content string has a python code & I want to run it. Is it possible ?
Hope I am clear. Thank you !
I'll say this up front: This is a terrible idea, and depending on the source of the string a serious security risk.
That disclaimer out of the way, python has an exec function that executes a string containing python code. For example:
exec("print 2+2")
Edit: I originally used eval in my answer, which is useful for evaluating individual expressions, while exec can be used for more general execution of arbitrary python code in a string.
Relevant docs:
http://docs.python.org/2/reference/simple_stmts.html#exec
http://docs.python.org/2/library/functions.html#eval
Well you could use eval:
eval(content)
And that will do what you want, however it's not recommended, especially if someone else controls the content of content - it's not too hard to hack into your system if you have eval
Did you tried with exec method as per documentation that should do
exec "print 'Hello, World!'"
Depending on the code you are trying to execute, you may use eval() or exec. There are several differences between these two options:
eval() does what it should: it evaluates an expression and returns a value, not executes code. That means you may call functions, do some arithmetic, even use list comprehensions, generators or lambdas, but not execute python statements that aren't expressions (e.g. if, for, print in Python 2; however, in Python 3 print is a function and is ok).
eval() accepts more parameters than just a string. It gets locals and globals, two dictionaries, defining the scope environment. You may make evaluation nearly (though not really) safe for untrusted strings if you fill and pass these dictionaries to eval(). Probably, you may even redefine builtins by properly setting __builtins__ in globals. http://docs.python.org/2/library/functions.html#eval
exec also accepts globals and locals. See http://docs.python.org/2/reference/simple_stmts.html#exec . And it may execute everything. And it is virtually impossible to make it even relatively safe.