Naming conflict with built-in function
Use __builtins__.list
or __builtins__['__list__']
(depending on context), or simply delete list
again (del list
).
No imports needed:
>>> __builtins__.list
<type 'list'>
The presence of __builtins__
is a CPython implementation detail; in the __main__
module it is a module, everywhere else it is the module __dict__
dictionary. Jython, IronPython and PyPy may opt to not make this available at all. Use the __builtin__
module for those platforms, or for Python 3 compatible implementations, the builtins
module:
>>> import __builtin__
>>> __builtin__.list
<type 'list'>
Variable name conflicts with built-in function
You can say Swift.type(of:whatever)
.
Is it OK to re-use the names of Python's built-in functions?
This turned into a bit of a list of different options, rather than a straight answer. However, two concepts are paramount:
- Users should be able to replace
range
andxrange
if they explicitly choose to; but - Users should not be able to implicitly/accidentally replace
range
andxrange
;
it should always be clear to readers of their code where the built-ins are used and where the replacements are used.
For that reason, all options I've outlined below prevent a wildcard import (from inclusive import *
) from shadowing the built-ins. Which is the best option for you depends on whether you see replacing the built-ins as a primary or secondary use of your module. Will users generally want to replace the built-ins, or use them alongside each other?
In your position, I think I would do the following:
inclusive.py
:
"""Inclusive versions of range and xrange."""
__all__ = [] # block 'from inclusive import *'
old_range, old_xrange = range, xrange # alias for access
def range(...): # shadow the built-in
...
def xrange(...): # ditto
...
This allows users to either:
import inclusive
and accessinclusive.range
andinclusive.xrange
;from inclusive import range, xrange
, clearly replacing the built-ins without any unpleasant side effects; orfrom inclusive import range as irange, xrange as ixrange
to use the built-in and replacement versions alongside one another.
Defining __all__
as an empty list means that from inclusive import *
won't quietly shadow the built-ins.
If you really wanted to, you could add:
irange, ixrange = range, xrange
to the end of inclusive.py
and modify the __all__
definition to:
__all__ = ['irange', 'ixrange']
Now the users have two additional choices:
from inclusive import irange, ixrange
(slightly simpler than manually aliasing the functions as in option 3 above); andfrom inclusive import *
(same result as above, still no implicit shadowing of built-ins).
Of course, you could go completely the other way - name your own versions irange
and ixrange
, then if the user really wants to replace the built-ins they would have to:
from inclusive import irange as range, ixrange as xrange
This doesn't require you to define __all__
to avoid a wildcard import shadowing the built-ins.
Conflicting variable and function names in python
In Python, functions are data, and typing is dynamic. This means that the following lines are valid Python:
def func(x):
return x + 3
func = 3
func
is now an int. The original function func
is no longer referenced. The fact that func
was originally a function doesn't have any bearing on what types of data can be assigned to it in the future. (This is what "dynamic typing" means.)
Therefore, since there's no static typing, and "function" is a valid data type, it wouldn't make sense for the Python interpreter to distinguish between a function and a piece of data referenced by the same name. Therefore, within a given scope, there's no way to use the same unqualified variable name to mean two different things.
In your particular case, if the code in your xplus1
function meant anything, it would mean "compute the value of xplusy(x,1)
and assign that value to the variable xplusy
-- thereby losing the reference to the function xplusy
." However, within the scope of a function, the interpreter won't let you make an assignment to a variable outside of that scope, so it assumes that by writing an assignment statement, you're introducing a new local variable xplusy
. The local variable, however, hasn't been defined yet, so your attempt to call it, xplusy(x,1)
, fails. The globally defined function is not called as a fall-back because, again, you can't have two unqualified names be identical and point to different data in the same scope.
Another example demonstrating the "no duplication of variable names within one scope" rule (which I actually only just discovered while playing around with the prompt in my attempt to construct this answer):
>>> def f1():
... a = xplusy(3,4)
... xplusy = 5
... print xplusy
...
>>> f1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f1
UnboundLocalError: local variable 'xplusy' referenced before assignment
>>> def f1():
... a = xplusy(3,4)
... print a
...
>>> f1()
7
This demonstrates that it really is the scope, not the statement that requires unique names.
EDIT: This is a really cool post that explains this and other scoping-related behavior: http://me.veekun.com/blog/2011/04/24/gotcha-python-scoping-closures/
Parameter naming conflict with Python
Assuming that the Client is defined something like:
def list(**params):
# some stuff with params
print(params.get('from'))
print(params.get('limit'))
Then indeed calling list(from=5)
will give a syntax error. But as the function packs all arguments to a kwargs dict and treats them as string keys, we can do the same thing on the other side - unpack a dict to the function arguments:
list(**{'from': 5, 'limit': 10})
Will indeed print:
5
10
Modules naming conflict
Modules change how you access code from multiple files, but that's all they do. They do not (for the most part) affect the fundamental nature of C++ as a language.
C++ already has a tool for managing name conflicts between disparate libraries and source locations: namespaces. As such, C++ modules have no need to solve a problem that has adequately already been resolved.
GCC function name conflict
GCC is playing tricks on you due to the interplay of the following:
abs
is a built-in function;- you're declaring
abs
to returnunsigned int
while the standard (and built-in)abs
returnssigned int
.
Try compiling with gcc -fno-builtin
; on my box, that gives the expected result of 1
. Compiling without that option but with abs
declared as returning signed int
causes the program to print 2
.
(The real solution to this problem is to not use library identifiers for your own functions. Also note that you shouldn't be printing an unsigned int
with %d
.)
How do I resolve name conflict in MATLAB?
Disclaimer: Please, please, please, do not do this.
Assuming that your own stack.m
is only in the search path because it is in the current folder, then the easiest fix is to create some dummy subfolder, navigate to it, execute Matlabs stack
function (which is the only stack
in the current searchpath) and navigate back.
Here I have exemplified it with magic
:
function a= magic
n=5;
cd dummy
a= magic(n);
cd ..
where dummy
is the name of the subfolder.
How to avoid function name conflict in a C library?
If I was using C++, I could just add
::
to resolve library conflict.
But you are using C++. Just because you include a header that contains C API, it doesn't mean the translation unit stops being a C++ translation unit. If the header is designed to play nice with C++, then its contents are still put in the global namespace (and unistd.h
can be included in a C++ translation unit just fine).
This means ::read
will resolve to the C library function declared by unistd.h
. You can use it just fine within Serial::read
. Those are different functions to a C++ compiler. Just disambiguate the name inside the member function, since unqualified name lookup would have to find the member inside class scope.
Howto resolve a function name conflict when compiling a kernel module
The problem will not be in your object file as macros have file-scope and are replaced by the preprocessor. Thus after being compiled, the macro no longer exists as far as your nivxi.o
file is concerned.
The issue is probably in your mutex.h
file. I would look at the top and you will likely see an #include <lockdep.h>
line. Thus once the preprocessor gets down to your function definition, it treats mutex_acquire
as a token to be replaced (with the wrong number of arguments).
The easiest way to solve your problem will be to #undef mutex_acquire
and #undef mutex_release
at the beginning of mutex.h
. This will prevent the preprocessor from replacing the tokens in your mutex.h
. Since defines have file-scope, you don't need to worry about this propagating beyond your application
Related Topics
What Is the Maximum Float in Python
Selenium: Firefoxprofile Exception Can't Load the Profile
Improper Use of _New_ to Generate Class Instances
How to Set Window Size in Selenium Chrome Python
How to Use Selenium with Python
Record Speakers Output with Pyaudio
How to Change the Python Version in Visual Studio Code
How to Add a Custom Ca Root Certificate to the Ca Store Used by Pip in Windows
What Is the Most Efficient Way to Get First and Last Line of a Text File
How to Run an Ipython Magic from a Script (Or Timing a Python Script)
Pyqt4 Wait in Thread for User Input from Gui
Creating a Bat File for Python Script
Typeerror: Worker() Takes 0 Positional Arguments But 1 Was Given
How to Delete All Blank Lines in the File with the Help of Python
Running Interactive Commands in Paramiko
Encode and Assemble Multiple Features in Pyspark
Python String 'In' Operator Implementation Algorithm and Time Complexity