In Python, Why can a function like pow be called directly, while a function like floor needs to be imported into the module first?

Source: Internet
Author: User
Tags builtin
A beginner in python. I hope you can give me more advice on python. I hope you will give me more comments: I wrote them in the comments answered by @ bhuztez. You can send it to the top layer.

Here, the @ blue big answer is a misunderstanding, and the @ bhuztez big answer is a perfect solution.

For this question, please refer to @ flow memory for the most incisive answer. For details about the internal mechanism of Python, please refer to @ bhuztez for a great deal, for more information about the code, see @ blue.

The Python _ builtin ___ module is completely a runtime item, @ The Code referenced by blue greatly registers the correspondence between the name in the initial _ builtin ___ module and the function pointer during VM initialization; however, the Python (source code to bytecode) compiler does not care about this.
The pow () of Python cannot be compared with the _ builtin_powi () of GCC; the former behavior can be changed at runtime, while the compiler does not regard it as a special thing; the latter is the intrinsic function directly supported by the compiler.

When the initialization is complete, the "pow" in the __builtin _ module maps to the builtin_pow () function. The latter further calls the PyNumber_Power () function to implement the function. cpython/bltinmodule. c at 2.7 · python/cpython · GitHub
The Python source code compiler will compile the ** operator as the BINARY_POWER bytecode instruction, while the Python bytecode interpreter is the BINARY_POWER implementation, which directly calls PyNumber_Power () function (the current binding of "pow" in the _ builtin _ module is not resolved through the symbol ). Cpython/ceval. c at 2.7 · python/cpython · GitHub

In Python code, calling pow () actually requires a symbolic parsing (LOAD_NAME) to find the target and then calling it. The module binding is variable, so we can do the following:

$ pythonPython 2.7.5 (default, Mar  9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> 2 ** 532>>> pow(2, 5)32>>> __builtins__
  
   >>> 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', 'pmod', '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
   
    >>> mypow = pow>>> mypow
    
     >>> __builtins__.pow = lambda x, y: mypow(x, y) - 1>>> pow(2, 5)31>>> 2 ** 532
    
   
  
I have seen blue as a Python expert, and I have come to criticize it. Black magic is the first thing to do here, otherwise some problems will be unclear.

>>> __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 draw a lot of truth, but it is useless for this problem.

The real reason is that this is what the Python designers like, because the designers can make the floor ready for direct calls. Pow () is a built-in function, so it does not need to be imported.
Floor () Is the function of the math module. You must import math (from math import floor) before using it.
Note that the math module also has a pow (), which is somewhat different from the pow () of built-in.
Take a look at the official documentation:
2. Built-in Functions
And
9.2. math-Mathematical functions ------------------------------- Update ------------------
Let's see the explanation of @ redna xelafx. My understanding is biased. Let's move it to the front so that more people can see it.









As mentioned above, pow is a Builtin function, which is directly supported by the compiler. You can refer to this link to learn about the differences between Built in function and common function: Intrinsic function

Next I will show you how to implement Builtin Pow in Python. First in Python, the Built in function is defined in the Bltinmodules. c file. The specific code is as follows:

static PyMethodDef builtin_methods[]
Pow seems to be more common than floor. It is more suitable for building-in. The essence of this problem is: why are some functions in _ builtins __while others? In addition to the scope, the reason for this scope may also be that Pow is int, floor may be float. Although there is no type in python.

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.