In Python, why would a function like POW be called directly, and a function like floor should import the module first?

Source: Internet
Author: User
Tags builtin mathematical functions
Python novice, hope the great gods to teach more

Reply content:

It was written in a comment that @bhuztez big answer. Forget it or send it to the top floor.

Here @ Blue Big answer really misunderstood some, @bhuztez big answer is completely positive solution.

This question, to see the most incisive answer please see @flow memory greatly, to go deep into the internal mechanism of Python see @bhuztez big, to see the specific code see @ Blue greatly revised the answer.

Python's __builtin___ module is entirely a runtime thing, and the code that is referenced in blue is actually registering the corresponding relationship between the name in the initial __builtin___ module and the function pointer when the VM is initialized. However, Python's (source-to-bytecode) compiler does not care about this.
Python's pow () cannot be compared with __builtin_powi () like GCC, whose behavior can be changed at run time, and the compiler does not treat it as a special thing, while the latter is the intrinsic function that the compiler supports directly.

When the initial initialization is good, the "POW" in the __builtin__ module is mapped to the Builtin_pow () function, which further calls the Pynumber_power () function to implement the function; cpython/bltinmodule.c at 2.7 · Python/cpython GitHub
The python source compiler compiles the * * operator into a binary_power bytecode instruction, while the Python bytecode interpreter for Binary_power is the direct call to the Pynumber_power () function (without symbolic parsing __ The current binding of "POW" in the builtin__ module). CPYTHON/CEVAL.C at 2.7 · Python/cpython GitHub

Since the call to POW in Python code () actually has to go through symbolic parsing (load_name) to find the target and then call the past, and the binding of the module is mutable, you can do something like this:
$ pythonPython 2.7.5 (default, Mar  9  the,  A: the: to) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0. the)]  on DarwinType "Help", "Copyright", "Credits" or "License"  for  More Information.>>> 2 ** 5 +>>> POW(2, 5) +>>> __builtins__<Module ' __builtin__ ' (built-inch)>>>> dir(__builtins__)[' Arithmeticerror ', ' Assertionerror ', ' Attributeerror ', ' Baseexception ', ' Buffererror ', ' byteswarning ', ' deprecationwarning ', ' Eoferror ', ' ellipsis ', ' EnvironmentError ', ' Exception ', ' False ', ' Floatingpointerror ', ' futurewarning ', ' Generatorexit ', ' IOError ', ' Importerror ', ' importwarning ', ' Indentationerror ', ' Indexerror ', ' Keyerror ', ' Keyboardinterrupt ', ' Lookuperror ', ' Memoryerror ', ' Nameerror ', ' None ', ' notimplemented ', ' Notimplementederror ', ' OSError ', ' Overflowerror ', ' pendingdeprecationwarning ', ' Referenceerror ', ' RuntimeError ', ' runtimewarning ', ' StandardError ', ' Stopiteration ', ' SyntaxError ', ' syntaxwarning ', ' Systemerror ', ' Systemexit ', ' Taberror ', ' True ', ' TypeError ', ' Unboundlocalerror ', ' Unicodedecodeerror ', ' Unicodeencodeerror ', ' Unicodeerror ', ' Unicodetranslateerror ', ' unicodewarning ', ' userwarning ', ' ValueError ', ' Warning ', ' Zerodivisionerror ', '_', ' __debug__ ', ' __doc__ ', ' __import__ ', ' __name__ ', ' __package__ ', ' ABS ', ' All ', ' any ', ' Apply ', ' basestring ', ' bin ', ' bool ', ' buffer ', ' ByteArray ', ' bytes ', ' callable ', ' CHR ', ' Classmethod ', ' CMP ', ' Coerce ', ' Compile ', ' Complex ', ' copyright ', ' credits ', ' delattr ', ' Dict ', ' dir ', ' Divmod ', ' Enumerate ', ' eval ', ' execfile ', ' exit ', ' file ', ' Filter ', ' float ', ' format ', ' Frozenset ', ' GetAttr ', ' Globals ', ' hasattr ', ' Hash ', ' Help ', ' Hex ', ' id ', ' input ', ' int ', ' Intern ', ' Isinstance ', ' Issubclass ', ' iter ', ' Len ', ' License ', ' list ', ' locals ', ' Long ', ' map ', ' Max ', ' Memoryview ', ' min ', ' Next ', ' object ', ' Oct ', ' Open ', ' Ord ', ' POW ', ' print ', ' property ', ' Quit ', ' Range ', ' Raw_input ', ' reduce ', ' Reload ', ' repr ', ' reversed ', ' Round ', ' Set ', ' SetAttr ', ' Slice ', ' sorted ', ' Staticmethod ', ' str ', ' Sum ', ' Super ', ' tuple ', ' type ', ' UNICHR ', ' Unicode ', ' VARs ', ' xrange ', ' Zip ']>>> POW<built-inch function POW>>>> Mypow = POW>>> Mypow<built-inch function POW>>>> __builtins__.POW = Lambda x, y: Mypow(x, y) - 1>>> POW(2, 5) to>>> 2 ** 5 +
See the blue to impersonate a python expert, special to criticize. Here is the first black magic, or some problems will not be explained clearly.

>>> __builtins__
  
   
    
   >>> pow(2,2)4>>> __builtins__ = None>>> pow(2,2)Traceback (most recent call last):  File "
   
    
     
    ", line 1, in 
    
     
      
     NameError: name 'pow' is not defined>>> __builtins__ = {'pow':1}>>> pow1>>>
    
     
   
    
  
   
Many people make a lot of sense, but there is no egg for this problem.

The real reason is that this is the Python designer's preference, because the designer can completely make floor also can be made directly call. Pow () is a built-in function, so you don't need to import it.
Floor () is the function of the math module and needs to be import math (from the math import floor) before it can be used.
Note, however, that there is also a POW () in the math module, which is somewhat different from the built-in POW ().
Take a look at the official documentation:
2. Built-in Functions
And
9.2. math-mathematical functions -------------------------------Update------------------
Can see @RednaxelaFX explanation, my understanding is biased, or put in front, let more people see









It is clear that the POW is the BUILTIN function, and the BUILTIN function is directly supported by the compiler, you can refer to this link to understand the difference between the built in function and the normal function: intrinsic function

I'm going to start by talking about how the Builtin POW is implemented in Python. First in Python, the Built in function is defined in the BLTINMODULES.C file, and the specific code is:

staticPyMethodDefbuiltin_methods[]
POW seems to be more commonly used as a build-in than floor. The essence of this problem is: why are some functions in __builtins__ and others not? In addition to the scope reason, the reason for this scope, there is another possibility is the POW is an int, floor may be float. There is no type in Python, though.
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.